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.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -15,6 +15,34 @@
<button id="bag-toggle" type="button">Bag</button>
<button id="leave" type="button">Leave world</button>
</div>
<button id="settings-toggle" type="button" hidden title="Settings" aria-label="Settings">⚙</button>
<aside id="settings-panel" hidden>
<header>
<h2>Settings</h2>
<button id="settings-close" type="button">Close</button>
</header>
<section class="settings-group">
<h3>Viewing distance</h3>
<div class="settings-options">
<button type="button" data-graphics-key="viewDistance" data-graphics-value="long">Long</button>
<button type="button" data-graphics-key="viewDistance" data-graphics-value="short">Short</button>
</div>
</section>
<section class="settings-group">
<h3>Lighting</h3>
<div class="settings-options">
<button type="button" data-graphics-key="lighting" data-graphics-value="soft">Soft</button>
<button type="button" data-graphics-key="lighting" data-graphics-value="simple">Simple</button>
</div>
</section>
<section class="settings-group">
<h3>Bloom</h3>
<div class="settings-options">
<button type="button" data-graphics-key="bloom" data-graphics-value="on">On</button>
<button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
</div>
</section>
</aside>
<div id="toast-stack" aria-live="polite"></div>
<div id="world-tooltip" hidden></div>
<aside id="bag-panel" hidden>
@@ -338,6 +366,61 @@
</section>
</aside>
<div id="bounty-backdrop" class="modal-backdrop" hidden></div>
<aside id="bounty-panel" hidden>
<header>
<h2>Bounty Office</h2>
<button id="bounty-close" type="button">Close</button>
</header>
<div class="bounty-tabs" role="tablist">
<button type="button" class="bounty-tab active" data-tab="place" role="tab">Place / raise</button>
<button type="button" class="bounty-tab" data-tab="mine" role="tab">My bounty</button>
</div>
<section class="bounty-pane" data-pane="place">
<div class="bounty-search-row">
<label>First <input id="bounty-search-first" autocomplete="off" spellcheck="false"></label>
<label>Last <input id="bounty-search-last" autocomplete="off" spellcheck="false"></label>
<button id="bounty-search" type="button">Search</button>
</div>
<div class="bounty-target">
<div id="bounty-preview"></div>
<div>
<p id="bounty-target-label">No target selected.</p>
<p id="bounty-target-amount" class="hint"></p>
</div>
</div>
<label class="bounty-amount-label">Coins to add
<input id="bounty-amount" type="number" min="1" step="1" value="100">
</label>
<button id="bounty-raise" type="button">Add to bounty</button>
<p id="bounty-status" class="hint"></p>
</section>
<section class="bounty-pane" data-pane="mine" hidden>
<p class="hint">Coin currently on your head:</p>
<p id="bounty-my-amount" class="bounty-my-amount">None</p>
</section>
</aside>
<div id="barber-backdrop" class="modal-backdrop" hidden></div>
<aside id="barber-panel" hidden>
<header>
<h2>Barber</h2>
<button id="barber-close" type="button">Close</button>
</header>
<div class="hair-controls">
<canvas data-hair-preview width="64" height="96" aria-label="Hair preview"></canvas>
<label>Hair
<select data-hair-style></select>
</label>
<label>Hue <input data-hair-hue type="range" min="0" max="360" value="30"></label>
<label>Saturation <input data-hair-saturation type="range" min="0" max="100" value="55"></label>
<label>Darkness <input data-hair-darkness type="range" min="0" max="100" value="45"></label>
<span data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
</div>
<button id="barber-apply" type="button">Apply</button>
<p id="barber-status" class="hint"></p>
</aside>
<div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
<aside id="cauldron-pick-panel" hidden>
<header>
@@ -372,6 +455,7 @@
<h2 id="inspect-name">Player</h2>
<button id="inspect-close" type="button">Close</button>
</header>
<p id="inspect-bounty" class="hint" hidden></p>
<p id="inspect-error" class="error"></p>
<div id="inspect-action"></div>
</div>
@@ -386,21 +470,40 @@
<h1>Tile MMO</h1>
<p id="status">Connecting…</p>
<p id="error" class="error"></p>
<form id="create-form">
<label>First name <input id="first-name" required></label>
<label>Last name <input id="last-name" required></label>
<label>Sex
<select id="sex">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</label>
<button type="submit">Create character</button>
</form>
<div id="character-list"></div>
<button id="create-character-open" type="button">Create Character</button>
<p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
</section>
</div>
<div id="create-backdrop" class="modal-backdrop" hidden></div>
<aside id="create-panel" hidden>
<header>
<h2>Create character</h2>
<button id="create-close" type="button">Close</button>
</header>
<p id="create-error" class="error"></p>
<form id="create-form">
<label>First name <input id="first-name" required></label>
<label>Last name <input id="last-name" required></label>
<label>Sex
<select id="sex">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</label>
<div id="create-hair" class="hair-controls">
<canvas id="create-hair-preview" data-hair-preview width="64" height="96" aria-label="Character preview"></canvas>
<label>Hair
<select id="create-hair-style" data-hair-style></select>
</label>
<label>Hue <input id="create-hair-hue" data-hair-hue type="range" min="0" max="360" value="30"></label>
<label>Saturation <input id="create-hair-saturation" data-hair-saturation type="range" min="0" max="100" value="55"></label>
<label>Darkness <input id="create-hair-darkness" data-hair-darkness type="range" min="0" max="100" value="45"></label>
<span id="create-hair-swatch" data-hair-swatch class="hair-swatch" aria-hidden="true"></span>
</div>
<button type="submit">Create & play</button>
</form>
</aside>
<script src="/framework/framework.js"></script>
<script type="module" src="/src/play/main.js"></script>
</body>
@@ -15,6 +15,34 @@ <button id="bag-toggle" type="button">Bag</button> <button id="bag-toggle" type="button">Bag</button> <button id="leave" type="button">Leave world</button> <button id="leave" type="button">Leave world</button> </div> </div> <button id="settings-toggle" type="button" hidden title="Settings" aria-label="Settings">⚙</button> <aside id="settings-panel" hidden> <header> <h2>Settings</h2> <button id="settings-close" type="button">Close</button> </header> <section class="settings-group"> <h3>Viewing distance</h3> <div class="settings-options"> <button type="button" data-graphics-key="viewDistance" data-graphics-value="long">Long</button> <button type="button" data-graphics-key="viewDistance" data-graphics-value="short">Short</button> </div> </section> <section class="settings-group"> <h3>Lighting</h3> <div class="settings-options"> <button type="button" data-graphics-key="lighting" data-graphics-value="soft">Soft</button> <button type="button" data-graphics-key="lighting" data-graphics-value="simple">Simple</button> </div> </section> <section class="settings-group"> <h3>Bloom</h3> <div class="settings-options"> <button type="button" data-graphics-key="bloom" data-graphics-value="on">On</button> <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button> </div> </section> </aside> <div id="toast-stack" aria-live="polite"></div> <div id="toast-stack" aria-live="polite"></div> <div id="world-tooltip" hidden></div> <div id="world-tooltip" hidden></div> <aside id="bag-panel" hidden> <aside id="bag-panel" hidden>@@ -338,6 +366,61 @@ </section> </section> </aside> </aside> <div id="bounty-backdrop" class="modal-backdrop" hidden></div> <aside id="bounty-panel" hidden> <header> <h2>Bounty Office</h2> <button id="bounty-close" type="button">Close</button> </header> <div class="bounty-tabs" role="tablist"> <button type="button" class="bounty-tab active" data-tab="place" role="tab">Place / raise</button> <button type="button" class="bounty-tab" data-tab="mine" role="tab">My bounty</button> </div> <section class="bounty-pane" data-pane="place"> <div class="bounty-search-row"> <label>First <input id="bounty-search-first" autocomplete="off" spellcheck="false"></label> <label>Last <input id="bounty-search-last" autocomplete="off" spellcheck="false"></label> <button id="bounty-search" type="button">Search</button> </div> <div class="bounty-target"> <div id="bounty-preview"></div> <div> <p id="bounty-target-label">No target selected.</p> <p id="bounty-target-amount" class="hint"></p> </div> </div> <label class="bounty-amount-label">Coins to add <input id="bounty-amount" type="number" min="1" step="1" value="100"> </label> <button id="bounty-raise" type="button">Add to bounty</button> <p id="bounty-status" class="hint"></p> </section> <section class="bounty-pane" data-pane="mine" hidden> <p class="hint">Coin currently on your head:</p> <p id="bounty-my-amount" class="bounty-my-amount">None</p> </section> </aside> <div id="barber-backdrop" class="modal-backdrop" hidden></div> <aside id="barber-panel" hidden> <header> <h2>Barber</h2> <button id="barber-close" type="button">Close</button> </header> <div class="hair-controls"> <canvas data-hair-preview width="64" height="96" aria-label="Hair preview"></canvas> <label>Hair <select data-hair-style></select> </label> <label>Hue <input data-hair-hue type="range" min="0" max="360" value="30"></label> <label>Saturation <input data-hair-saturation type="range" min="0" max="100" value="55"></label> <label>Darkness <input data-hair-darkness type="range" min="0" max="100" value="45"></label> <span data-hair-swatch class="hair-swatch" aria-hidden="true"></span> </div> <button id="barber-apply" type="button">Apply</button> <p id="barber-status" class="hint"></p> </aside> <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div> <div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div> <aside id="cauldron-pick-panel" hidden> <aside id="cauldron-pick-panel" hidden> <header> <header>@@ -372,6 +455,7 @@ <h2 id="inspect-name">Player</h2> <h2 id="inspect-name">Player</h2> <button id="inspect-close" type="button">Close</button> <button id="inspect-close" type="button">Close</button> </header> </header> <p id="inspect-bounty" class="hint" hidden></p> <p id="inspect-error" class="error"></p> <p id="inspect-error" class="error"></p> <div id="inspect-action"></div> <div id="inspect-action"></div> </div> </div>@@ -386,21 +470,40 @@ <h1>Tile MMO</h1> <h1>Tile MMO</h1> <p id="status">Connecting…</p> <p id="status">Connecting…</p> <p id="error" class="error"></p> <p id="error" class="error"></p> <form id="create-form"> <label>First name <input id="first-name" required></label> <label>Last name <input id="last-name" required></label> <label>Sex <select id="sex"> <option value="male">Male</option> <option value="female">Female</option> </select> </label> <button type="submit">Create character</button> </form> <div id="character-list"></div> <div id="character-list"></div> <button id="create-character-open" type="button">Create Character</button> <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p> <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p> </section> </section> </div> </div> <div id="create-backdrop" class="modal-backdrop" hidden></div> <aside id="create-panel" hidden> <header> <h2>Create character</h2> <button id="create-close" type="button">Close</button> </header> <p id="create-error" class="error"></p> <form id="create-form"> <label>First name <input id="first-name" required></label> <label>Last name <input id="last-name" required></label> <label>Sex <select id="sex"> <option value="male">Male</option> <option value="female">Female</option> </select> </label> <div id="create-hair" class="hair-controls"> <canvas id="create-hair-preview" data-hair-preview width="64" height="96" aria-label="Character preview"></canvas> <label>Hair <select id="create-hair-style" data-hair-style></select> </label> <label>Hue <input id="create-hair-hue" data-hair-hue type="range" min="0" max="360" value="30"></label> <label>Saturation <input id="create-hair-saturation" data-hair-saturation type="range" min="0" max="100" value="55"></label> <label>Darkness <input id="create-hair-darkness" data-hair-darkness type="range" min="0" max="100" value="45"></label> <span id="create-hair-swatch" data-hair-swatch class="hair-swatch" aria-hidden="true"></span> </div> <button type="submit">Create & play</button> </form> </aside> <script src="/framework/framework.js"></script> <script src="/framework/framework.js"></script> <script type="module" src="/src/play/main.js"></script> <script type="module" src="/src/play/main.js"></script></body></body>@@ -0,0 +1,226 @@
/**
* Temporary unique 16×16 herb sprites under client/assets/herbs/.
* One PNG per herbId — shared by world nodes and inventory icons.
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { HERB_ORDER, HERB_DEFINITIONS } from "../../shared/definitions/herbs.js";
const SIZE = 16;
const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/herbs");
function crcTable ()
{
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++)
{
let c = n;
for (let k = 0; k < 8; k++)
{ c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
table[n] = c >>> 0;
}
return table;
}
const CRC_TABLE = crcTable();
function crc32 (buf)
{
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++)
{ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
return (c ^ 0xffffffff) >>> 0;
}
function chunk (type, data)
{
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length);
const typeBuf = Buffer.from(type, "ascii");
const crcBuf = Buffer.alloc(4);
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
return Buffer.concat([len, typeBuf, data, crcBuf]);
}
function encodePng (rgba)
{
const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
for (let y = 0; y < SIZE; y++)
{
const row = y * (SIZE * 4 + 1);
raw[row] = 0;
for (let x = 0; x < SIZE; x++)
{
const i = (y * SIZE + x) * 4;
const o = row + 1 + x * 4;
raw[o] = rgba[i];
raw[o + 1] = rgba[i + 1];
raw[o + 2] = rgba[i + 2];
raw[o + 3] = rgba[i + 3];
}
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(SIZE, 0);
ihdr.writeUInt32BE(SIZE, 4);
ihdr[8] = 8;
ihdr[9] = 6;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk("IHDR", ihdr),
chunk("IDAT", deflateSync(raw, { level: 9 })),
chunk("IEND", Buffer.alloc(0))
]);
}
function setPx (rgba, x, y, color)
{
if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
{ return; }
const i = (y * SIZE + x) * 4;
rgba[i] = color[0];
rgba[i + 1] = color[1];
rgba[i + 2] = color[2];
rgba[i + 3] = color[3];
}
function hashString (text)
{
let h = 2166136261;
for (let i = 0; i < text.length; i++)
{
h ^= text.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
/** Distinct leaf/flower palettes keyed by herb identity. */
function paletteFor (herbId, tier)
{
const h = hashString(herbId);
const hue = (h % 360);
const sat = 0.35 + ((h >>> 8) % 40) / 100;
const lit = 0.28 + (tier - 1) * 0.04 + ((h >>> 16) % 20) / 100;
const flower = hsl(hue, sat, lit);
const leaf = hsl((hue + 100) % 360, 0.45, 0.32);
const stem = hsl((hue + 90) % 360, 0.35, 0.22);
const accent = hsl((hue + 40) % 360, Math.min(0.85, sat + 0.2), Math.min(0.7, lit + 0.15));
return { flower, leaf, stem, accent };
}
function hsl (h, s, l)
{
const a = s * Math.min(l, 1 - l);
const f = (n) =>
{
const k = (n + h / 30) % 12;
const c = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * Math.min(1, Math.max(0, c)));
};
return [f(0), f(8), f(4), 255];
}
function drawHerb (herbId, tier)
{
const rgba = new Uint8Array(SIZE * SIZE * 4);
const { flower, leaf, stem, accent } = paletteFor(herbId, tier);
const shape = hashString(herbId) % 5;
// Stem
for (let y = 10; y < 15; y++)
{
setPx(rgba, 7, y, stem);
setPx(rgba, 8, y, stem);
}
if (shape === 0)
{
// Bushy leaves
for (const [x, y] of [[4, 8], [5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [11, 8],
[5, 9], [6, 8], [9, 8], [10, 9], [6, 10], [9, 10]])
{ setPx(rgba, x, y, leaf); }
for (const [x, y] of [[6, 4], [7, 3], [8, 3], [9, 4], [7, 4], [8, 4]])
{ setPx(rgba, x, y, flower); }
}
else if (shape === 1)
{
// Spike / upright
for (let y = 3; y < 11; y++)
{
setPx(rgba, 7, y, flower);
setPx(rgba, 8, y, accent);
if (y % 2 === 0)
{
setPx(rgba, 6, y, leaf);
setPx(rgba, 9, y, leaf);
}
}
}
else if (shape === 2)
{
// Bell / hanging
for (const [x, y] of [[5, 5], [6, 4], [7, 3], [8, 3], [9, 4], [10, 5]])
{ setPx(rgba, x, y, leaf); }
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]])
{ setPx(rgba, x, y, flower); }
setPx(rgba, 7, 9, accent);
setPx(rgba, 8, 9, accent);
}
else if (shape === 3)
{
// Round bloom
for (let dy = -3; dy <= 3; dy++)
{
for (let dx = -3; dx <= 3; dx++)
{
if (dx * dx + dy * dy <= 10)
{ setPx(rgba, 7 + dx, 6 + dy, flower); }
if (dx * dx + dy * dy <= 3)
{ setPx(rgba, 7 + dx, 6 + dy, accent); }
}
}
setPx(rgba, 4, 9, leaf);
setPx(rgba, 5, 10, leaf);
setPx(rgba, 10, 9, leaf);
setPx(rgba, 11, 10, leaf);
}
else
{
// Berry cluster / root-ish
for (const [x, y] of [[5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [6, 8], [9, 8]])
{ setPx(rgba, x, y, leaf); }
for (const [x, y] of [[6, 9], [7, 8], [8, 8], [9, 9], [7, 9], [8, 9], [7, 10], [8, 10]])
{ setPx(rgba, x, y, flower); }
setPx(rgba, 7, 7, accent);
setPx(rgba, 8, 7, accent);
}
// Tier mark (tiny dots for high tiers)
if (tier >= 5)
{
setPx(rgba, 1, 1, accent);
setPx(rgba, 2, 1, accent);
}
if (tier >= 7)
{
setPx(rgba, 13, 1, accent);
setPx(rgba, 14, 1, accent);
}
return rgba;
}
mkdirSync(OUT, { recursive: true });
for (const herbId of HERB_ORDER)
{
const def = HERB_DEFINITIONS[herbId];
const png = encodePng(drawHerb(herbId, def.tier));
writeFileSync(join(OUT, `${herbId}.png`), png);
console.log(`wrote ${herbId}.png (tier ${def.tier})`);
}
console.log(`Generated ${HERB_ORDER.length} herb sprites → ${OUT}`);
@@ -0,0 +1,226 @@/** * Temporary unique 16×16 herb sprites under client/assets/herbs/. * One PNG per herbId — shared by world nodes and inventory icons. */import { mkdirSync, writeFileSync } from "node:fs";import { deflateSync } from "node:zlib";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { HERB_ORDER, HERB_DEFINITIONS } from "../../shared/definitions/herbs.js";const SIZE = 16;const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/herbs");function crcTable (){ const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); } table[n] = c >>> 0; } return table;}const CRC_TABLE = crcTable();function crc32 (buf){ let c = 0xffffffff; for (let i = 0; i < buf.length; i++) { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); } return (c ^ 0xffffffff) >>> 0;}function chunk (type, data){ const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const typeBuf = Buffer.from(type, "ascii"); const crcBuf = Buffer.alloc(4); crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data]))); return Buffer.concat([len, typeBuf, data, crcBuf]);}function encodePng (rgba){ const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE); for (let y = 0; y < SIZE; y++) { const row = y * (SIZE * 4 + 1); raw[row] = 0; for (let x = 0; x < SIZE; x++) { const i = (y * SIZE + x) * 4; const o = row + 1 + x * 4; raw[o] = rgba[i]; raw[o + 1] = rgba[i + 1]; raw[o + 2] = rgba[i + 2]; raw[o + 3] = rgba[i + 3]; } } const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(SIZE, 0); ihdr.writeUInt32BE(SIZE, 4); ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; return Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", Buffer.alloc(0)) ]);}function setPx (rgba, x, y, color){ if (x < 0 || y < 0 || x >= SIZE || y >= SIZE) { return; } const i = (y * SIZE + x) * 4; rgba[i] = color[0]; rgba[i + 1] = color[1]; rgba[i + 2] = color[2]; rgba[i + 3] = color[3];}function hashString (text){ let h = 2166136261; for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0;}/** Distinct leaf/flower palettes keyed by herb identity. */function paletteFor (herbId, tier){ const h = hashString(herbId); const hue = (h % 360); const sat = 0.35 + ((h >>> 8) % 40) / 100; const lit = 0.28 + (tier - 1) * 0.04 + ((h >>> 16) % 20) / 100; const flower = hsl(hue, sat, lit); const leaf = hsl((hue + 100) % 360, 0.45, 0.32); const stem = hsl((hue + 90) % 360, 0.35, 0.22); const accent = hsl((hue + 40) % 360, Math.min(0.85, sat + 0.2), Math.min(0.7, lit + 0.15)); return { flower, leaf, stem, accent };}function hsl (h, s, l){ const a = s * Math.min(l, 1 - l); const f = (n) => { const k = (n + h / 30) % 12; const c = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); return Math.round(255 * Math.min(1, Math.max(0, c))); }; return [f(0), f(8), f(4), 255];}function drawHerb (herbId, tier){ const rgba = new Uint8Array(SIZE * SIZE * 4); const { flower, leaf, stem, accent } = paletteFor(herbId, tier); const shape = hashString(herbId) % 5; // Stem for (let y = 10; y < 15; y++) { setPx(rgba, 7, y, stem); setPx(rgba, 8, y, stem); } if (shape === 0) { // Bushy leaves for (const [x, y] of [[4, 8], [5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [11, 8], [5, 9], [6, 8], [9, 8], [10, 9], [6, 10], [9, 10]]) { setPx(rgba, x, y, leaf); } for (const [x, y] of [[6, 4], [7, 3], [8, 3], [9, 4], [7, 4], [8, 4]]) { setPx(rgba, x, y, flower); } } else if (shape === 1) { // Spike / upright for (let y = 3; y < 11; y++) { setPx(rgba, 7, y, flower); setPx(rgba, 8, y, accent); if (y % 2 === 0) { setPx(rgba, 6, y, leaf); setPx(rgba, 9, y, leaf); } } } else if (shape === 2) { // Bell / hanging for (const [x, y] of [[5, 5], [6, 4], [7, 3], [8, 3], [9, 4], [10, 5]]) { setPx(rgba, x, y, leaf); } 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]]) { setPx(rgba, x, y, flower); } setPx(rgba, 7, 9, accent); setPx(rgba, 8, 9, accent); } else if (shape === 3) { // Round bloom for (let dy = -3; dy <= 3; dy++) { for (let dx = -3; dx <= 3; dx++) { if (dx * dx + dy * dy <= 10) { setPx(rgba, 7 + dx, 6 + dy, flower); } if (dx * dx + dy * dy <= 3) { setPx(rgba, 7 + dx, 6 + dy, accent); } } } setPx(rgba, 4, 9, leaf); setPx(rgba, 5, 10, leaf); setPx(rgba, 10, 9, leaf); setPx(rgba, 11, 10, leaf); } else { // Berry cluster / root-ish for (const [x, y] of [[5, 7], [6, 6], [7, 5], [8, 5], [9, 6], [10, 7], [6, 8], [9, 8]]) { setPx(rgba, x, y, leaf); } for (const [x, y] of [[6, 9], [7, 8], [8, 8], [9, 9], [7, 9], [8, 9], [7, 10], [8, 10]]) { setPx(rgba, x, y, flower); } setPx(rgba, 7, 7, accent); setPx(rgba, 8, 7, accent); } // Tier mark (tiny dots for high tiers) if (tier >= 5) { setPx(rgba, 1, 1, accent); setPx(rgba, 2, 1, accent); } if (tier >= 7) { setPx(rgba, 13, 1, accent); setPx(rgba, 14, 1, accent); } return rgba;}mkdirSync(OUT, { recursive: true });for (const herbId of HERB_ORDER){ const def = HERB_DEFINITIONS[herbId]; const png = encodePng(drawHerb(herbId, def.tier)); writeFileSync(join(OUT, `${herbId}.png`), png); console.log(`wrote ${herbId}.png (tier ${def.tier})`);}console.log(`Generated ${HERB_ORDER.length} herb sprites → ${OUT}`);@@ -0,0 +1,125 @@
/**
* Temporary 16×16 status-effect icons (replace with final art later).
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { STATUS_EFFECT_DISPLAY } from "../../shared/statusEffects/display.js";
const SIZE = 16;
const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/status-effects");
const PALETTE = {
"health-regen": [80, 200, 100],
"stamina-regen": [90, 200, 170],
"strength-bonus": [220, 100, 60],
"mind-bonus": [140, 120, 230],
"stamina-drain": [180, 60, 90],
glow: [240, 220, 90],
shrink: [180, 140, 210],
blind: [40, 40, 50]
};
function crcTable ()
{
const table = new Uint32Array(256);
for (let n = 0; n < 256; n++)
{
let c = n;
for (let k = 0; k < 8; k++)
{ c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
table[n] = c >>> 0;
}
return table;
}
const CRC_TABLE = crcTable();
function crc32 (buf)
{
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++)
{ c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
return (c ^ 0xffffffff) >>> 0;
}
function chunk (type, data)
{
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length);
const typeBuf = Buffer.from(type, "ascii");
const crcBuf = Buffer.alloc(4);
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
return Buffer.concat([len, typeBuf, data, crcBuf]);
}
function encodePng (rgba)
{
const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
for (let y = 0; y < SIZE; y++)
{
const row = y * (SIZE * 4 + 1);
raw[row] = 0;
for (let x = 0; x < SIZE; x++)
{
const i = (y * SIZE + x) * 4;
const o = row + 1 + x * 4;
raw[o] = rgba[i];
raw[o + 1] = rgba[i + 1];
raw[o + 2] = rgba[i + 2];
raw[o + 3] = rgba[i + 3];
}
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(SIZE, 0);
ihdr.writeUInt32BE(SIZE, 4);
ihdr[8] = 8;
ihdr[9] = 6;
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk("IHDR", ihdr),
chunk("IDAT", deflateSync(raw, { level: 9 })),
chunk("IEND", Buffer.alloc(0))
]);
}
function setPx (rgba, x, y, rgb)
{
if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
{ return; }
const i = (y * SIZE + x) * 4;
rgba[i] = rgb[0];
rgba[i + 1] = rgb[1];
rgba[i + 2] = rgb[2];
rgba[i + 3] = 255;
}
function drawIcon (rgb)
{
const rgba = new Uint8Array(SIZE * SIZE * 4);
const rim = [Math.max(0, rgb[0] - 50), Math.max(0, rgb[1] - 50), Math.max(0, rgb[2] - 50)];
for (let y = 2; y < 14; y++)
{
for (let x = 2; x < 14; x++)
{
const edge = x === 2 || x === 13 || y === 2 || y === 13;
setPx(rgba, x, y, edge ? rim : rgb);
}
}
// Simple glyph: plus / diamond / bar
for (let i = 5; i < 11; i++)
{
setPx(rgba, i, 7, [255, 255, 255]);
setPx(rgba, 7, i, [255, 255, 255]);
}
return rgba;
}
mkdirSync(OUT, { recursive: true });
for (const display of Object.values(STATUS_EFFECT_DISPLAY))
{
const rgb = PALETTE[display.iconKey] ?? [160, 160, 160];
writeFileSync(join(OUT, `${display.iconKey}.png`), encodePng(drawIcon(rgb)));
console.log(`wrote ${display.iconKey}.png`);
}
@@ -0,0 +1,125 @@/** * Temporary 16×16 status-effect icons (replace with final art later). */import { mkdirSync, writeFileSync } from "node:fs";import { deflateSync } from "node:zlib";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { STATUS_EFFECT_DISPLAY } from "../../shared/statusEffects/display.js";const SIZE = 16;const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/status-effects");const PALETTE = { "health-regen": [80, 200, 100], "stamina-regen": [90, 200, 170], "strength-bonus": [220, 100, 60], "mind-bonus": [140, 120, 230], "stamina-drain": [180, 60, 90], glow: [240, 220, 90], shrink: [180, 140, 210], blind: [40, 40, 50]};function crcTable (){ const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); } table[n] = c >>> 0; } return table;}const CRC_TABLE = crcTable();function crc32 (buf){ let c = 0xffffffff; for (let i = 0; i < buf.length; i++) { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); } return (c ^ 0xffffffff) >>> 0;}function chunk (type, data){ const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const typeBuf = Buffer.from(type, "ascii"); const crcBuf = Buffer.alloc(4); crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data]))); return Buffer.concat([len, typeBuf, data, crcBuf]);}function encodePng (rgba){ const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE); for (let y = 0; y < SIZE; y++) { const row = y * (SIZE * 4 + 1); raw[row] = 0; for (let x = 0; x < SIZE; x++) { const i = (y * SIZE + x) * 4; const o = row + 1 + x * 4; raw[o] = rgba[i]; raw[o + 1] = rgba[i + 1]; raw[o + 2] = rgba[i + 2]; raw[o + 3] = rgba[i + 3]; } } const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(SIZE, 0); ihdr.writeUInt32BE(SIZE, 4); ihdr[8] = 8; ihdr[9] = 6; return Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", Buffer.alloc(0)) ]);}function setPx (rgba, x, y, rgb){ if (x < 0 || y < 0 || x >= SIZE || y >= SIZE) { return; } const i = (y * SIZE + x) * 4; rgba[i] = rgb[0]; rgba[i + 1] = rgb[1]; rgba[i + 2] = rgb[2]; rgba[i + 3] = 255;}function drawIcon (rgb){ const rgba = new Uint8Array(SIZE * SIZE * 4); const rim = [Math.max(0, rgb[0] - 50), Math.max(0, rgb[1] - 50), Math.max(0, rgb[2] - 50)]; for (let y = 2; y < 14; y++) { for (let x = 2; x < 14; x++) { const edge = x === 2 || x === 13 || y === 2 || y === 13; setPx(rgba, x, y, edge ? rim : rgb); } } // Simple glyph: plus / diamond / bar for (let i = 5; i < 11; i++) { setPx(rgba, i, 7, [255, 255, 255]); setPx(rgba, 7, i, [255, 255, 255]); } return rgba;}mkdirSync(OUT, { recursive: true });for (const display of Object.values(STATUS_EFFECT_DISPLAY)){ const rgb = PALETTE[display.iconKey] ?? [160, 160, 160]; writeFileSync(join(OUT, `${display.iconKey}.png`), encodePng(drawIcon(rgb))); console.log(`wrote ${display.iconKey}.png`);}@@ -11,8 +11,24 @@ import {
normalizeItemSeedValues,
effectiveSeedValue
} from "/shared/shop/pricing.js";
import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
import {
normalizeStarterLoadout,
starterLoadoutsEqual,
DEFAULT_STARTER_EQUIPMENT,
DEFAULT_STARTER_INVENTORY
} from "/shared/items/starterLoadout.js";
const SEED_PAGE_SIZE = 20;
const SLOT_LABELS = Object.freeze({
head: "Head",
chest: "Chest",
legs: "Legs",
boots: "Boots",
weapon: "Weapon",
offhand: "Off-hand"
});
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
{
@@ -32,6 +48,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
let seedQuery = "";
let seedPage = 0;
let seedPanel = null;
/** @type {{ equipment: Record<string, number|null>, inventory: { itemId: number, quantity: number }[] }} */
let draftStarter = normalizeStarterLoadout({
starterEquipment: DEFAULT_STARTER_EQUIPMENT,
starterInventory: DEFAULT_STARTER_INVENTORY
});
let starterPanel = null;
buildForm(form, {
getActiveCategory: () => activeCategory,
@@ -41,6 +63,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
syncTabs(form, activeCategory);
if (id === "basePrices")
{ renderSeedPanel(); }
if (id === "starterEquipment")
{ renderStarterPanel(); }
},
onFieldInput (field)
{
@@ -50,6 +74,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
onSeedPanelReady (panel)
{
seedPanel = panel;
},
onStarterPanelReady (panel)
{
starterPanel = panel;
}
});
@@ -68,14 +96,31 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
{
if (event.target?.dataset?.seedItemId)
{ return; }
if (event.target?.dataset?.starterField)
{ return; }
refreshDirty();
});
form.addEventListener("change", (event) =>
{
if (event.target?.dataset?.seedItemId)
{ return; }
if (event.target?.dataset?.starterField)
{ return; }
refreshDirty();
});
form.addEventListener("starter-changed", () => refreshDirty());
form.addEventListener("starter-add-inv", () =>
{
const first = listAllItems()[0];
if (!first)
{ return; }
draftStarter = {
...draftStarter,
inventory: [...draftStarter.inventory, { itemId: first.itemId, quantity: 1 }]
};
renderStarterPanel();
form.dispatchEvent(new CustomEvent("starter-changed"));
});
function show (visible)
{
@@ -83,11 +128,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
{
fillForm(form, baseline);
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
draftStarter = normalizeStarterLoadout(baseline);
seedQuery = "";
seedPage = 0;
if (seedPanel?.search)
{ seedPanel.search.value = ""; }
renderSeedPanel();
renderStarterPanel();
refreshDirty();
}
open = visible;
@@ -118,7 +165,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
return {
...baseline,
...scalarDirtyValues(form, baseline),
itemSeedValues: draftSeeds
itemSeedValues: draftSeeds,
starterEquipment: draftStarter.equipment,
starterInventory: draftStarter.inventory
};
}
@@ -129,6 +178,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues);
if (!itemSeedMapsEqual(prevSeeds, nextSeeds))
{ changed.itemSeedValues = nextSeeds; }
const nextStarter = normalizeStarterLoadout({
starterEquipment: draftStarter.equipment,
starterInventory: draftStarter.inventory
});
if (!starterLoadoutsEqual(baseline, nextStarter))
{
changed.starterEquipment = nextStarter.equipment;
changed.starterInventory = nextStarter.inventory;
}
return changed;
}
@@ -245,6 +303,110 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
refreshDirty();
}
function renderStarterPanel ()
{
if (!starterPanel)
{ return; }
const { equipRoot, invRoot } = starterPanel;
equipRoot.innerHTML = "";
for (const slot of EQUIPMENT_SLOTS)
{
const row = document.createElement("label");
row.className = "starter-equip-row";
row.dataset.slot = slot;
const title = document.createElement("span");
title.textContent = SLOT_LABELS[slot] ?? slot;
const select = document.createElement("select");
select.dataset.starterField = "equip";
select.dataset.slot = slot;
const empty = document.createElement("option");
empty.value = "";
empty.textContent = "(empty)";
select.append(empty);
for (const item of listItemsForSlot(slot))
{
const opt = document.createElement("option");
opt.value = String(item.itemId);
opt.textContent = item.displayName;
select.append(opt);
}
select.value = draftStarter.equipment[slot] != null
? String(draftStarter.equipment[slot])
: "";
select.addEventListener("change", () =>
{
const raw = select.value;
draftStarter = {
...draftStarter,
equipment: {
...draftStarter.equipment,
[slot]: raw === "" ? null : Number(raw)
}
};
form.dispatchEvent(new CustomEvent("starter-changed"));
row.classList.toggle("dirty", draftStarter.equipment[slot] !== normalizeStarterLoadout(baseline).equipment[slot]);
});
row.append(title, select);
equipRoot.append(row);
}
invRoot.innerHTML = "";
draftStarter.inventory.forEach((entry, index) =>
{
const row = document.createElement("div");
row.className = "starter-inv-row";
const select = document.createElement("select");
select.dataset.starterField = "inv-item";
for (const item of listAllItems())
{
const opt = document.createElement("option");
opt.value = String(item.itemId);
opt.textContent = item.displayName;
select.append(opt);
}
select.value = String(entry.itemId);
const qty = document.createElement("input");
qty.type = "number";
qty.min = "1";
qty.step = "1";
qty.dataset.starterField = "inv-qty";
qty.value = String(entry.quantity);
const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Remove";
select.addEventListener("change", () =>
{
const next = draftStarter.inventory.map((rowEntry, i) => (
i === index ? { ...rowEntry, itemId: Number(select.value) } : rowEntry
));
draftStarter = { ...draftStarter, inventory: next };
form.dispatchEvent(new CustomEvent("starter-changed"));
});
qty.addEventListener("change", () =>
{
const quantity = Math.max(1, Math.floor(Number(qty.value) || 1));
qty.value = String(quantity);
const next = draftStarter.inventory.map((rowEntry, i) => (
i === index ? { ...rowEntry, quantity } : rowEntry
));
draftStarter = { ...draftStarter, inventory: next };
form.dispatchEvent(new CustomEvent("starter-changed"));
});
remove.addEventListener("click", () =>
{
draftStarter = {
...draftStarter,
inventory: draftStarter.inventory.filter((_, i) => i !== index)
};
renderStarterPanel();
form.dispatchEvent(new CustomEvent("starter-changed"));
});
row.append(select, qty, remove);
invRoot.append(row);
});
refreshDirty();
}
function updateSeedRowReadouts (row, itemId, snap = null)
{
const resolved = snap ?? itemPriceSnapshot(itemId, {
@@ -280,8 +442,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
? message.itemLastSales
: {};
draftSeeds = { ...baseline.itemSeedValues };
draftStarter = normalizeStarterLoadout(baseline);
fillForm(form, baseline);
renderSeedPanel();
renderStarterPanel();
refreshDirty();
renderLog(log, message.changelog ?? []);
onApplied?.(message.settings);
@@ -289,7 +453,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
};
}
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })
function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady })
{
form.innerHTML = "";
const tabs = document.createElement("div");
@@ -325,6 +489,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput,
section.append(panel.root);
onSeedPanelReady?.(panel);
}
else if (category.panel === "starterEquipment")
{
const panel = buildStarterEquipmentPanel({
onAddInventory ()
{ form.dispatchEvent(new CustomEvent("starter-add-inv")); }
});
section.append(panel.root);
onStarterPanelReady?.(panel);
}
else
{
for (const field of category.fields)
@@ -417,6 +590,55 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext })
return { root, search, meta, list, prev, next, pageLabel };
}
function buildStarterEquipmentPanel ({ onAddInventory })
{
const root = document.createElement("div");
root.className = "starter-equipment-panel";
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "Applies only to newly created characters. Items are marked “Received from the gods”. Existing characters are unchanged.";
const equipTitle = document.createElement("h3");
equipTitle.textContent = "Equipped";
const equipRoot = document.createElement("div");
equipRoot.className = "starter-equip-list";
const invTitle = document.createElement("h3");
invTitle.textContent = "Inventory";
const invRoot = document.createElement("div");
invRoot.className = "starter-inv-list";
const add = document.createElement("button");
add.type = "button";
add.textContent = "Add inventory item";
add.addEventListener("click", () => onAddInventory?.());
root.append(hint, equipTitle, equipRoot, invTitle, invRoot, add);
return { root, equipRoot, invRoot };
}
function listAllItems ()
{
return Object.values(ITEM_DEFINITIONS)
.map((def) => ({
itemId: def.itemId,
displayName: def.displayName ?? `#${def.itemId}`
}))
.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
function listItemsForSlot (slot)
{
return Object.values(ITEM_DEFINITIONS)
.filter((def) => def.equipment?.slot === slot)
.map((def) => ({
itemId: def.itemId,
displayName: def.displayName ?? `#${def.itemId}`
}))
.sort((a, b) => a.displayName.localeCompare(b.displayName));
}
function syncTabs (form, activeCategory)
{
for (const tab of form.querySelectorAll(".settings-tab"))
@@ -11,8 +11,24 @@ import { normalizeItemSeedValues, normalizeItemSeedValues, effectiveSeedValue effectiveSeedValue} from "/shared/shop/pricing.js";} from "/shared/shop/pricing.js";import { ITEM_DEFINITIONS } from "/shared/definitions/items.js";import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";import { normalizeStarterLoadout, starterLoadoutsEqual, DEFAULT_STARTER_EQUIPMENT, DEFAULT_STARTER_INVENTORY} from "/shared/items/starterLoadout.js";const SEED_PAGE_SIZE = 20;const SEED_PAGE_SIZE = 20;const SLOT_LABELS = Object.freeze({ head: "Head", chest: "Chest", legs: "Legs", boots: "Boots", weapon: "Weapon", offhand: "Off-hand"});export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight }){{@@ -32,6 +48,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi let seedQuery = ""; let seedQuery = ""; let seedPage = 0; let seedPage = 0; let seedPanel = null; let seedPanel = null; /** @type {{ equipment: Record<string, number|null>, inventory: { itemId: number, quantity: number }[] }} */ let draftStarter = normalizeStarterLoadout({ starterEquipment: DEFAULT_STARTER_EQUIPMENT, starterInventory: DEFAULT_STARTER_INVENTORY }); let starterPanel = null; buildForm(form, { buildForm(form, { getActiveCategory: () => activeCategory, getActiveCategory: () => activeCategory,@@ -41,6 +63,8 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi syncTabs(form, activeCategory); syncTabs(form, activeCategory); if (id === "basePrices") if (id === "basePrices") { renderSeedPanel(); } { renderSeedPanel(); } if (id === "starterEquipment") { renderStarterPanel(); } }, }, onFieldInput (field) onFieldInput (field) { {@@ -50,6 +74,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi onSeedPanelReady (panel) onSeedPanelReady (panel) { { seedPanel = panel; seedPanel = panel; }, onStarterPanelReady (panel) { starterPanel = panel; } } }); });@@ -68,14 +96,31 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi { { if (event.target?.dataset?.seedItemId) if (event.target?.dataset?.seedItemId) { return; } { return; } if (event.target?.dataset?.starterField) { return; } refreshDirty(); refreshDirty(); }); }); form.addEventListener("change", (event) => form.addEventListener("change", (event) => { { if (event.target?.dataset?.seedItemId) if (event.target?.dataset?.seedItemId) { return; } { return; } if (event.target?.dataset?.starterField) { return; } refreshDirty(); refreshDirty(); }); }); form.addEventListener("starter-changed", () => refreshDirty()); form.addEventListener("starter-add-inv", () => { const first = listAllItems()[0]; if (!first) { return; } draftStarter = { ...draftStarter, inventory: [...draftStarter.inventory, { itemId: first.itemId, quantity: 1 }] }; renderStarterPanel(); form.dispatchEvent(new CustomEvent("starter-changed")); }); function show (visible) function show (visible) { {@@ -83,11 +128,13 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi { { fillForm(form, baseline); fillForm(form, baseline); draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) }; draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) }; draftStarter = normalizeStarterLoadout(baseline); seedQuery = ""; seedQuery = ""; seedPage = 0; seedPage = 0; if (seedPanel?.search) if (seedPanel?.search) { seedPanel.search.value = ""; } { seedPanel.search.value = ""; } renderSeedPanel(); renderSeedPanel(); renderStarterPanel(); refreshDirty(); refreshDirty(); } } open = visible; open = visible;@@ -118,7 +165,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi return { return { ...baseline, ...baseline, ...scalarDirtyValues(form, baseline), ...scalarDirtyValues(form, baseline), itemSeedValues: draftSeeds itemSeedValues: draftSeeds, starterEquipment: draftStarter.equipment, starterInventory: draftStarter.inventory }; }; } }@@ -129,6 +178,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues); const prevSeeds = normalizeItemSeedValues(baseline.itemSeedValues); if (!itemSeedMapsEqual(prevSeeds, nextSeeds)) if (!itemSeedMapsEqual(prevSeeds, nextSeeds)) { changed.itemSeedValues = nextSeeds; } { changed.itemSeedValues = nextSeeds; } const nextStarter = normalizeStarterLoadout({ starterEquipment: draftStarter.equipment, starterInventory: draftStarter.inventory }); if (!starterLoadoutsEqual(baseline, nextStarter)) { changed.starterEquipment = nextStarter.equipment; changed.starterInventory = nextStarter.inventory; } return changed; return changed; } }@@ -245,6 +303,110 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi refreshDirty(); refreshDirty(); } } function renderStarterPanel () { if (!starterPanel) { return; } const { equipRoot, invRoot } = starterPanel; equipRoot.innerHTML = ""; for (const slot of EQUIPMENT_SLOTS) { const row = document.createElement("label"); row.className = "starter-equip-row"; row.dataset.slot = slot; const title = document.createElement("span"); title.textContent = SLOT_LABELS[slot] ?? slot; const select = document.createElement("select"); select.dataset.starterField = "equip"; select.dataset.slot = slot; const empty = document.createElement("option"); empty.value = ""; empty.textContent = "(empty)"; select.append(empty); for (const item of listItemsForSlot(slot)) { const opt = document.createElement("option"); opt.value = String(item.itemId); opt.textContent = item.displayName; select.append(opt); } select.value = draftStarter.equipment[slot] != null ? String(draftStarter.equipment[slot]) : ""; select.addEventListener("change", () => { const raw = select.value; draftStarter = { ...draftStarter, equipment: { ...draftStarter.equipment, [slot]: raw === "" ? null : Number(raw) } }; form.dispatchEvent(new CustomEvent("starter-changed")); row.classList.toggle("dirty", draftStarter.equipment[slot] !== normalizeStarterLoadout(baseline).equipment[slot]); }); row.append(title, select); equipRoot.append(row); } invRoot.innerHTML = ""; draftStarter.inventory.forEach((entry, index) => { const row = document.createElement("div"); row.className = "starter-inv-row"; const select = document.createElement("select"); select.dataset.starterField = "inv-item"; for (const item of listAllItems()) { const opt = document.createElement("option"); opt.value = String(item.itemId); opt.textContent = item.displayName; select.append(opt); } select.value = String(entry.itemId); const qty = document.createElement("input"); qty.type = "number"; qty.min = "1"; qty.step = "1"; qty.dataset.starterField = "inv-qty"; qty.value = String(entry.quantity); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; select.addEventListener("change", () => { const next = draftStarter.inventory.map((rowEntry, i) => ( i === index ? { ...rowEntry, itemId: Number(select.value) } : rowEntry )); draftStarter = { ...draftStarter, inventory: next }; form.dispatchEvent(new CustomEvent("starter-changed")); }); qty.addEventListener("change", () => { const quantity = Math.max(1, Math.floor(Number(qty.value) || 1)); qty.value = String(quantity); const next = draftStarter.inventory.map((rowEntry, i) => ( i === index ? { ...rowEntry, quantity } : rowEntry )); draftStarter = { ...draftStarter, inventory: next }; form.dispatchEvent(new CustomEvent("starter-changed")); }); remove.addEventListener("click", () => { draftStarter = { ...draftStarter, inventory: draftStarter.inventory.filter((_, i) => i !== index) }; renderStarterPanel(); form.dispatchEvent(new CustomEvent("starter-changed")); }); row.append(select, qty, remove); invRoot.append(row); }); refreshDirty(); } function updateSeedRowReadouts (row, itemId, snap = null) function updateSeedRowReadouts (row, itemId, snap = null) { { const resolved = snap ?? itemPriceSnapshot(itemId, { const resolved = snap ?? itemPriceSnapshot(itemId, {@@ -280,8 +442,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi ? message.itemLastSales ? message.itemLastSales : {}; : {}; draftSeeds = { ...baseline.itemSeedValues }; draftSeeds = { ...baseline.itemSeedValues }; draftStarter = normalizeStarterLoadout(baseline); fillForm(form, baseline); fillForm(form, baseline); renderSeedPanel(); renderSeedPanel(); renderStarterPanel(); refreshDirty(); refreshDirty(); renderLog(log, message.changelog ?? []); renderLog(log, message.changelog ?? []); onApplied?.(message.settings); onApplied?.(message.settings);@@ -289,7 +453,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi }; };}}function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady })function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, onSeedPanelReady, onStarterPanelReady }){{ form.innerHTML = ""; form.innerHTML = ""; const tabs = document.createElement("div"); const tabs = document.createElement("div");@@ -325,6 +489,15 @@ function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput, section.append(panel.root); section.append(panel.root); onSeedPanelReady?.(panel); onSeedPanelReady?.(panel); } } else if (category.panel === "starterEquipment") { const panel = buildStarterEquipmentPanel({ onAddInventory () { form.dispatchEvent(new CustomEvent("starter-add-inv")); } }); section.append(panel.root); onStarterPanelReady?.(panel); } else else { { for (const field of category.fields) for (const field of category.fields)@@ -417,6 +590,55 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext }) return { root, search, meta, list, prev, next, pageLabel }; return { root, search, meta, list, prev, next, pageLabel };}}function buildStarterEquipmentPanel ({ onAddInventory }){ const root = document.createElement("div"); root.className = "starter-equipment-panel"; const hint = document.createElement("p"); hint.className = "hint"; hint.textContent = "Applies only to newly created characters. Items are marked “Received from the gods”. Existing characters are unchanged."; const equipTitle = document.createElement("h3"); equipTitle.textContent = "Equipped"; const equipRoot = document.createElement("div"); equipRoot.className = "starter-equip-list"; const invTitle = document.createElement("h3"); invTitle.textContent = "Inventory"; const invRoot = document.createElement("div"); invRoot.className = "starter-inv-list"; const add = document.createElement("button"); add.type = "button"; add.textContent = "Add inventory item"; add.addEventListener("click", () => onAddInventory?.()); root.append(hint, equipTitle, equipRoot, invTitle, invRoot, add); return { root, equipRoot, invRoot };}function listAllItems (){ return Object.values(ITEM_DEFINITIONS) .map((def) => ({ itemId: def.itemId, displayName: def.displayName ?? `#${def.itemId}` })) .sort((a, b) => a.displayName.localeCompare(b.displayName));}function listItemsForSlot (slot){ return Object.values(ITEM_DEFINITIONS) .filter((def) => def.equipment?.slot === slot) .map((def) => ({ itemId: def.itemId, displayName: def.displayName ?? `#${def.itemId}` })) .sort((a, b) => a.displayName.localeCompare(b.displayName));}function syncTabs (form, activeCategory)function syncTabs (form, activeCategory){{ for (const tab of form.querySelectorAll(".settings-tab")) for (const tab of form.querySelectorAll(".settings-tab"))@@ -0,0 +1,83 @@
import { bindHairControls } from "./hairControls.js";
export function initBarber ({
socket,
MessageType,
resolveSpriteUrl,
getInventoryBag,
onSuppressWorldClick
})
{
const backdrop = document.getElementById("barber-backdrop");
const panel = document.getElementById("barber-panel");
const statusEl = document.getElementById("barber-status");
let open = false;
let sex = "male";
const controls = bindHairControls({
root: panel,
resolveSpriteUrl,
getSex: () => sex,
getBag: () => getInventoryBag?.() ?? null,
hideHeadgear: true
});
function suppressWorldClick ()
{
onSuppressWorldClick?.();
}
document.getElementById("barber-close")?.addEventListener("click", () => close());
backdrop?.addEventListener("mousedown", (event) =>
{
event.preventDefault();
suppressWorldClick();
});
backdrop?.addEventListener("click", () => close());
panel?.addEventListener("mousedown", (event) =>
{
event.stopPropagation();
suppressWorldClick();
});
document.getElementById("barber-apply")?.addEventListener("click", () =>
{
statusEl.textContent = "Saving…";
socket.send({
type: MessageType.setHair,
hair: controls.currentHair()
});
});
function close ()
{
if (!open)
{ return; }
open = false;
panel.hidden = true;
backdrop.hidden = true;
statusEl.textContent = "";
socket.send({ type: MessageType.closeBarber });
}
return {
isOpen: () => open,
isBlocking: () => open,
close,
handleSnapshot (message)
{
open = true;
panel.hidden = false;
backdrop.hidden = false;
sex = message.sex === "female" ? "female" : "male";
controls.fillStyles();
controls.setHair(message.hair);
statusEl.textContent = message.message ?? "";
},
handleClosed ()
{
open = false;
panel.hidden = true;
backdrop.hidden = true;
}
};
}
@@ -0,0 +1,83 @@import { bindHairControls } from "./hairControls.js";export function initBarber ({ socket, MessageType, resolveSpriteUrl, getInventoryBag, onSuppressWorldClick}){ const backdrop = document.getElementById("barber-backdrop"); const panel = document.getElementById("barber-panel"); const statusEl = document.getElementById("barber-status"); let open = false; let sex = "male"; const controls = bindHairControls({ root: panel, resolveSpriteUrl, getSex: () => sex, getBag: () => getInventoryBag?.() ?? null, hideHeadgear: true }); function suppressWorldClick () { onSuppressWorldClick?.(); } document.getElementById("barber-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("mousedown", (event) => { event.preventDefault(); suppressWorldClick(); }); backdrop?.addEventListener("click", () => close()); panel?.addEventListener("mousedown", (event) => { event.stopPropagation(); suppressWorldClick(); }); document.getElementById("barber-apply")?.addEventListener("click", () => { statusEl.textContent = "Saving…"; socket.send({ type: MessageType.setHair, hair: controls.currentHair() }); }); function close () { if (!open) { return; } open = false; panel.hidden = true; backdrop.hidden = true; statusEl.textContent = ""; socket.send({ type: MessageType.closeBarber }); } return { isOpen: () => open, isBlocking: () => open, close, handleSnapshot (message) { open = true; panel.hidden = false; backdrop.hidden = false; sex = message.sex === "female" ? "female" : "male"; controls.fillStyles(); controls.setHair(message.hair); statusEl.textContent = message.message ?? ""; }, handleClosed () { open = false; panel.hidden = true; backdrop.hidden = true; } };}@@ -0,0 +1,191 @@
export function initBounty ({
socket,
MessageType,
resolveSpriteUrl,
onSuppressWorldClick
})
{
const backdrop = document.getElementById("bounty-backdrop");
const panel = document.getElementById("bounty-panel");
const statusEl = document.getElementById("bounty-status");
const myAmountEl = document.getElementById("bounty-my-amount");
const previewEl = document.getElementById("bounty-preview");
const targetLabel = document.getElementById("bounty-target-label");
const targetAmount = document.getElementById("bounty-target-amount");
const firstInput = document.getElementById("bounty-search-first");
const lastInput = document.getElementById("bounty-search-last");
const amountInput = document.getElementById("bounty-amount");
const tabs = [...document.querySelectorAll(".bounty-tab")];
const panes = [...document.querySelectorAll(".bounty-pane")];
let open = false;
/** @type {null | { characterId: number, firstName: string, lastName: string, amountCopper: number }} */
let target = null;
let activeTab = "place";
function suppressWorldClick ()
{
onSuppressWorldClick?.();
}
function setTab (tab)
{
activeTab = tab;
for (const button of tabs)
{ button.classList.toggle("active", button.dataset.tab === tab); }
for (const pane of panes)
{ pane.hidden = pane.dataset.pane !== tab; }
}
for (const button of tabs)
{ button.addEventListener("click", () => setTab(button.dataset.tab)); }
document.getElementById("bounty-close")?.addEventListener("click", () => close());
backdrop?.addEventListener("mousedown", (event) =>
{
event.preventDefault();
suppressWorldClick();
});
backdrop?.addEventListener("click", () => close());
panel?.addEventListener("mousedown", (event) =>
{
event.stopPropagation();
suppressWorldClick();
});
document.getElementById("bounty-search")?.addEventListener("click", () =>
{
const firstName = firstInput.value.trim();
const lastName = lastInput.value.trim();
if (!firstName || !lastName)
{
statusEl.textContent = "Enter a first and last name.";
return;
}
statusEl.textContent = "Searching…";
socket.send({ type: MessageType.getCharacterBounty, firstName, lastName });
});
document.getElementById("bounty-raise")?.addEventListener("click", () =>
{
if (!target)
{
statusEl.textContent = "Search for a target first.";
return;
}
const amountCopper = Math.floor(Number(amountInput.value) || 0);
if (amountCopper <= 0)
{
statusEl.textContent = "Enter a positive coin amount.";
return;
}
statusEl.textContent = "Placing bounty…";
socket.send({
type: MessageType.raiseBounty,
firstName: target.firstName,
lastName: target.lastName,
amountCopper
});
});
function clearTarget ()
{
target = null;
previewEl.replaceChildren();
targetLabel.textContent = "No target selected.";
targetAmount.textContent = "";
}
function renderPreview (layers)
{
previewEl.replaceChildren();
const wrap = document.createElement("div");
wrap.className = "char-preview";
for (const layer of layers ?? [])
{
const url = resolveSpriteUrl?.(layer.sprite);
if (!url)
{ continue; }
const img = document.createElement("img");
img.src = url;
img.alt = "";
if (layer.tint)
{ img.style.filter = `opacity(1)`; }
wrap.append(img);
}
previewEl.append(wrap);
}
function showTarget (entry)
{
if (!entry)
{
clearTarget();
statusEl.textContent = "No adventurer by that name.";
return;
}
target = {
characterId: entry.characterId,
firstName: entry.firstName,
lastName: entry.lastName,
amountCopper: entry.amountCopper | 0
};
targetLabel.textContent = `${entry.firstName} ${entry.lastName}`;
targetAmount.textContent = (entry.amountCopper | 0) > 0
? `Current bounty: ${entry.amountLabel ?? entry.amountCopper}`
: "No bounty yet.";
renderPreview(entry.layers);
statusEl.textContent = "";
}
function close ()
{
if (!open)
{ return; }
open = false;
panel.hidden = true;
backdrop.hidden = true;
clearTarget();
statusEl.textContent = "";
socket.send({ type: MessageType.closeBounty });
}
return {
isOpen: () => open,
isBlocking: () => open,
close,
handleSnapshot (message)
{
open = true;
panel.hidden = false;
backdrop.hidden = false;
setTab(activeTab);
myAmountEl.textContent = (message.myAmountCopper | 0) > 0
? message.myAmountLabel || String(message.myAmountCopper)
: "None";
if (message.raised)
{
statusEl.textContent = message.raised.message ?? "Bounty updated.";
if (target && target.characterId === message.raised.characterId)
{
target.amountCopper = message.raised.amountCopper | 0;
targetAmount.textContent = `Current bounty: ${message.raised.amountLabel}`;
}
}
else if (message.message && !(message.myAmountCopper > 0 && activeTab === "mine"))
{ statusEl.textContent = ""; }
},
handleCharacterBounty (message)
{
if (!open)
{ return; }
showTarget(message.target);
},
handleClosed ()
{
open = false;
panel.hidden = true;
backdrop.hidden = true;
}
};
}
@@ -0,0 +1,191 @@export function initBounty ({ socket, MessageType, resolveSpriteUrl, onSuppressWorldClick}){ const backdrop = document.getElementById("bounty-backdrop"); const panel = document.getElementById("bounty-panel"); const statusEl = document.getElementById("bounty-status"); const myAmountEl = document.getElementById("bounty-my-amount"); const previewEl = document.getElementById("bounty-preview"); const targetLabel = document.getElementById("bounty-target-label"); const targetAmount = document.getElementById("bounty-target-amount"); const firstInput = document.getElementById("bounty-search-first"); const lastInput = document.getElementById("bounty-search-last"); const amountInput = document.getElementById("bounty-amount"); const tabs = [...document.querySelectorAll(".bounty-tab")]; const panes = [...document.querySelectorAll(".bounty-pane")]; let open = false; /** @type {null | { characterId: number, firstName: string, lastName: string, amountCopper: number }} */ let target = null; let activeTab = "place"; function suppressWorldClick () { onSuppressWorldClick?.(); } function setTab (tab) { activeTab = tab; for (const button of tabs) { button.classList.toggle("active", button.dataset.tab === tab); } for (const pane of panes) { pane.hidden = pane.dataset.pane !== tab; } } for (const button of tabs) { button.addEventListener("click", () => setTab(button.dataset.tab)); } document.getElementById("bounty-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("mousedown", (event) => { event.preventDefault(); suppressWorldClick(); }); backdrop?.addEventListener("click", () => close()); panel?.addEventListener("mousedown", (event) => { event.stopPropagation(); suppressWorldClick(); }); document.getElementById("bounty-search")?.addEventListener("click", () => { const firstName = firstInput.value.trim(); const lastName = lastInput.value.trim(); if (!firstName || !lastName) { statusEl.textContent = "Enter a first and last name."; return; } statusEl.textContent = "Searching…"; socket.send({ type: MessageType.getCharacterBounty, firstName, lastName }); }); document.getElementById("bounty-raise")?.addEventListener("click", () => { if (!target) { statusEl.textContent = "Search for a target first."; return; } const amountCopper = Math.floor(Number(amountInput.value) || 0); if (amountCopper <= 0) { statusEl.textContent = "Enter a positive coin amount."; return; } statusEl.textContent = "Placing bounty…"; socket.send({ type: MessageType.raiseBounty, firstName: target.firstName, lastName: target.lastName, amountCopper }); }); function clearTarget () { target = null; previewEl.replaceChildren(); targetLabel.textContent = "No target selected."; targetAmount.textContent = ""; } function renderPreview (layers) { previewEl.replaceChildren(); const wrap = document.createElement("div"); wrap.className = "char-preview"; for (const layer of layers ?? []) { const url = resolveSpriteUrl?.(layer.sprite); if (!url) { continue; } const img = document.createElement("img"); img.src = url; img.alt = ""; if (layer.tint) { img.style.filter = `opacity(1)`; } wrap.append(img); } previewEl.append(wrap); } function showTarget (entry) { if (!entry) { clearTarget(); statusEl.textContent = "No adventurer by that name."; return; } target = { characterId: entry.characterId, firstName: entry.firstName, lastName: entry.lastName, amountCopper: entry.amountCopper | 0 }; targetLabel.textContent = `${entry.firstName} ${entry.lastName}`; targetAmount.textContent = (entry.amountCopper | 0) > 0 ? `Current bounty: ${entry.amountLabel ?? entry.amountCopper}` : "No bounty yet."; renderPreview(entry.layers); statusEl.textContent = ""; } function close () { if (!open) { return; } open = false; panel.hidden = true; backdrop.hidden = true; clearTarget(); statusEl.textContent = ""; socket.send({ type: MessageType.closeBounty }); } return { isOpen: () => open, isBlocking: () => open, close, handleSnapshot (message) { open = true; panel.hidden = false; backdrop.hidden = false; setTab(activeTab); myAmountEl.textContent = (message.myAmountCopper | 0) > 0 ? message.myAmountLabel || String(message.myAmountCopper) : "None"; if (message.raised) { statusEl.textContent = message.raised.message ?? "Bounty updated."; if (target && target.characterId === message.raised.characterId) { target.amountCopper = message.raised.amountCopper | 0; targetAmount.textContent = `Current bounty: ${message.raised.amountLabel}`; } } else if (message.message && !(message.myAmountCopper > 0 && activeTab === "mine")) { statusEl.textContent = ""; } }, handleCharacterBounty (message) { if (!open) { return; } showTarget(message.target); }, handleClosed () { open = false; panel.hidden = true; backdrop.hidden = true; } };}@@ -0,0 +1,68 @@
import { applyMagentaTintToImageData } from "/shared/render/tint.js";
import { layersForHairPreview } from "/shared/appearance/hair.js";
/**
* Draw stacked character layers (body + hair + optional gear) onto a canvas.
* Magenta hair/gear tints applied in 2D for UI previews.
*/
export async function paintCharacterPreview (canvas, {
sex,
bag = null,
hair = null,
hideHeadgear = true,
resolveSpriteUrl,
scale = 4
} = {})
{
if (!canvas)
{ return; }
const layers = layersForHairPreview(sex, bag, hair, { hideHeadgear });
const images = [];
for (const layer of layers)
{
const url = resolveSpriteUrl?.(layer.sprite);
if (!url)
{ continue; }
const img = await loadHtmlImage(url);
images.push({ img, tint: layer.tint ?? null });
}
if (!images.length)
{ return; }
const w = images[0].img.naturalWidth || images[0].img.width;
const h = images[0].img.naturalHeight || images[0].img.height;
canvas.width = w * scale;
canvas.height = h * scale;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const entry of images)
{
const source = entry.tint ? tintedCanvas(entry.img, entry.tint) : entry.img;
ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
}
}
function loadHtmlImage (url)
{
return new Promise((resolve, reject) =>
{
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Failed to load ${url}`));
img.src = url;
});
}
function tintedCanvas (sourceImg, tintRgb)
{
const canvas = document.createElement("canvas");
canvas.width = sourceImg.naturalWidth || sourceImg.width;
canvas.height = sourceImg.naturalHeight || sourceImg.height;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false;
ctx.drawImage(sourceImg, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
applyMagentaTintToImageData(imageData, tintRgb);
ctx.putImageData(imageData, 0, 0);
return canvas;
}
@@ -0,0 +1,68 @@import { applyMagentaTintToImageData } from "/shared/render/tint.js";import { layersForHairPreview } from "/shared/appearance/hair.js";/** * Draw stacked character layers (body + hair + optional gear) onto a canvas. * Magenta hair/gear tints applied in 2D for UI previews. */export async function paintCharacterPreview (canvas, { sex, bag = null, hair = null, hideHeadgear = true, resolveSpriteUrl, scale = 4} = {}){ if (!canvas) { return; } const layers = layersForHairPreview(sex, bag, hair, { hideHeadgear }); const images = []; for (const layer of layers) { const url = resolveSpriteUrl?.(layer.sprite); if (!url) { continue; } const img = await loadHtmlImage(url); images.push({ img, tint: layer.tint ?? null }); } if (!images.length) { return; } const w = images[0].img.naturalWidth || images[0].img.width; const h = images[0].img.naturalHeight || images[0].img.height; canvas.width = w * scale; canvas.height = h * scale; const ctx = canvas.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, canvas.width, canvas.height); for (const entry of images) { const source = entry.tint ? tintedCanvas(entry.img, entry.tint) : entry.img; ctx.drawImage(source, 0, 0, canvas.width, canvas.height); }}function loadHtmlImage (url){ return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(img); img.onerror = () => reject(new Error(`Failed to load ${url}`)); img.src = url; });}function tintedCanvas (sourceImg, tintRgb){ const canvas = document.createElement("canvas"); canvas.width = sourceImg.naturalWidth || sourceImg.width; canvas.height = sourceImg.naturalHeight || sourceImg.height; const ctx = canvas.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.drawImage(sourceImg, 0, 0); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); applyMagentaTintToImageData(imageData, tintRgb); ctx.putImageData(imageData, 0, 0); return canvas;}@@ -0,0 +1,92 @@
import {
ViewDistance,
LightingMode,
BloomMode,
loadGraphicsSettings,
saveGraphicsSettings,
normalizeGraphicsSettings
} from "/shared/graphics/settings.js";
/**
* @param {{
* onChange: (settings: { viewDistance: string, lighting: string, bloom: string }) => void
* }} options
*/
export function initGraphicsSettings ({ onChange })
{
const toggle = document.getElementById("settings-toggle");
const panel = document.getElementById("settings-panel");
const closeBtn = document.getElementById("settings-close");
if (!toggle || !panel)
{
return {
getSettings: () => loadGraphicsSettings(),
apply: () => {},
close: () => {}
};
}
let settings = loadGraphicsSettings();
function syncButtons ()
{
for (const btn of panel.querySelectorAll("[data-graphics-key]"))
{
const key = btn.getAttribute("data-graphics-key");
const value = btn.getAttribute("data-graphics-value");
btn.classList.toggle("active", settings[key] === value);
}
}
function emit ()
{
settings = saveGraphicsSettings(settings);
syncButtons();
onChange?.(settings);
}
function open ()
{
panel.hidden = false;
syncButtons();
}
function close ()
{
panel.hidden = true;
}
toggle.addEventListener("click", () =>
{
if (panel.hidden)
{ open(); }
else
{ close(); }
});
closeBtn?.addEventListener("click", close);
panel.addEventListener("click", (event) =>
{
const btn = event.target.closest("[data-graphics-key]");
if (!btn || !panel.contains(btn))
{ return; }
const key = btn.getAttribute("data-graphics-key");
const value = btn.getAttribute("data-graphics-value");
if (!key || !value)
{ return; }
settings = normalizeGraphicsSettings({ ...settings, [key]: value });
emit();
});
syncButtons();
return {
getSettings: () => ({ ...settings }),
/** Re-apply current settings (e.g. after world enter). */
apply ()
{ onChange?.(settings); },
close
};
}
export { ViewDistance, LightingMode, BloomMode };
@@ -0,0 +1,92 @@import { ViewDistance, LightingMode, BloomMode, loadGraphicsSettings, saveGraphicsSettings, normalizeGraphicsSettings} from "/shared/graphics/settings.js";/** * @param {{ * onChange: (settings: { viewDistance: string, lighting: string, bloom: string }) => void * }} options */export function initGraphicsSettings ({ onChange }){ const toggle = document.getElementById("settings-toggle"); const panel = document.getElementById("settings-panel"); const closeBtn = document.getElementById("settings-close"); if (!toggle || !panel) { return { getSettings: () => loadGraphicsSettings(), apply: () => {}, close: () => {} }; } let settings = loadGraphicsSettings(); function syncButtons () { for (const btn of panel.querySelectorAll("[data-graphics-key]")) { const key = btn.getAttribute("data-graphics-key"); const value = btn.getAttribute("data-graphics-value"); btn.classList.toggle("active", settings[key] === value); } } function emit () { settings = saveGraphicsSettings(settings); syncButtons(); onChange?.(settings); } function open () { panel.hidden = false; syncButtons(); } function close () { panel.hidden = true; } toggle.addEventListener("click", () => { if (panel.hidden) { open(); } else { close(); } }); closeBtn?.addEventListener("click", close); panel.addEventListener("click", (event) => { const btn = event.target.closest("[data-graphics-key]"); if (!btn || !panel.contains(btn)) { return; } const key = btn.getAttribute("data-graphics-key"); const value = btn.getAttribute("data-graphics-value"); if (!key || !value) { return; } settings = normalizeGraphicsSettings({ ...settings, [key]: value }); emit(); }); syncButtons(); return { getSettings: () => ({ ...settings }), /** Re-apply current settings (e.g. after world enter). */ apply () { onChange?.(settings); }, close };}export { ViewDistance, LightingMode, BloomMode };@@ -0,0 +1,136 @@
import {
DEFAULT_HAIR_STYLE,
DEFAULT_HAIR_HUE,
DEFAULT_HAIR_SATURATION,
DEFAULT_HAIR_DARKNESS,
listHairStyles,
normalizeHairSliders,
hairColorFromSliders
} from "/shared/appearance/hair.js";
import { paintCharacterPreview } from "./characterPreview.js";
/**
* Shared hair style + HSL controls with live character preview.
*/
export function bindHairControls ({
root,
resolveSpriteUrl,
getSex,
getBag = () => null,
hideHeadgear = true,
onChange = null
})
{
const preview = root.querySelector("[data-hair-preview]");
const styleSelect = root.querySelector("[data-hair-style]");
const hue = root.querySelector("[data-hair-hue]");
const saturation = root.querySelector("[data-hair-saturation]");
const darkness = root.querySelector("[data-hair-darkness]");
const swatch = root.querySelector("[data-hair-swatch]");
let paintToken = 0;
function currentHair ()
{
const style = styleSelect?.value === "none" ? null : (styleSelect?.value || DEFAULT_HAIR_STYLE);
const sliders = normalizeHairSliders({
hue: hue?.value,
saturation: Number(saturation?.value) / 100,
darkness: Number(darkness?.value) / 100
});
return {
style,
...sliders,
color: hairColorFromSliders(sliders)
};
}
function fillStyles ()
{
if (!styleSelect)
{ return; }
const sex = getSex?.() === "female" ? "female" : "male";
const selected = styleSelect.value || DEFAULT_HAIR_STYLE;
styleSelect.replaceChildren();
const none = document.createElement("option");
none.value = "none";
none.textContent = "Bald";
styleSelect.append(none);
for (const style of listHairStyles(sex))
{
const option = document.createElement("option");
option.value = style;
option.textContent = style.replace("hair-", "Style ");
styleSelect.append(option);
}
if ([...styleSelect.options].some((option) => option.value === selected))
{ styleSelect.value = selected; }
else
{ styleSelect.value = DEFAULT_HAIR_STYLE; }
}
function syncSwatch ()
{
if (!swatch)
{ return; }
const color = hairColorFromSliders(currentHair());
swatch.style.background = `rgb(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)})`;
}
async function refreshPreview ()
{
const token = ++paintToken;
syncSwatch();
onChange?.(currentHair());
if (!preview)
{ return; }
try
{
await paintCharacterPreview(preview, {
sex: getSex?.() === "female" ? "female" : "male",
bag: getBag?.() ?? null,
hair: currentHair(),
hideHeadgear,
resolveSpriteUrl,
scale: 4
});
}
catch (error)
{
if (token === paintToken)
{ console.warn(error); }
}
}
function setHair (hair)
{
fillStyles();
if (styleSelect)
{ styleSelect.value = hair?.style ?? DEFAULT_HAIR_STYLE; }
const sliders = normalizeHairSliders(hair ?? {});
if (hue)
{ hue.value = String(Math.round(sliders.hue)); }
if (saturation)
{ saturation.value = String(Math.round(sliders.saturation * 100)); }
if (darkness)
{ darkness.value = String(Math.round(sliders.darkness * 100)); }
void refreshPreview();
}
fillStyles();
if (hue && !hue.value)
{ hue.value = String(DEFAULT_HAIR_HUE); }
if (saturation && !saturation.value)
{ saturation.value = String(Math.round(DEFAULT_HAIR_SATURATION * 100)); }
if (darkness && !darkness.value)
{ darkness.value = String(Math.round(DEFAULT_HAIR_DARKNESS * 100)); }
for (const el of [styleSelect, hue, saturation, darkness])
{ el?.addEventListener("input", () => void refreshPreview()); }
return {
currentHair,
setHair,
fillStyles,
refreshPreview
};
}
@@ -0,0 +1,136 @@import { DEFAULT_HAIR_STYLE, DEFAULT_HAIR_HUE, DEFAULT_HAIR_SATURATION, DEFAULT_HAIR_DARKNESS, listHairStyles, normalizeHairSliders, hairColorFromSliders} from "/shared/appearance/hair.js";import { paintCharacterPreview } from "./characterPreview.js";/** * Shared hair style + HSL controls with live character preview. */export function bindHairControls ({ root, resolveSpriteUrl, getSex, getBag = () => null, hideHeadgear = true, onChange = null}){ const preview = root.querySelector("[data-hair-preview]"); const styleSelect = root.querySelector("[data-hair-style]"); const hue = root.querySelector("[data-hair-hue]"); const saturation = root.querySelector("[data-hair-saturation]"); const darkness = root.querySelector("[data-hair-darkness]"); const swatch = root.querySelector("[data-hair-swatch]"); let paintToken = 0; function currentHair () { const style = styleSelect?.value === "none" ? null : (styleSelect?.value || DEFAULT_HAIR_STYLE); const sliders = normalizeHairSliders({ hue: hue?.value, saturation: Number(saturation?.value) / 100, darkness: Number(darkness?.value) / 100 }); return { style, ...sliders, color: hairColorFromSliders(sliders) }; } function fillStyles () { if (!styleSelect) { return; } const sex = getSex?.() === "female" ? "female" : "male"; const selected = styleSelect.value || DEFAULT_HAIR_STYLE; styleSelect.replaceChildren(); const none = document.createElement("option"); none.value = "none"; none.textContent = "Bald"; styleSelect.append(none); for (const style of listHairStyles(sex)) { const option = document.createElement("option"); option.value = style; option.textContent = style.replace("hair-", "Style "); styleSelect.append(option); } if ([...styleSelect.options].some((option) => option.value === selected)) { styleSelect.value = selected; } else { styleSelect.value = DEFAULT_HAIR_STYLE; } } function syncSwatch () { if (!swatch) { return; } const color = hairColorFromSliders(currentHair()); swatch.style.background = `rgb(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)})`; } async function refreshPreview () { const token = ++paintToken; syncSwatch(); onChange?.(currentHair()); if (!preview) { return; } try { await paintCharacterPreview(preview, { sex: getSex?.() === "female" ? "female" : "male", bag: getBag?.() ?? null, hair: currentHair(), hideHeadgear, resolveSpriteUrl, scale: 4 }); } catch (error) { if (token === paintToken) { console.warn(error); } } } function setHair (hair) { fillStyles(); if (styleSelect) { styleSelect.value = hair?.style ?? DEFAULT_HAIR_STYLE; } const sliders = normalizeHairSliders(hair ?? {}); if (hue) { hue.value = String(Math.round(sliders.hue)); } if (saturation) { saturation.value = String(Math.round(sliders.saturation * 100)); } if (darkness) { darkness.value = String(Math.round(sliders.darkness * 100)); } void refreshPreview(); } fillStyles(); if (hue && !hue.value) { hue.value = String(DEFAULT_HAIR_HUE); } if (saturation && !saturation.value) { saturation.value = String(Math.round(DEFAULT_HAIR_SATURATION * 100)); } if (darkness && !darkness.value) { darkness.value = String(Math.round(DEFAULT_HAIR_DARKNESS * 100)); } for (const el of [styleSelect, hue, saturation, darkness]) { el?.addEventListener("input", () => void refreshPreview()); } return { currentHair, setHair, fillStyles, refreshPreview };}@@ -0,0 +1,60 @@
export function initHealth ()
{
let vitals = document.getElementById("vitals");
if (!vitals)
{
vitals = document.createElement("div");
vitals.id = "vitals";
vitals.hidden = true;
document.body.append(vitals);
}
let bar = document.getElementById("health-bar");
if (!bar)
{
bar = document.createElement("div");
bar.id = "health-bar";
bar.innerHTML = '<div id="health-bar-fill"></div><span id="health-bar-label" class="health-bar-label"></span>';
vitals.prepend(bar);
}
else if (bar.parentElement !== vitals)
{ vitals.prepend(bar); }
const fill = document.getElementById("health-bar-fill");
const label = document.getElementById("health-bar-label");
let current = 1;
let max = 1;
function render ()
{
const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0;
fill.style.transform = `scaleY(${ratio})`;
label.textContent = `${Math.ceil(current)}/${max | 0}`;
bar.classList.toggle("empty", current <= 0);
bar.classList.toggle("low", current > 0 && current / max <= 0.25);
}
return {
show ()
{
vitals.hidden = false;
bar.hidden = false;
render();
},
hide ()
{
bar.hidden = true;
},
apply (message)
{
if (message?.max != null)
{ max = Math.max(1, message.max | 0); }
if (message?.current != null)
{ current = Math.max(0, Number(message.current) || 0); }
render();
},
getCurrent ()
{ return current; },
getMax ()
{ return max; }
};
}
@@ -0,0 +1,60 @@export function initHealth (){ let vitals = document.getElementById("vitals"); if (!vitals) { vitals = document.createElement("div"); vitals.id = "vitals"; vitals.hidden = true; document.body.append(vitals); } let bar = document.getElementById("health-bar"); if (!bar) { bar = document.createElement("div"); bar.id = "health-bar"; bar.innerHTML = '<div id="health-bar-fill"></div><span id="health-bar-label" class="health-bar-label"></span>'; vitals.prepend(bar); } else if (bar.parentElement !== vitals) { vitals.prepend(bar); } const fill = document.getElementById("health-bar-fill"); const label = document.getElementById("health-bar-label"); let current = 1; let max = 1; function render () { const ratio = max > 0 ? Math.min(1, Math.max(0, current / max)) : 0; fill.style.transform = `scaleY(${ratio})`; label.textContent = `${Math.ceil(current)}/${max | 0}`; bar.classList.toggle("empty", current <= 0); bar.classList.toggle("low", current > 0 && current / max <= 0.25); } return { show () { vitals.hidden = false; bar.hidden = false; render(); }, hide () { bar.hidden = true; }, apply (message) { if (message?.max != null) { max = Math.max(1, message.max | 0); } if (message?.current != null) { current = Math.max(0, Number(message.current) || 0); } render(); }, getCurrent () { return current; }, getMax () { return max; } };}@@ -861,6 +861,10 @@ export function initInventory ({
{
return bag.inventory ?? [];
},
getEquipment ()
{
return bag.equipment?.slots ?? bag.equipment ?? {};
},
handleInventory (message)
{
bag = { ...bag, ...message };
@@ -861,6 +861,10 @@ export function initInventory ({ { { return bag.inventory ?? []; return bag.inventory ?? []; }, }, getEquipment () { return bag.equipment?.slots ?? bag.equipment ?? {}; }, handleInventory (message) handleInventory (message) { { bag = { ...bag, ...message }; bag = { ...bag, ...message };@@ -10,11 +10,17 @@ import { initSkills } from "./skills.js";
import { initCrafting } from "./crafting.js";
import { initAlchemy } from "./alchemy.js";
import { initStamina } from "./stamina.js";
import { initHealth } from "./health.js";
import { initStatusEffects } from "./statusEffects.js";
import { initContextMenu } from "./contextMenu.js";
import { initDeath } from "./death.js";
import { initToasts } from "./toasts.js";
import { initShop } from "./shop.js";
import { initMarket } from "./market.js";
import { initBounty } from "./bounty.js";
import { initBarber } from "./barber.js";
import { bindHairControls } from "./hairControls.js";
import { initGraphicsSettings } from "./graphicsSettings.js";
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -33,6 +39,7 @@ let socket;
let session = null;
let playing = false;
let view = null;
let graphicsSettingsUi = null;
let scene = null;
let gait = GAIT.walk;
let catalog = { grounds: {}, blocks: {} };
@@ -43,11 +50,16 @@ let skills;
let crafting;
let alchemy;
let staminaUi;
let healthUi;
let statusEffectsUi;
let contextMenu;
let death;
let toasts;
let shop;
let market;
let bounty;
let barber;
let createHairControls;
let pendingPickup = null;
/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
let pendingInteract = null;
@@ -99,7 +111,20 @@ function uiBlocked ()
{
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
|| crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
|| market?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
|| market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
|| contextMenu?.isOpen() || death?.isBlocking());
}
function applyGraphicsSettings (settings)
{
view?.setGraphicsPrefs(settings);
if (socket && playing)
{
socket.send({
type: MessageType.setGraphicsSettings,
viewDistance: settings.viewDistance
});
}
}
function clearPendingPickup ()
@@ -197,6 +222,28 @@ function requestOpenMarket (tileX, tileY)
{ approachAdjacentTile(tileX, tileY); }
}
function requestOpenBounty (tileX, tileY)
{
clearAllPendingActions();
pendingInteract = { kind: "bounty", tileX, tileY };
const local = view?.entities.get(view.localEntityId);
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
{ flushPendingInteract(); }
else
{ approachAdjacentTile(tileX, tileY); }
}
function requestOpenBarber (tileX, tileY)
{
clearAllPendingActions();
pendingInteract = { kind: "barber", tileX, tileY };
const local = view?.entities.get(view.localEntityId);
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
{ flushPendingInteract(); }
else
{ approachAdjacentTile(tileX, tileY); }
}
function requestOpenCauldron (tileX, tileY)
{
clearAllPendingActions();
@@ -300,6 +347,24 @@ function flushPendingInteract ()
return;
}
if (pendingInteract.kind === "bounty")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({ type: MessageType.openBounty });
clearPendingInteract();
return;
}
if (pendingInteract.kind === "barber")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
{ return; }
socket.send({ type: MessageType.openBarber });
clearPendingInteract();
return;
}
if (pendingInteract.kind === "cauldron")
{
if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -467,6 +532,10 @@ function handleLeftClick (mouseX, mouseY)
{ requestOpenBank(tile.tileX, tile.tileY); }
else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
{ requestOpenMarket(tile.tileX, tile.tileY); }
else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
{ requestOpenBounty(tile.tileX, tile.tileY); }
else if (isBarberTile(view, tile.tileX, tile.tileY))
{ requestOpenBarber(tile.tileX, tile.tileY); }
else if (isCauldronTile(view, tile.tileX, tile.tileY))
{ requestOpenCauldron(tile.tileX, tile.tileY); }
else if (isFurnaceTile(view, tile.tileX, tile.tileY))
@@ -588,6 +657,22 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Bounty Office",
onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
});
}
if (isBarberTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Barber",
onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
});
}
if (isCauldronTile(view, tile.tileX, tile.tileY))
{
items.push({
@@ -702,18 +787,31 @@ function startPlay (payload)
playing = true;
overlay.hidden = true;
hud.hidden = false;
const settingsToggle = document.getElementById("settings-toggle");
if (settingsToggle)
{ settingsToggle.hidden = false; }
document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
gait = payload.gait ?? GAIT.walk;
document.getElementById("gait").textContent = gait;
staminaUi?.show();
healthUi?.show();
statusEffectsUi?.show();
if (payload.stamina != null)
{ staminaUi?.apply(payload.stamina); }
if (payload.health != null || payload.maxHealth != null)
{
healthUi?.apply({
current: payload.health ?? healthUi.getCurrent?.(),
max: payload.maxHealth ?? healthUi.getMax?.()
});
}
if (!scene)
{
scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
game.loadScene(scene);
useNearestNeighbour(scene, game.images);
view = new WorldView(game, scene, catalog);
graphicsSettingsUi?.apply();
const ticker = new GameObject(0, 0, null, 10);
ticker.update = (dt) =>
{
@@ -791,8 +889,11 @@ function startPlay (payload)
payload.firstName,
payload.lastName,
payload.characterId,
payload.layers
payload.layers,
payload.health,
payload.maxHealth
);
graphicsSettingsUi?.apply();
}
async function main ()
@@ -800,6 +901,24 @@ async function main ()
catalog = await loadSpriteCatalog();
await preloadCatalogImages(game, catalog);
applySpriteSheets(game.images, catalog);
createHairControls = bindHairControls({
root: document.getElementById("create-hair"),
resolveSpriteUrl (name)
{
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
},
getSex: () => document.getElementById("sex")?.value ?? "male",
hideHeadgear: true
});
document.getElementById("sex")?.addEventListener("change", () =>
{
createHairControls?.fillStyles();
void createHairControls?.refreshPreview();
});
void createHairControls?.refreshPreview();
graphicsSettingsUi = initGraphicsSettings({
onChange: applyGraphicsSettings
});
social = initSocial({
socket: { send (payload) { socket.send(payload); } },
MessageType
@@ -845,6 +964,8 @@ async function main ()
}
});
staminaUi = initStamina();
healthUi = initHealth();
statusEffectsUi = initStatusEffects();
toasts = initToasts();
shop = initShop({
socket: { send (payload) { socket.send(payload); } },
@@ -872,6 +993,31 @@ async function main ()
return inventory?.getInventorySlots?.() ?? [];
}
});
bounty = initBounty({
socket: { send (payload) { socket.send(payload); } },
MessageType,
onSuppressWorldClick: consumeWorldClick,
resolveSpriteUrl (name)
{
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
}
});
barber = initBarber({
socket: { send (payload) { socket.send(payload); } },
MessageType,
onSuppressWorldClick: consumeWorldClick,
resolveSpriteUrl (name)
{
return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
},
getInventoryBag ()
{
return {
equipment: { slots: inventory?.getEquipment?.() ?? {} },
inventory: inventory?.getInventorySlots?.() ?? []
};
}
});
chat = initChat({
socket: { send (payload) { socket.send(payload); } },
MessageType,
@@ -898,6 +1044,7 @@ async function main ()
{ overlay.hidden = false; }
break;
case MessageType.enterWorld:
closeCreateModal();
startPlay(message);
inventory?.setLocalCharacterId(message.characterId);
break;
@@ -961,6 +1108,10 @@ async function main ()
document.getElementById("gait").textContent = gait;
}
break;
case MessageType.statusEffects:
view?.setLocalBlind(!!message.blind);
statusEffectsUi?.apply(message);
break;
case MessageType.bankSnapshot:
inventory?.handleBank(message);
break;
@@ -1021,6 +1172,22 @@ async function main ()
market?.handleTrade(message);
toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
break;
case MessageType.bountySnapshot:
bounty?.handleSnapshot(message);
break;
case MessageType.closeBounty:
bounty?.handleClosed(message);
break;
case MessageType.characterBounty:
bounty?.handleCharacterBounty(message);
social?.handleCharacterBounty(message);
break;
case MessageType.barberSnapshot:
barber?.handleSnapshot(message);
break;
case MessageType.closeBarber:
barber?.handleClosed(message);
break;
case MessageType.itemBubble:
chat?.showItemBubble(message);
break;
@@ -1031,6 +1198,23 @@ async function main ()
view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
view?.flashDamage(message.targetId);
view?.spawnDamageNumber(message.targetId, message.damage);
if (message.targetId === view?.localEntityId)
{
healthUi?.apply({
current: message.health,
max: message.maxHealth
});
}
break;
case MessageType.entityHealth:
view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
if (message.entityId === view?.localEntityId)
{
healthUi?.apply({
current: message.health,
max: message.maxHealth
});
}
break;
case MessageType.skillLevelUp:
view?.spawnSkillLevelUp(message.entityId, message);
@@ -1044,10 +1228,22 @@ async function main ()
clearAllPendingActions();
contextMenu?.hide();
death?.show();
if (message.entityId === view?.localEntityId)
{
healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
}
break;
case MessageType.playerRespawned:
death?.hide();
view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
if (message.entityId === view?.localEntityId)
{
healthUi?.apply({
current: message.health,
max: message.maxHealth
});
}
if (message.stamina != null || message.maxStamina != null)
{
staminaUi?.apply({
@@ -1060,7 +1256,14 @@ async function main ()
if (playing)
{ toasts?.show(message.message); }
else
{ showError(message.message); }
{
const createPanel = document.getElementById("create-panel");
const createError = document.getElementById("create-error");
if (createPanel && !createPanel.hidden && createError)
{ createError.textContent = message.message ?? ""; }
else
{ showError(message.message); }
}
social?.showError(message.message);
break;
case MessageType.toast:
@@ -1098,10 +1301,14 @@ function returnToMenu (reason = "")
crafting?.reset();
alchemy?.reset();
staminaUi?.hide();
healthUi?.hide();
statusEffectsUi?.hide();
skills?.hide();
contextMenu?.hide();
death?.reset();
shop?.close({ notifyServer: false });
bounty?.close();
barber?.close();
hideWorldTooltip();
if (view)
{
@@ -1113,19 +1320,47 @@ function returnToMenu (reason = "")
}
overlay.hidden = false;
hud.hidden = true;
const settingsToggle = document.getElementById("settings-toggle");
if (settingsToggle)
{ settingsToggle.hidden = true; }
graphicsSettingsUi?.close();
if (reason)
{ statusEl.textContent = reason; }
}
document.getElementById("create-character-open")?.addEventListener("click", () =>
{
showError("");
const createError = document.getElementById("create-error");
if (createError)
{ createError.textContent = ""; }
document.getElementById("create-backdrop").hidden = false;
document.getElementById("create-panel").hidden = false;
void createHairControls?.refreshPreview();
});
function closeCreateModal ()
{
document.getElementById("create-backdrop").hidden = true;
document.getElementById("create-panel").hidden = true;
}
document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
document.getElementById("create-form").addEventListener("submit", (event) =>
{
event.preventDefault();
showError("");
const createError = document.getElementById("create-error");
if (createError)
{ createError.textContent = ""; }
socket.send({
type: MessageType.createCharacter,
firstName: document.getElementById("first-name").value,
lastName: document.getElementById("last-name").value,
sex: document.getElementById("sex").value
sex: document.getElementById("sex").value,
hair: createHairControls?.currentHair?.() ?? null
});
});
@@ -1151,6 +1386,16 @@ function isMarketplaceTile (view, tileX, tileY)
return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
}
function isBountyOfficeTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
}
function isBarberTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.barber;
}
function isCauldronTile (view, tileX, tileY)
{
return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
@@ -10,11 +10,17 @@ import { initSkills } from "./skills.js";import { initCrafting } from "./crafting.js";import { initCrafting } from "./crafting.js";import { initAlchemy } from "./alchemy.js";import { initAlchemy } from "./alchemy.js";import { initStamina } from "./stamina.js";import { initStamina } from "./stamina.js";import { initHealth } from "./health.js";import { initStatusEffects } from "./statusEffects.js";import { initContextMenu } from "./contextMenu.js";import { initContextMenu } from "./contextMenu.js";import { initDeath } from "./death.js";import { initDeath } from "./death.js";import { initToasts } from "./toasts.js";import { initToasts } from "./toasts.js";import { initShop } from "./shop.js";import { initShop } from "./shop.js";import { initMarket } from "./market.js";import { initMarket } from "./market.js";import { initBounty } from "./bounty.js";import { initBarber } from "./barber.js";import { bindHairControls } from "./hairControls.js";import { initGraphicsSettings } from "./graphicsSettings.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { isOreBoulderState } from "/shared/definitions/materialTiers.js";import { isOreBoulderState } from "/shared/definitions/materialTiers.js";import { formatQuantity } from "/shared/items/formatQuantity.js";import { formatQuantity } from "/shared/items/formatQuantity.js";@@ -33,6 +39,7 @@ let socket;let session = null;let session = null;let playing = false;let playing = false;let view = null;let view = null;let graphicsSettingsUi = null;let scene = null;let scene = null;let gait = GAIT.walk;let gait = GAIT.walk;let catalog = { grounds: {}, blocks: {} };let catalog = { grounds: {}, blocks: {} };@@ -43,11 +50,16 @@ let skills;let crafting;let crafting;let alchemy;let alchemy;let staminaUi;let staminaUi;let healthUi;let statusEffectsUi;let contextMenu;let contextMenu;let death;let death;let toasts;let toasts;let shop;let shop;let market;let market;let bounty;let barber;let createHairControls;let pendingPickup = null;let pendingPickup = null;/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } *//** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */let pendingInteract = null;let pendingInteract = null;@@ -99,7 +111,20 @@ function uiBlocked (){{ return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking() || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking() || market?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking()); || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());}function applyGraphicsSettings (settings){ view?.setGraphicsPrefs(settings); if (socket && playing) { socket.send({ type: MessageType.setGraphicsSettings, viewDistance: settings.viewDistance }); }}}function clearPendingPickup ()function clearPendingPickup ()@@ -197,6 +222,28 @@ function requestOpenMarket (tileX, tileY) { approachAdjacentTile(tileX, tileY); } { approachAdjacentTile(tileX, tileY); }}}function requestOpenBounty (tileX, tileY){ clearAllPendingActions(); pendingInteract = { kind: "bounty", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); }}function requestOpenBarber (tileX, tileY){ clearAllPendingActions(); pendingInteract = { kind: "barber", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); }}function requestOpenCauldron (tileX, tileY)function requestOpenCauldron (tileX, tileY){{ clearAllPendingActions(); clearAllPendingActions();@@ -300,6 +347,24 @@ function flushPendingInteract () return; return; } } if (pendingInteract.kind === "bounty") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openBounty }); clearPendingInteract(); return; } if (pendingInteract.kind === "barber") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openBarber }); clearPendingInteract(); return; } if (pendingInteract.kind === "cauldron") if (pendingInteract.kind === "cauldron") { { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)@@ -467,6 +532,10 @@ function handleLeftClick (mouseX, mouseY) { requestOpenBank(tile.tileX, tile.tileY); } { requestOpenBank(tile.tileX, tile.tileY); } else if (isMarketplaceTile(view, tile.tileX, tile.tileY)) else if (isMarketplaceTile(view, tile.tileX, tile.tileY)) { requestOpenMarket(tile.tileX, tile.tileY); } { requestOpenMarket(tile.tileX, tile.tileY); } else if (isBountyOfficeTile(view, tile.tileX, tile.tileY)) { requestOpenBounty(tile.tileX, tile.tileY); } else if (isBarberTile(view, tile.tileX, tile.tileY)) { requestOpenBarber(tile.tileX, tile.tileY); } else if (isCauldronTile(view, tile.tileX, tile.tileY)) else if (isCauldronTile(view, tile.tileX, tile.tileY)) { requestOpenCauldron(tile.tileX, tile.tileY); } { requestOpenCauldron(tile.tileX, tile.tileY); } else if (isFurnaceTile(view, tile.tileX, tile.tileY)) else if (isFurnaceTile(view, tile.tileX, tile.tileY))@@ -588,6 +657,22 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isBountyOfficeTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Bounty Office", onSelect: () => requestOpenBounty(tile.tileX, tile.tileY) }); } if (isBarberTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Barber", onSelect: () => requestOpenBarber(tile.tileX, tile.tileY) }); } if (isCauldronTile(view, tile.tileX, tile.tileY)) if (isCauldronTile(view, tile.tileX, tile.tileY)) { { items.push({ items.push({@@ -702,18 +787,31 @@ function startPlay (payload) playing = true; playing = true; overlay.hidden = true; overlay.hidden = true; hud.hidden = false; hud.hidden = false; const settingsToggle = document.getElementById("settings-toggle"); if (settingsToggle) { settingsToggle.hidden = false; } document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`; document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`; gait = payload.gait ?? GAIT.walk; gait = payload.gait ?? GAIT.walk; document.getElementById("gait").textContent = gait; document.getElementById("gait").textContent = gait; staminaUi?.show(); staminaUi?.show(); healthUi?.show(); statusEffectsUi?.show(); if (payload.stamina != null) if (payload.stamina != null) { staminaUi?.apply(payload.stamina); } { staminaUi?.apply(payload.stamina); } if (payload.health != null || payload.maxHealth != null) { healthUi?.apply({ current: payload.health ?? healthUi.getCurrent?.(), max: payload.maxHealth ?? healthUi.getMax?.() }); } if (!scene) if (!scene) { { scene = new Scene(0, 0, window.innerWidth, window.innerHeight); scene = new Scene(0, 0, window.innerWidth, window.innerHeight); game.loadScene(scene); game.loadScene(scene); useNearestNeighbour(scene, game.images); useNearestNeighbour(scene, game.images); view = new WorldView(game, scene, catalog); view = new WorldView(game, scene, catalog); graphicsSettingsUi?.apply(); const ticker = new GameObject(0, 0, null, 10); const ticker = new GameObject(0, 0, null, 10); ticker.update = (dt) => ticker.update = (dt) => { {@@ -791,8 +889,11 @@ function startPlay (payload) payload.firstName, payload.firstName, payload.lastName, payload.lastName, payload.characterId, payload.characterId, payload.layers payload.layers, payload.health, payload.maxHealth ); ); graphicsSettingsUi?.apply();}}async function main ()async function main ()@@ -800,6 +901,24 @@ async function main () catalog = await loadSpriteCatalog(); catalog = await loadSpriteCatalog(); await preloadCatalogImages(game, catalog); await preloadCatalogImages(game, catalog); applySpriteSheets(game.images, catalog); applySpriteSheets(game.images, catalog); createHairControls = bindHairControls({ root: document.getElementById("create-hair"), resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, getSex: () => document.getElementById("sex")?.value ?? "male", hideHeadgear: true }); document.getElementById("sex")?.addEventListener("change", () => { createHairControls?.fillStyles(); void createHairControls?.refreshPreview(); }); void createHairControls?.refreshPreview(); graphicsSettingsUi = initGraphicsSettings({ onChange: applyGraphicsSettings }); social = initSocial({ social = initSocial({ socket: { send (payload) { socket.send(payload); } }, socket: { send (payload) { socket.send(payload); } }, MessageType MessageType@@ -845,6 +964,8 @@ async function main () } } }); }); staminaUi = initStamina(); staminaUi = initStamina(); healthUi = initHealth(); statusEffectsUi = initStatusEffects(); toasts = initToasts(); toasts = initToasts(); shop = initShop({ shop = initShop({ socket: { send (payload) { socket.send(payload); } }, socket: { send (payload) { socket.send(payload); } },@@ -872,6 +993,31 @@ async function main () return inventory?.getInventorySlots?.() ?? []; return inventory?.getInventorySlots?.() ?? []; } } }); }); bounty = initBounty({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; } }); barber = initBarber({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, getInventoryBag () { return { equipment: { slots: inventory?.getEquipment?.() ?? {} }, inventory: inventory?.getInventorySlots?.() ?? [] }; } }); chat = initChat({ chat = initChat({ socket: { send (payload) { socket.send(payload); } }, socket: { send (payload) { socket.send(payload); } }, MessageType, MessageType,@@ -898,6 +1044,7 @@ async function main () { overlay.hidden = false; } { overlay.hidden = false; } break; break; case MessageType.enterWorld: case MessageType.enterWorld: closeCreateModal(); startPlay(message); startPlay(message); inventory?.setLocalCharacterId(message.characterId); inventory?.setLocalCharacterId(message.characterId); break; break;@@ -961,6 +1108,10 @@ async function main () document.getElementById("gait").textContent = gait; document.getElementById("gait").textContent = gait; } } break; break; case MessageType.statusEffects: view?.setLocalBlind(!!message.blind); statusEffectsUi?.apply(message); break; case MessageType.bankSnapshot: case MessageType.bankSnapshot: inventory?.handleBank(message); inventory?.handleBank(message); break; break;@@ -1021,6 +1172,22 @@ async function main () market?.handleTrade(message); market?.handleTrade(message); toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`); toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`); break; break; case MessageType.bountySnapshot: bounty?.handleSnapshot(message); break; case MessageType.closeBounty: bounty?.handleClosed(message); break; case MessageType.characterBounty: bounty?.handleCharacterBounty(message); social?.handleCharacterBounty(message); break; case MessageType.barberSnapshot: barber?.handleSnapshot(message); break; case MessageType.closeBarber: barber?.handleClosed(message); break; case MessageType.itemBubble: case MessageType.itemBubble: chat?.showItemBubble(message); chat?.showItemBubble(message); break; break;@@ -1031,6 +1198,23 @@ async function main () view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); view?.flashDamage(message.targetId); view?.flashDamage(message.targetId); view?.spawnDamageNumber(message.targetId, message.damage); view?.spawnDamageNumber(message.targetId, message.damage); if (message.targetId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } break; case MessageType.entityHealth: view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } break; break; case MessageType.skillLevelUp: case MessageType.skillLevelUp: view?.spawnSkillLevelUp(message.entityId, message); view?.spawnSkillLevelUp(message.entityId, message);@@ -1044,10 +1228,22 @@ async function main () clearAllPendingActions(); clearAllPendingActions(); contextMenu?.hide(); contextMenu?.hide(); death?.show(); death?.show(); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: 0, max: healthUi.getMax?.() }); view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.()); } break; break; case MessageType.playerRespawned: case MessageType.playerRespawned: death?.hide(); death?.hide(); view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } if (message.stamina != null || message.maxStamina != null) if (message.stamina != null || message.maxStamina != null) { { staminaUi?.apply({ staminaUi?.apply({@@ -1060,7 +1256,14 @@ async function main () if (playing) if (playing) { toasts?.show(message.message); } { toasts?.show(message.message); } else else { showError(message.message); } { const createPanel = document.getElementById("create-panel"); const createError = document.getElementById("create-error"); if (createPanel && !createPanel.hidden && createError) { createError.textContent = message.message ?? ""; } else { showError(message.message); } } social?.showError(message.message); social?.showError(message.message); break; break; case MessageType.toast: case MessageType.toast:@@ -1098,10 +1301,14 @@ function returnToMenu (reason = "") crafting?.reset(); crafting?.reset(); alchemy?.reset(); alchemy?.reset(); staminaUi?.hide(); staminaUi?.hide(); healthUi?.hide(); statusEffectsUi?.hide(); skills?.hide(); skills?.hide(); contextMenu?.hide(); contextMenu?.hide(); death?.reset(); death?.reset(); shop?.close({ notifyServer: false }); shop?.close({ notifyServer: false }); bounty?.close(); barber?.close(); hideWorldTooltip(); hideWorldTooltip(); if (view) if (view) { {@@ -1113,19 +1320,47 @@ function returnToMenu (reason = "") } } overlay.hidden = false; overlay.hidden = false; hud.hidden = true; hud.hidden = true; const settingsToggle = document.getElementById("settings-toggle"); if (settingsToggle) { settingsToggle.hidden = true; } graphicsSettingsUi?.close(); if (reason) if (reason) { statusEl.textContent = reason; } { statusEl.textContent = reason; }}}document.getElementById("create-character-open")?.addEventListener("click", () =>{ showError(""); const createError = document.getElementById("create-error"); if (createError) { createError.textContent = ""; } document.getElementById("create-backdrop").hidden = false; document.getElementById("create-panel").hidden = false; void createHairControls?.refreshPreview();});function closeCreateModal (){ document.getElementById("create-backdrop").hidden = true; document.getElementById("create-panel").hidden = true;}document.getElementById("create-close")?.addEventListener("click", closeCreateModal);document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);document.getElementById("create-form").addEventListener("submit", (event) =>document.getElementById("create-form").addEventListener("submit", (event) =>{{ event.preventDefault(); event.preventDefault(); showError(""); showError(""); const createError = document.getElementById("create-error"); if (createError) { createError.textContent = ""; } socket.send({ socket.send({ type: MessageType.createCharacter, type: MessageType.createCharacter, firstName: document.getElementById("first-name").value, firstName: document.getElementById("first-name").value, lastName: document.getElementById("last-name").value, lastName: document.getElementById("last-name").value, sex: document.getElementById("sex").value sex: document.getElementById("sex").value, hair: createHairControls?.currentHair?.() ?? null }); });});});@@ -1151,6 +1386,16 @@ function isMarketplaceTile (view, tileX, tileY) return blockTypeAt(view, tileX, tileY) === BlockType.marketplace; return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;}}function isBountyOfficeTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;}function isBarberTile (view, tileX, tileY){ return blockTypeAt(view, tileX, tileY) === BlockType.barber;}function isCauldronTile (view, tileX, tileY)function isCauldronTile (view, tileX, tileY){{ return blockTypeAt(view, tileX, tileY) === BlockType.cauldron; return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;@@ -4,6 +4,7 @@ export function initSocial ({ socket, MessageType })
const inspect = document.getElementById("inspect-modal");
const inspectBackdrop = document.getElementById("inspect-backdrop");
const inspectName = document.getElementById("inspect-name");
const inspectBounty = document.getElementById("inspect-bounty");
const inspectAction = document.getElementById("inspect-action");
const inspectError = document.getElementById("inspect-error");
const friendsPanel = document.getElementById("friends-panel");
@@ -28,6 +29,11 @@ export function initSocial ({ socket, MessageType })
inspect.hidden = true;
inspectBackdrop.hidden = true;
inspectError.textContent = "";
if (inspectBounty)
{
inspectBounty.hidden = true;
inspectBounty.textContent = "";
}
}
function relation (characterId)
@@ -171,9 +177,35 @@ export function initSocial ({ socket, MessageType })
};
open = true;
inspectError.textContent = "";
if (inspectBounty)
{
inspectBounty.hidden = true;
inspectBounty.textContent = "";
}
inspect.hidden = false;
inspectBackdrop.hidden = false;
renderInspect();
socket.send({
type: MessageType.getCharacterBounty,
characterId: entity.characterId
});
},
handleCharacterBounty (message)
{
if (!open || !inspected || !inspectBounty)
{ return; }
const target = message.target;
if (!target || target.characterId !== inspected.characterId)
{ return; }
const amount = target.amountCopper | 0;
if (amount <= 0)
{
inspectBounty.hidden = true;
inspectBounty.textContent = "";
return;
}
inspectBounty.hidden = false;
inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`;
},
hideInspect,
reset ()
@@ -4,6 +4,7 @@ export function initSocial ({ socket, MessageType }) const inspect = document.getElementById("inspect-modal"); const inspect = document.getElementById("inspect-modal"); const inspectBackdrop = document.getElementById("inspect-backdrop"); const inspectBackdrop = document.getElementById("inspect-backdrop"); const inspectName = document.getElementById("inspect-name"); const inspectName = document.getElementById("inspect-name"); const inspectBounty = document.getElementById("inspect-bounty"); const inspectAction = document.getElementById("inspect-action"); const inspectAction = document.getElementById("inspect-action"); const inspectError = document.getElementById("inspect-error"); const inspectError = document.getElementById("inspect-error"); const friendsPanel = document.getElementById("friends-panel"); const friendsPanel = document.getElementById("friends-panel");@@ -28,6 +29,11 @@ export function initSocial ({ socket, MessageType }) inspect.hidden = true; inspect.hidden = true; inspectBackdrop.hidden = true; inspectBackdrop.hidden = true; inspectError.textContent = ""; inspectError.textContent = ""; if (inspectBounty) { inspectBounty.hidden = true; inspectBounty.textContent = ""; } } } function relation (characterId) function relation (characterId)@@ -171,9 +177,35 @@ export function initSocial ({ socket, MessageType }) }; }; open = true; open = true; inspectError.textContent = ""; inspectError.textContent = ""; if (inspectBounty) { inspectBounty.hidden = true; inspectBounty.textContent = ""; } inspect.hidden = false; inspect.hidden = false; inspectBackdrop.hidden = false; inspectBackdrop.hidden = false; renderInspect(); renderInspect(); socket.send({ type: MessageType.getCharacterBounty, characterId: entity.characterId }); }, handleCharacterBounty (message) { if (!open || !inspected || !inspectBounty) { return; } const target = message.target; if (!target || target.characterId !== inspected.characterId) { return; } const amount = target.amountCopper | 0; if (amount <= 0) { inspectBounty.hidden = true; inspectBounty.textContent = ""; return; } inspectBounty.hidden = false; inspectBounty.textContent = `Bounty: ${target.amountLabel ?? amount}`; }, }, hideInspect, hideInspect, reset () reset ()@@ -1,14 +1,23 @@
export function initStamina ()
{
let vitals = document.getElementById("vitals");
if (!vitals)
{
vitals = document.createElement("div");
vitals.id = "vitals";
vitals.hidden = true;
document.body.append(vitals);
}
let bar = document.getElementById("stamina-bar");
if (!bar)
{
bar = document.createElement("div");
bar.id = "stamina-bar";
bar.hidden = true;
bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>';
document.body.append(bar);
vitals.append(bar);
}
else if (bar.parentElement !== vitals)
{ vitals.append(bar); }
const fill = document.getElementById("stamina-bar-fill");
const label = document.getElementById("stamina-bar-label");
@@ -27,12 +36,12 @@ export function initStamina ()
return {
show ()
{
bar.hidden = false;
vitals.hidden = false;
render();
},
hide ()
{
bar.hidden = true;
vitals.hidden = true;
},
apply (message)
{
@@ -1,14 +1,23 @@export function initStamina ()export function initStamina (){{ let vitals = document.getElementById("vitals"); if (!vitals) { vitals = document.createElement("div"); vitals.id = "vitals"; vitals.hidden = true; document.body.append(vitals); } let bar = document.getElementById("stamina-bar"); let bar = document.getElementById("stamina-bar"); if (!bar) if (!bar) { { bar = document.createElement("div"); bar = document.createElement("div"); bar.id = "stamina-bar"; bar.id = "stamina-bar"; bar.hidden = true; bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>'; bar.innerHTML = '<div id="stamina-bar-fill"></div><span id="stamina-bar-label" class="stamina-bar-label"></span>'; document.body.append(bar); vitals.append(bar); } } else if (bar.parentElement !== vitals) { vitals.append(bar); } const fill = document.getElementById("stamina-bar-fill"); const fill = document.getElementById("stamina-bar-fill"); const label = document.getElementById("stamina-bar-label"); const label = document.getElementById("stamina-bar-label");@@ -27,12 +36,12 @@ export function initStamina () return { return { show () show () { { bar.hidden = false; vitals.hidden = false; render(); render(); }, }, hide () hide () { { bar.hidden = true; vitals.hidden = true; }, }, apply (message) apply (message) { {@@ -0,0 +1,211 @@
import {
statusEffectDisplay,
statusEffectIconPath,
formatStatusRemaining
} from "/shared/statusEffects/display.js";
export function initStatusEffects ()
{
let vitals = document.getElementById("vitals");
if (!vitals)
{
vitals = document.createElement("div");
vitals.id = "vitals";
vitals.hidden = true;
document.body.append(vitals);
}
let rail = document.getElementById("status-effects");
if (!rail)
{
rail = document.createElement("div");
rail.id = "status-effects";
rail.setAttribute("aria-label", "Active effects");
vitals.prepend(rail);
}
else if (rail.parentElement !== vitals)
{ vitals.prepend(rail); }
let tip = document.getElementById("status-effect-tooltip");
if (!tip)
{
tip = document.createElement("div");
tip.id = "status-effect-tooltip";
tip.hidden = true;
document.body.append(tip);
}
/** @type {Array<{ type: string, expiresAt: number, amount?: number, amountPerSecond?: number, scale?: number }>} */
let effects = [];
let hoverType = null;
let tickId = 0;
function remainingMs (entry, now = Date.now())
{
return Math.max(0, (entry.expiresAt | 0) - now);
}
function prune (now = Date.now())
{
effects = effects.filter((entry) => remainingMs(entry, now) > 0);
}
function hideTip ()
{
hoverType = null;
tip.hidden = true;
}
function showTipFor (entry, anchor)
{
const display = statusEffectDisplay(entry.type);
if (!display)
{
hideTip();
return;
}
hoverType = entry.type;
const left = remainingMs(entry);
tip.innerHTML = "";
const title = document.createElement("strong");
title.textContent = display.title;
const body = document.createElement("p");
body.textContent = display.describe(entry);
const time = document.createElement("p");
time.className = "status-effect-tooltip-time";
time.textContent = left > 0 ? `${formatStatusRemaining(left)} remaining` : "Expired";
tip.append(title, body, time);
tip.hidden = false;
tip.dataset.polarity = display.polarity;
const rect = anchor.getBoundingClientRect();
const tipW = tip.offsetWidth || 180;
const tipH = tip.offsetHeight || 60;
let leftPx = rect.left - tipW - 8;
if (leftPx < 8)
{ leftPx = rect.right + 8; }
let topPx = rect.bottom - tipH;
if (topPx < 8)
{ topPx = 8; }
if (topPx + tipH > window.innerHeight - 8)
{ topPx = window.innerHeight - tipH - 8; }
tip.style.left = `${leftPx}px`;
tip.style.top = `${topPx}px`;
}
function refreshTip ()
{
if (!hoverType)
{ return; }
const entry = effects.find((row) => row.type === hoverType);
const btn = rail.querySelector(`[data-effect-type="${hoverType}"]`);
if (!entry || !btn)
{
hideTip();
return;
}
showTipFor(entry, btn);
}
function render ()
{
const now = Date.now();
prune(now);
rail.replaceChildren();
for (const entry of effects)
{
const display = statusEffectDisplay(entry.type);
if (!display)
{ continue; }
const btn = document.createElement("button");
btn.type = "button";
btn.className = `status-effect-icon status-effect-${display.polarity}`;
btn.dataset.effectType = entry.type;
btn.setAttribute("aria-label", display.title);
const img = document.createElement("img");
img.src = statusEffectIconPath(entry.type);
img.alt = "";
img.draggable = false;
img.addEventListener("error", () =>
{
img.remove();
btn.classList.add("status-effect-icon-fallback");
btn.textContent = display.title.slice(0, 1);
}, { once: true });
btn.append(img);
btn.addEventListener("mouseenter", () => showTipFor(entry, btn));
btn.addEventListener("mouseleave", hideTip);
btn.addEventListener("focus", () => showTipFor(entry, btn));
btn.addEventListener("blur", hideTip);
rail.append(btn);
}
rail.hidden = effects.length === 0;
refreshTip();
}
function stopTick ()
{
if (tickId)
{
clearInterval(tickId);
tickId = 0;
}
}
function ensureTick ()
{
if (tickId || effects.length === 0)
{ return; }
tickId = setInterval(() =>
{
const before = effects.length;
prune();
if (effects.length !== before)
{ render(); }
else
{ refreshTip(); }
if (effects.length === 0)
{ stopTick(); }
}, 250);
}
return {
apply (message)
{
const list = Array.isArray(message?.effects) ? message.effects : [];
effects = list
.filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now())
.map((entry) => ({
type: entry.type,
expiresAt: entry.expiresAt | 0,
amount: entry.amount | 0,
amountPerSecond: Number(entry.amountPerSecond) || 0,
scale: entry.scale ?? null,
lightRadiusTiles: entry.lightRadiusTiles ?? null
}));
render();
if (effects.length)
{ ensureTick(); }
else
{
stopTick();
hideTip();
}
},
clear ()
{
effects = [];
stopTick();
hideTip();
render();
},
show ()
{
vitals.hidden = false;
render();
},
hide ()
{
this.clear();
}
};
}
@@ -0,0 +1,211 @@import { statusEffectDisplay, statusEffectIconPath, formatStatusRemaining} from "/shared/statusEffects/display.js";export function initStatusEffects (){ let vitals = document.getElementById("vitals"); if (!vitals) { vitals = document.createElement("div"); vitals.id = "vitals"; vitals.hidden = true; document.body.append(vitals); } let rail = document.getElementById("status-effects"); if (!rail) { rail = document.createElement("div"); rail.id = "status-effects"; rail.setAttribute("aria-label", "Active effects"); vitals.prepend(rail); } else if (rail.parentElement !== vitals) { vitals.prepend(rail); } let tip = document.getElementById("status-effect-tooltip"); if (!tip) { tip = document.createElement("div"); tip.id = "status-effect-tooltip"; tip.hidden = true; document.body.append(tip); } /** @type {Array<{ type: string, expiresAt: number, amount?: number, amountPerSecond?: number, scale?: number }>} */ let effects = []; let hoverType = null; let tickId = 0; function remainingMs (entry, now = Date.now()) { return Math.max(0, (entry.expiresAt | 0) - now); } function prune (now = Date.now()) { effects = effects.filter((entry) => remainingMs(entry, now) > 0); } function hideTip () { hoverType = null; tip.hidden = true; } function showTipFor (entry, anchor) { const display = statusEffectDisplay(entry.type); if (!display) { hideTip(); return; } hoverType = entry.type; const left = remainingMs(entry); tip.innerHTML = ""; const title = document.createElement("strong"); title.textContent = display.title; const body = document.createElement("p"); body.textContent = display.describe(entry); const time = document.createElement("p"); time.className = "status-effect-tooltip-time"; time.textContent = left > 0 ? `${formatStatusRemaining(left)} remaining` : "Expired"; tip.append(title, body, time); tip.hidden = false; tip.dataset.polarity = display.polarity; const rect = anchor.getBoundingClientRect(); const tipW = tip.offsetWidth || 180; const tipH = tip.offsetHeight || 60; let leftPx = rect.left - tipW - 8; if (leftPx < 8) { leftPx = rect.right + 8; } let topPx = rect.bottom - tipH; if (topPx < 8) { topPx = 8; } if (topPx + tipH > window.innerHeight - 8) { topPx = window.innerHeight - tipH - 8; } tip.style.left = `${leftPx}px`; tip.style.top = `${topPx}px`; } function refreshTip () { if (!hoverType) { return; } const entry = effects.find((row) => row.type === hoverType); const btn = rail.querySelector(`[data-effect-type="${hoverType}"]`); if (!entry || !btn) { hideTip(); return; } showTipFor(entry, btn); } function render () { const now = Date.now(); prune(now); rail.replaceChildren(); for (const entry of effects) { const display = statusEffectDisplay(entry.type); if (!display) { continue; } const btn = document.createElement("button"); btn.type = "button"; btn.className = `status-effect-icon status-effect-${display.polarity}`; btn.dataset.effectType = entry.type; btn.setAttribute("aria-label", display.title); const img = document.createElement("img"); img.src = statusEffectIconPath(entry.type); img.alt = ""; img.draggable = false; img.addEventListener("error", () => { img.remove(); btn.classList.add("status-effect-icon-fallback"); btn.textContent = display.title.slice(0, 1); }, { once: true }); btn.append(img); btn.addEventListener("mouseenter", () => showTipFor(entry, btn)); btn.addEventListener("mouseleave", hideTip); btn.addEventListener("focus", () => showTipFor(entry, btn)); btn.addEventListener("blur", hideTip); rail.append(btn); } rail.hidden = effects.length === 0; refreshTip(); } function stopTick () { if (tickId) { clearInterval(tickId); tickId = 0; } } function ensureTick () { if (tickId || effects.length === 0) { return; } tickId = setInterval(() => { const before = effects.length; prune(); if (effects.length !== before) { render(); } else { refreshTip(); } if (effects.length === 0) { stopTick(); } }, 250); } return { apply (message) { const list = Array.isArray(message?.effects) ? message.effects : []; effects = list .filter((entry) => entry?.type && (entry.expiresAt | 0) > Date.now()) .map((entry) => ({ type: entry.type, expiresAt: entry.expiresAt | 0, amount: entry.amount | 0, amountPerSecond: Number(entry.amountPerSecond) || 0, scale: entry.scale ?? null, lightRadiusTiles: entry.lightRadiusTiles ?? null })); render(); if (effects.length) { ensureTick(); } else { stopTick(); hideTip(); } }, clear () { effects = []; stopTick(); hideTip(); render(); }, show () { vitals.hidden = false; render(); }, hide () { this.clear(); } };}@@ -203,6 +203,11 @@ export class WorldView
this.groundItems = new Map();
this.edges = new Map();
this.localEntityId = null;
this.localBlind = false;
/** @type {"soft"|"simple"} */
this.lightingMode = "soft";
/** @type {boolean} */
this.bloomEnabled = true;
this.settings = { ...DEFAULT_WORLD_SETTINGS };
this.worldHour = 12;
/** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
@@ -228,6 +233,27 @@ export class WorldView
this.#syncBloomLayer();
}
/**
* Client graphics prefs (lighting Soft/Simple, bloom On/Off).
* @param {{ lighting?: string, bloom?: string }} prefs
*/
setGraphicsPrefs (prefs)
{
if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
{ this.lightingMode = prefs.lighting; }
if (prefs?.bloom === "off" || prefs?.bloom === "on")
{
const enabled = prefs.bloom !== "off";
if (enabled !== this.bloomEnabled)
{
this.bloomEnabled = enabled;
this.#syncBloomLayer();
}
else
{ this.bloomEnabled = enabled; }
}
}
/** Apply server (or local) calendar season; rebakes chunks when it changes. */
setWorldSeason (season)
{
@@ -240,7 +266,7 @@ export class WorldView
this.#rebakeAllChunks();
}
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
{
this.localEntityId = entityId;
this.#upsertEntity({
@@ -252,7 +278,9 @@ export class WorldView
sex,
firstName,
lastName,
layers: layers ?? undefined
layers: layers ?? undefined,
...(health != null ? { health } : {}),
...(maxHealth != null ? { maxHealth } : {})
});
}
@@ -454,6 +482,8 @@ export class WorldView
if (!existing)
{ return; }
existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
if (payload.visualScale != null)
{ existing.visualScale = Number(payload.visualScale) || 1; }
this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
this.#placeEntity(existing);
}
@@ -654,6 +684,7 @@ export class WorldView
this.#updateDamageNumbers(now);
this.#updateSkillLevelFloats(now);
this.#centerCamera();
this.#cullOffscreenDrawables();
this.#updateShade(deltaTime);
}
@@ -963,6 +994,82 @@ export class WorldView
this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
}
/**
* World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
* Tiles fully outside this rect are not drawn.
*/
#drawBounds ()
{
const pad = this.tileSize() * 0.5;
const camX = this.scene.cameraPosition.x;
const camY = this.scene.cameraPosition.y;
const w = this.scene.real_size.x;
const h = this.scene.real_size.y;
return {
left: -camX - pad,
right: -camX + w + pad,
top: -camY - pad,
bottom: -camY + h + pad
};
}
#rectIntersects (left, top, right, bottom, bounds)
{
return right >= bounds.left
&& left <= bounds.right
&& bottom >= bounds.top
&& top <= bounds.bottom;
}
#setRendererVisible (object, visible)
{
if (object?.renderer)
{ object.renderer.visible = !!visible; }
}
/** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
#cullOffscreenDrawables ()
{
const bounds = this.#drawBounds();
const size = this.tileSize();
for (const baked of this.bakedChunks.values())
{
const left = baked.chunkX * CHUNK_SIZE * size;
const top = baked.chunkY * CHUNK_SIZE * size;
const chunkPx = CHUNK_SIZE * size;
const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
this.#setRendererVisible(baked.groundObject, chunkVisible);
this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
baked._inViewport = chunkVisible;
for (let row = 0; row < CHUNK_SIZE; row++)
{
const rowTop = top + row * size;
const rowVisible = chunkVisible && this.#rectIntersects(
left, rowTop, left + chunkPx, rowTop + size, bounds
);
this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
}
}
for (const objects of this.tiles.values())
{
const left = objects.tileX * size;
const top = objects.tileY * size;
const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
objects._inViewport = visible;
this.#setRendererVisible(objects.ground, visible);
this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
this.#setRendererVisible(objects.block, visible);
this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
if (objects.waterEdges)
{
for (const edge of Object.values(objects.waterEdges))
{ this.#setRendererVisible(edge, visible); }
}
}
}
#upsertEntity (payload)
{
const size = this.tileSize();
@@ -995,6 +1102,10 @@ export class WorldView
entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
if (payload.visualScale != null)
{ entity.visualScale = Number(payload.visualScale) || 1; }
else if (entity.visualScale == null)
{ entity.visualScale = 1; }
if (payload.health != null)
{ entity.health = payload.health; }
if (payload.maxHealth != null)
@@ -1147,20 +1258,23 @@ export class WorldView
entity.object.transform.rotation = walkTilt;
this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY, entity.visualScale ?? 1);
for (let index = 0; index < (entity.overlays ?? []).length; index++)
{
const overlay = entity.overlays[index];
const overlaySortY = entity.visualY + 0.5 * (index + 1);
overlay.transform.rotation = walkTilt;
this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
}
for (const overlay of entity.bloomOverlays ?? [])
{
this.#setRendererVisible(overlay, this.bloomEnabled);
if (!this.bloomEnabled)
{ continue; }
overlay.transform.rotation = walkTilt;
this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
}
this.#placeHpBar(entity, pivotX, pivotY);
}
@@ -1285,13 +1399,22 @@ export class WorldView
const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
const localX = objects.tileX - chunkX * CHUNK_SIZE;
const localY = objects.tileY - chunkY * CHUNK_SIZE;
const corners = chunkBaked
? this.#tileLitCorners(chunkBaked, localX, localY)
: null;
let litCorners = null;
if (chunkBaked)
{
if (this.lightingMode === "simple")
{
const gridW = CHUNK_SIZE + 2;
const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
}
else
{ litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
}
objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
this.#syncWaterGroundSprite(
objects.ground,
corners,
litCorners,
ambientDark,
objects.waterEdges,
timeSec,
@@ -1302,7 +1425,32 @@ export class WorldView
#ambientDarkness ()
{
const hour = this.nightPreview ?? this.worldHour;
return nightFactor(hour, this.settings.nightDarkness);
let dark = nightFactor(hour, this.settings.nightDarkness);
if (this.localBlind)
{ dark = Math.min(1, dark + 0.85); }
return dark;
}
setLocalBlind (blind)
{
this.localBlind = !!blind;
}
/** Soft vision bubble while blinded (client-only; stacks with ambient). */
#blindVisionLight ()
{
if (!this.localBlind)
{ return null; }
const local = this.entities.get(this.localEntityId);
if (!local)
{ return null; }
const tileSize = this.tileSize();
return {
tileX: Math.floor(local.visualX / tileSize),
tileY: Math.floor(local.visualY / tileSize),
range: 2.25,
intensity: 1
};
}
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
@@ -1316,8 +1464,7 @@ export class WorldView
{
const current = entity.health;
const max = entity.maxHealth;
const show = entity.mobTypeId != null
&& current != null
const show = current != null
&& max != null
&& max > 0
&& current < max;
@@ -1636,17 +1783,18 @@ export class WorldView
return object;
}
#placePivoted (object, pivotX, pivotY, sortY, subOrder)
#placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
{
const sprite = object?.renderer?.sprite;
if (!sprite)
{ return; }
const zoom = this.zoom;
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
const factor = Math.max(0.1, Number(scale) || 1);
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
object.transform.position.x = center.x;
object.transform.position.y = center.y;
object.transform.size = new vector(draw.w, draw.h);
object.transform.size = new vector(draw.w * factor, draw.h * factor);
object.layer = ySortLayer(sortY, subOrder);
this.#markSortDirty();
}
@@ -1787,6 +1935,9 @@ export class WorldView
const activeLights = [...this.dynamicLights];
const tileSize = this.tileSize();
const blindLight = this.#blindVisionLight();
if (blindLight)
{ activeLights.push(blindLight); }
for (const entity of this.entities.values())
{
const range = entity.lightRadiusTiles ?? 0;
@@ -1804,12 +1955,16 @@ export class WorldView
for (const objects of this.tiles.values())
{
if (objects._inViewport === false)
{ continue; }
const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
objects.shadeAlpha = ambientDark * (1 - intensity);
}
for (const baked of this.bakedChunks.values())
{
if (baked._inViewport === false)
{ continue; }
this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
if (baked.groundObject?.renderer?.shaderUniforms)
{ baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
@@ -1823,6 +1978,8 @@ export class WorldView
const timeSec = now / 1000;
for (const objects of this.tiles.values())
{
if (objects._inViewport === false)
{ continue; }
if (objects.block)
{ this.#syncLitSprite(objects.block, objects.shadeAlpha); }
if (objects.ground && isWaterGround(objects.groundTypeId))
@@ -1995,18 +2152,37 @@ export class WorldView
const pixels = baked.lightmapPixels;
this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
const simple = this.lightingMode === "simple";
for (let localY = 0; localY < CHUNK_SIZE; localY++)
{
for (let localX = 0; localX < CHUNK_SIZE; localX++)
{
const baseX = localX * SPRITE_SIZE_PX;
const baseY = localY * SPRITE_SIZE_PX;
if (simple)
{
const gridW = CHUNK_SIZE + 2;
const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
for (let py = 0; py < SPRITE_SIZE_PX; py++)
{
for (let px = 0; px < SPRITE_SIZE_PX; px++)
{
const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
pixels[offset] = value;
pixels[offset + 1] = value;
pixels[offset + 2] = value;
pixels[offset + 3] = 255;
}
}
continue;
}
const corners = this.#tileLitCorners(baked, localX, localY);
const nw = corners.nw;
const ne = corners.ne;
const sw = corners.sw;
const se = corners.se;
const baseX = localX * SPRITE_SIZE_PX;
const baseY = localY * SPRITE_SIZE_PX;
for (let py = 0; py < SPRITE_SIZE_PX; py++)
{
const v = (py + 0.5) / SPRITE_SIZE_PX;
@@ -2141,6 +2317,11 @@ export class WorldView
#syncBloomLayer ()
{
if (!this.bloomEnabled)
{
this.scene.setLayers([{ name: "default" }]);
return;
}
const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
this.scene.setLayers([
{ name: "default" },
@@ -203,6 +203,11 @@ export class WorldView this.groundItems = new Map(); this.groundItems = new Map(); this.edges = new Map(); this.edges = new Map(); this.localEntityId = null; this.localEntityId = null; this.localBlind = false; /** @type {"soft"|"simple"} */ this.lightingMode = "soft"; /** @type {boolean} */ this.bloomEnabled = true; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.worldHour = 12; this.worldHour = 12; /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */ /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */@@ -228,6 +233,27 @@ export class WorldView this.#syncBloomLayer(); this.#syncBloomLayer(); } } /** * Client graphics prefs (lighting Soft/Simple, bloom On/Off). * @param {{ lighting?: string, bloom?: string }} prefs */ setGraphicsPrefs (prefs) { if (prefs?.lighting === "simple" || prefs?.lighting === "soft") { this.lightingMode = prefs.lighting; } if (prefs?.bloom === "off" || prefs?.bloom === "on") { const enabled = prefs.bloom !== "off"; if (enabled !== this.bloomEnabled) { this.bloomEnabled = enabled; this.#syncBloomLayer(); } else { this.bloomEnabled = enabled; } } } /** Apply server (or local) calendar season; rebakes chunks when it changes. */ /** Apply server (or local) calendar season; rebakes chunks when it changes. */ setWorldSeason (season) setWorldSeason (season) { {@@ -240,7 +266,7 @@ export class WorldView this.#rebakeAllChunks(); this.#rebakeAllChunks(); } } setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null) { { this.localEntityId = entityId; this.localEntityId = entityId; this.#upsertEntity({ this.#upsertEntity({@@ -252,7 +278,9 @@ export class WorldView sex, sex, firstName, firstName, lastName, lastName, layers: layers ?? undefined layers: layers ?? undefined, ...(health != null ? { health } : {}), ...(maxHealth != null ? { maxHealth } : {}) }); }); } }@@ -454,6 +482,8 @@ export class WorldView if (!existing) if (!existing) { return; } { return; } existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; if (payload.visualScale != null) { existing.visualScale = Number(payload.visualScale) || 1; } this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#placeEntity(existing); this.#placeEntity(existing); } }@@ -654,6 +684,7 @@ export class WorldView this.#updateDamageNumbers(now); this.#updateDamageNumbers(now); this.#updateSkillLevelFloats(now); this.#updateSkillLevelFloats(now); this.#centerCamera(); this.#centerCamera(); this.#cullOffscreenDrawables(); this.#updateShade(deltaTime); this.#updateShade(deltaTime); } }@@ -963,6 +994,82 @@ export class WorldView this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; } } /** * World-pixel AABB of the screen, expanded by half a tile (zoom-aware). * Tiles fully outside this rect are not drawn. */ #drawBounds () { const pad = this.tileSize() * 0.5; const camX = this.scene.cameraPosition.x; const camY = this.scene.cameraPosition.y; const w = this.scene.real_size.x; const h = this.scene.real_size.y; return { left: -camX - pad, right: -camX + w + pad, top: -camY - pad, bottom: -camY + h + pad }; } #rectIntersects (left, top, right, bottom, bounds) { return right >= bounds.left && left <= bounds.right && bottom >= bounds.top && top <= bounds.bottom; } #setRendererVisible (object, visible) { if (object?.renderer) { object.renderer.visible = !!visible; } } /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ #cullOffscreenDrawables () { const bounds = this.#drawBounds(); const size = this.tileSize(); for (const baked of this.bakedChunks.values()) { const left = baked.chunkX * CHUNK_SIZE * size; const top = baked.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); this.#setRendererVisible(baked.groundObject, chunkVisible); this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); baked._inViewport = chunkVisible; for (let row = 0; row < CHUNK_SIZE; row++) { const rowTop = top + row * size; const rowVisible = chunkVisible && this.#rectIntersects( left, rowTop, left + chunkPx, rowTop + size, bounds ); this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); } } for (const objects of this.tiles.values()) { const left = objects.tileX * size; const top = objects.tileY * size; const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); objects._inViewport = visible; this.#setRendererVisible(objects.ground, visible); this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); this.#setRendererVisible(objects.block, visible); this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); if (objects.waterEdges) { for (const edge of Object.values(objects.waterEdges)) { this.#setRendererVisible(edge, visible); } } } } #upsertEntity (payload) #upsertEntity (payload) { { const size = this.tileSize(); const size = this.tileSize();@@ -995,6 +1102,10 @@ export class WorldView entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; if (payload.visualScale != null) { entity.visualScale = Number(payload.visualScale) || 1; } else if (entity.visualScale == null) { entity.visualScale = 1; } if (payload.health != null) if (payload.health != null) { entity.health = payload.health; } { entity.health = payload.health; } if (payload.maxHealth != null) if (payload.maxHealth != null)@@ -1147,20 +1258,23 @@ export class WorldView entity.object.transform.rotation = walkTilt; entity.object.transform.rotation = walkTilt; this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY, entity.visualScale ?? 1); for (let index = 0; index < (entity.overlays ?? []).length; index++) for (let index = 0; index < (entity.overlays ?? []).length; index++) { { const overlay = entity.overlays[index]; const overlay = entity.overlays[index]; const overlaySortY = entity.visualY + 0.5 * (index + 1); const overlaySortY = entity.visualY + 0.5 * (index + 1); overlay.transform.rotation = walkTilt; overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null); this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null); this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY); this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1); } } for (const overlay of entity.bloomOverlays ?? []) for (const overlay of entity.bloomOverlays ?? []) { { this.#setRendererVisible(overlay, this.bloomEnabled); if (!this.bloomEnabled) { continue; } overlay.transform.rotation = walkTilt; overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength, wade); this.#syncLitSprite(overlay, tileShade, flashStrength, wade); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY, entity.visualScale ?? 1); } } this.#placeHpBar(entity, pivotX, pivotY); this.#placeHpBar(entity, pivotX, pivotY); } }@@ -1285,13 +1399,22 @@ export class WorldView const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); const localX = objects.tileX - chunkX * CHUNK_SIZE; const localX = objects.tileX - chunkX * CHUNK_SIZE; const localY = objects.tileY - chunkY * CHUNK_SIZE; const localY = objects.tileY - chunkY * CHUNK_SIZE; const corners = chunkBaked let litCorners = null; ? this.#tileLitCorners(chunkBaked, localX, localY) if (chunkBaked) : null; { if (this.lightingMode === "simple") { const gridW = CHUNK_SIZE + 2; const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; } else { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } } objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); this.#syncWaterGroundSprite( this.#syncWaterGroundSprite( objects.ground, objects.ground, corners, litCorners, ambientDark, ambientDark, objects.waterEdges, objects.waterEdges, timeSec, timeSec,@@ -1302,7 +1425,32 @@ export class WorldView #ambientDarkness () #ambientDarkness () { { const hour = this.nightPreview ?? this.worldHour; const hour = this.nightPreview ?? this.worldHour; return nightFactor(hour, this.settings.nightDarkness); let dark = nightFactor(hour, this.settings.nightDarkness); if (this.localBlind) { dark = Math.min(1, dark + 0.85); } return dark; } setLocalBlind (blind) { this.localBlind = !!blind; } /** Soft vision bubble while blinded (client-only; stacks with ambient). */ #blindVisionLight () { if (!this.localBlind) { return null; } const local = this.entities.get(this.localEntityId); if (!local) { return null; } const tileSize = this.tileSize(); return { tileX: Math.floor(local.visualX / tileSize), tileY: Math.floor(local.visualY / tileSize), range: 2.25, intensity: 1 }; } } #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY) #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)@@ -1316,8 +1464,7 @@ export class WorldView { { const current = entity.health; const current = entity.health; const max = entity.maxHealth; const max = entity.maxHealth; const show = entity.mobTypeId != null const show = current != null && current != null && max != null && max != null && max > 0 && max > 0 && current < max; && current < max;@@ -1636,17 +1783,18 @@ export class WorldView return object; return object; } } #placePivoted (object, pivotX, pivotY, sortY, subOrder) #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1) { { const sprite = object?.renderer?.sprite; const sprite = object?.renderer?.sprite; if (!sprite) if (!sprite) { return; } { return; } const zoom = this.zoom; const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); const factor = Math.max(0.1, Number(scale) || 1); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom); object.transform.position.x = center.x; object.transform.position.x = center.x; object.transform.position.y = center.y; object.transform.position.y = center.y; object.transform.size = new vector(draw.w, draw.h); object.transform.size = new vector(draw.w * factor, draw.h * factor); object.layer = ySortLayer(sortY, subOrder); object.layer = ySortLayer(sortY, subOrder); this.#markSortDirty(); this.#markSortDirty(); } }@@ -1787,6 +1935,9 @@ export class WorldView const activeLights = [...this.dynamicLights]; const activeLights = [...this.dynamicLights]; const tileSize = this.tileSize(); const tileSize = this.tileSize(); const blindLight = this.#blindVisionLight(); if (blindLight) { activeLights.push(blindLight); } for (const entity of this.entities.values()) for (const entity of this.entities.values()) { { const range = entity.lightRadiusTiles ?? 0; const range = entity.lightRadiusTiles ?? 0;@@ -1804,12 +1955,16 @@ export class WorldView for (const objects of this.tiles.values()) for (const objects of this.tiles.values()) { { if (objects._inViewport === false) { continue; } const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion); const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion); objects.shadeAlpha = ambientDark * (1 - intensity); objects.shadeAlpha = ambientDark * (1 - intensity); } } for (const baked of this.bakedChunks.values()) for (const baked of this.bakedChunks.values()) { { if (baked._inViewport === false) { continue; } this.#writeChunkLightmap(baked, activeLights, lightOcclusion); this.#writeChunkLightmap(baked, activeLights, lightOcclusion); if (baked.groundObject?.renderer?.shaderUniforms) if (baked.groundObject?.renderer?.shaderUniforms) { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }@@ -1823,6 +1978,8 @@ export class WorldView const timeSec = now / 1000; const timeSec = now / 1000; for (const objects of this.tiles.values()) for (const objects of this.tiles.values()) { { if (objects._inViewport === false) { continue; } if (objects.block) if (objects.block) { this.#syncLitSprite(objects.block, objects.shadeAlpha); } { this.#syncLitSprite(objects.block, objects.shadeAlpha); } if (objects.ground && isWaterGround(objects.groundTypeId)) if (objects.ground && isWaterGround(objects.groundTypeId))@@ -1995,18 +2152,37 @@ export class WorldView const pixels = baked.lightmapPixels; const pixels = baked.lightmapPixels; this.#fillChunkLightGrids(baked, activeLights, lightOcclusion); this.#fillChunkLightGrids(baked, activeLights, lightOcclusion); const simple = this.lightingMode === "simple"; for (let localY = 0; localY < CHUNK_SIZE; localY++) for (let localY = 0; localY < CHUNK_SIZE; localY++) { { for (let localX = 0; localX < CHUNK_SIZE; localX++) for (let localX = 0; localX < CHUNK_SIZE; localX++) { { const baseX = localX * SPRITE_SIZE_PX; const baseY = localY * SPRITE_SIZE_PX; if (simple) { const gridW = CHUNK_SIZE + 2; const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0; const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); for (let py = 0; py < SPRITE_SIZE_PX; py++) { for (let px = 0; px < SPRITE_SIZE_PX; px++) { const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; pixels[offset] = value; pixels[offset + 1] = value; pixels[offset + 2] = value; pixels[offset + 3] = 255; } } continue; } const corners = this.#tileLitCorners(baked, localX, localY); const corners = this.#tileLitCorners(baked, localX, localY); const nw = corners.nw; const nw = corners.nw; const ne = corners.ne; const ne = corners.ne; const sw = corners.sw; const sw = corners.sw; const se = corners.se; const se = corners.se; const baseX = localX * SPRITE_SIZE_PX; const baseY = localY * SPRITE_SIZE_PX; for (let py = 0; py < SPRITE_SIZE_PX; py++) for (let py = 0; py < SPRITE_SIZE_PX; py++) { { const v = (py + 0.5) / SPRITE_SIZE_PX; const v = (py + 0.5) / SPRITE_SIZE_PX;@@ -2141,6 +2317,11 @@ export class WorldView #syncBloomLayer () #syncBloomLayer () { { if (!this.bloomEnabled) { this.scene.setLayers([{ name: "default" }]); return; } const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; this.scene.setLayers([ this.scene.setLayers([ { name: "default" }, { name: "default" },@@ -341,6 +341,41 @@ label { display: block; margin: 0.4rem 0; }
color: #6d6875;
}
.starter-equipment-panel h3 {
margin: 0.85rem 0 0.4rem;
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.03em;
color: #9aa3b2;
}
.starter-equip-list,
.starter-inv-list {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.starter-equip-row {
display: grid;
grid-template-columns: 5.5rem 1fr;
gap: 0.5rem;
align-items: center;
}
.starter-equip-row.dirty select,
.starter-inv-row.dirty select,
.starter-inv-row.dirty input {
border-color: #c4a35a;
}
.starter-inv-row {
display: grid;
grid-template-columns: 1fr 4.5rem auto;
gap: 0.4rem;
align-items: center;
}
#settings-log-wrap {
width: min(340px, 32vw);
flex-shrink: 0;
@@ -341,6 +341,41 @@ label { display: block; margin: 0.4rem 0; } color: #6d6875; color: #6d6875;}}.starter-equipment-panel h3 { margin: 0.85rem 0 0.4rem; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.03em; color: #9aa3b2;}.starter-equip-list,.starter-inv-list { display: flex; flex-direction: column; gap: 0.4rem;}.starter-equip-row { display: grid; grid-template-columns: 5.5rem 1fr; gap: 0.5rem; align-items: center;}.starter-equip-row.dirty select,.starter-inv-row.dirty select,.starter-inv-row.dirty input { border-color: #c4a35a;}.starter-inv-row { display: grid; grid-template-columns: 1fr 4.5rem auto; gap: 0.4rem; align-items: center;}#settings-log-wrap {#settings-log-wrap { width: min(340px, 32vw); width: min(340px, 32vw); flex-shrink: 0; flex-shrink: 0;@@ -37,6 +37,94 @@ html, body {
display: none !important;
}
#settings-toggle {
position: fixed;
z-index: 4;
top: 0.45rem;
right: 0.75rem;
width: 2.25rem;
height: 2.25rem;
padding: 0;
border: 1px solid #3a4250;
border-radius: 0.35rem;
background: rgba(18, 22, 28, 0.92);
color: #e8e4d9;
font-size: 1.15rem;
line-height: 1;
cursor: pointer;
}
#settings-toggle[hidden] {
display: none !important;
}
#settings-panel {
position: fixed;
z-index: 5;
top: 3.1rem;
right: 0.75rem;
width: min(18rem, calc(100vw - 1.5rem));
padding: 0.75rem 0.9rem 1rem;
border: 1px solid #3a4250;
border-radius: 0.4rem;
background: rgba(14, 17, 22, 0.96);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
}
#settings-panel[hidden] {
display: none !important;
}
#settings-panel header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0.65rem;
}
#settings-panel h2 {
margin: 0;
font-size: 1.05rem;
font-weight: 600;
}
#settings-panel h3 {
margin: 0 0 0.35rem;
font-size: 0.8rem;
font-weight: 600;
letter-spacing: 0.02em;
text-transform: uppercase;
color: #9aa3b2;
}
.settings-group + .settings-group {
margin-top: 0.85rem;
}
.settings-options {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.settings-options button {
flex: 1 1 auto;
min-width: 4.5rem;
padding: 0.35rem 0.55rem;
border: 1px solid #3a4250;
border-radius: 0.3rem;
background: #1a2029;
color: #c8cdd6;
cursor: pointer;
}
.settings-options button.active {
border-color: #7a91b8;
background: #2a3648;
color: #f0f2f6;
}
#toast-stack {
position: fixed;
top: 3.4rem;
@@ -101,6 +189,62 @@ html, body {
padding: 1.25rem;
}
#character-list {
margin: 0.75rem 0 1rem;
max-height: min(40vh, 20rem);
overflow: auto;
}
#create-character-open {
width: 100%;
margin-top: 0.25rem;
}
#create-panel {
position: fixed;
z-index: 6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(420px, 92vw);
max-height: min(90vh, 40rem);
overflow: auto;
padding: 1rem 1.1rem 1.15rem;
border: 1px solid #3a4250;
border-radius: 0.4rem;
background: rgba(18, 22, 28, 0.98);
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);
}
#create-panel[hidden] {
display: none !important;
}
#create-panel header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0.5rem;
}
#create-panel h2 {
margin: 0;
font-size: 1.1rem;
}
#create-panel label {
display: flex;
gap: 0.5rem;
align-items: center;
margin: 0.5rem 0;
}
#create-panel #create-form > button[type="submit"] {
width: 100%;
margin-top: 0.75rem;
}
label, .character-row {
display: flex;
gap: 0.5rem;
@@ -124,6 +268,65 @@ button {
.hint { color: #9aa3b2; font-size: 0.9rem; }
a { color: #d4c48a; }
.hair-controls {
display: grid;
grid-template-columns: 72px 1fr;
gap: 0.45rem 0.75rem;
align-items: center;
margin: 0.75rem 0;
}
.hair-controls canvas {
grid-row: 1 / span 5;
width: 64px;
height: 96px;
image-rendering: pixelated;
background: #0c0e12;
border: 1px solid #2c3340;
}
.hair-controls label {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 0.2rem;
margin: 0;
font-size: 0.8rem;
}
.hair-controls input[type="range"] {
width: 100%;
padding: 0;
}
.hair-swatch {
display: inline-block;
width: 1.25rem;
height: 1.25rem;
border: 1px solid #3a4250;
border-radius: 2px;
}
#barber-panel {
position: fixed;
z-index: 6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(360px, 92vw);
background: #1a1e26;
border: 1px solid #2c3340;
padding: 0.75rem 1rem 1rem;
}
#barber-panel header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.5rem;
}
#nametag {
position: fixed;
z-index: 4;
@@ -933,11 +1136,113 @@ a { color: #d4c48a; }
background: rgba(12, 14, 18, 0.92);
}
#stamina-bar {
#vitals {
position: fixed;
z-index: 4;
right: 1rem;
bottom: 1.25rem;
display: flex;
flex-direction: row;
gap: 0.45rem;
align-items: flex-end;
}
#vitals[hidden] {
display: none !important;
}
#status-effects {
display: flex;
flex-direction: column-reverse;
gap: 0.3rem;
align-items: center;
max-height: 120px;
overflow: visible;
}
#status-effects[hidden] {
display: none !important;
}
.status-effect-icon {
width: 28px;
height: 28px;
padding: 2px;
box-sizing: border-box;
border: 1px solid #3a4250;
background: rgba(12, 14, 18, 0.88);
cursor: default;
display: grid;
place-items: center;
image-rendering: pixelated;
}
.status-effect-icon img {
width: 16px;
height: 16px;
image-rendering: pixelated;
pointer-events: none;
}
.status-effect-buff {
border-color: #4a7a58;
}
.status-effect-debuff {
border-color: #7a4a4a;
}
.status-effect-icon-fallback {
font-size: 0.75rem;
font-weight: 700;
color: #d0d6e0;
}
#status-effect-tooltip {
position: fixed;
z-index: 20;
min-width: 10rem;
max-width: 16rem;
padding: 0.45rem 0.55rem;
background: rgba(12, 14, 18, 0.96);
border: 1px solid #3a4250;
color: #d0d6e0;
font-size: 0.78rem;
line-height: 1.35;
pointer-events: none;
}
#status-effect-tooltip[hidden] {
display: none !important;
}
#status-effect-tooltip strong {
display: block;
margin-bottom: 0.2rem;
color: #f0f2f6;
font-size: 0.82rem;
}
#status-effect-tooltip p {
margin: 0.15rem 0 0;
}
#status-effect-tooltip .status-effect-tooltip-time {
color: #9aa3b2;
font-size: 0.72rem;
}
#status-effect-tooltip[data-polarity="buff"] {
border-color: #4a7a58;
}
#status-effect-tooltip[data-polarity="debuff"] {
border-color: #7a4a4a;
}
#stamina-bar,
#health-bar {
position: relative;
width: 14px;
height: 120px;
padding: 3px;
@@ -950,33 +1255,52 @@ a { color: #d4c48a; }
align-items: stretch;
}
#stamina-bar[hidden] {
#stamina-bar[hidden],
#health-bar[hidden] {
display: none !important;
}
#stamina-bar-fill {
#stamina-bar-fill,
#health-bar-fill {
flex: 1;
width: 100%;
transform-origin: bottom center;
transform: scaleY(1);
background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
border-radius: 1px;
transition: transform 80ms linear;
}
#stamina-bar-fill {
background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);
}
#health-bar-fill {
background: linear-gradient(180deg, #e06060 0%, #a02828 100%);
}
#stamina-bar.empty #stamina-bar-fill {
background: #4a3030;
}
#health-bar.empty #health-bar-fill {
background: #3a2020;
}
#stamina-bar.low #stamina-bar-fill {
background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);
}
.stamina-bar-label {
#health-bar.low #health-bar-fill {
background: linear-gradient(180deg, #f0a040 0%, #c05020 100%);
}
.stamina-bar-label,
.health-bar-label {
position: absolute;
right: calc(100% + 0.4rem);
bottom: 0;
font-size: 0.75rem;
left: 50%;
top: calc(100% + 0.25rem);
transform: translateX(-50%);
font-size: 0.65rem;
color: #9aa3b2;
white-space: nowrap;
pointer-events: none;
@@ -1364,3 +1688,91 @@ a { color: #d4c48a; }
.item-bubble[hidden] {
display: none !important;
}
#bounty-panel {
position: fixed;
z-index: 6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(420px, 92vw);
max-height: min(70vh, 520px);
overflow: auto;
background: #1a1e26;
border: 1px solid #2c3340;
padding: 0.75rem 1rem 1rem;
}
#bounty-panel header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.5rem;
}
.bounty-tabs {
display: flex;
gap: 0.25rem;
margin: 0.5rem 0 0.75rem;
}
.bounty-tab {
flex: 1;
font-size: 0.85rem;
padding: 0.35rem 0.4rem;
background: #12151b;
border: 1px solid #2c3340;
color: inherit;
}
.bounty-tab.active {
outline: 1px solid #6a8caf;
border-color: #6a8caf;
}
.bounty-search-row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: end;
margin-bottom: 0.75rem;
}
.bounty-search-row label {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.8rem;
}
.bounty-search-row input,
.bounty-amount-label input {
background: #12151b;
border: 1px solid #2c3340;
color: inherit;
padding: 0.35rem 0.4rem;
min-width: 6rem;
}
.bounty-target {
display: flex;
gap: 0.75rem;
align-items: center;
margin-bottom: 0.75rem;
min-height: 48px;
}
.bounty-amount-label {
display: flex;
flex-direction: column;
gap: 0.25rem;
margin-bottom: 0.75rem;
font-size: 0.85rem;
}
.bounty-my-amount {
font-size: 1.25rem;
font-weight: 700;
margin: 0.5rem 0 0;
}
@@ -37,6 +37,94 @@ html, body { display: none !important; display: none !important;}}#settings-toggle { position: fixed; z-index: 4; top: 0.45rem; right: 0.75rem; width: 2.25rem; height: 2.25rem; padding: 0; border: 1px solid #3a4250; border-radius: 0.35rem; background: rgba(18, 22, 28, 0.92); color: #e8e4d9; font-size: 1.15rem; line-height: 1; cursor: pointer;}#settings-toggle[hidden] { display: none !important;}#settings-panel { position: fixed; z-index: 5; top: 3.1rem; right: 0.75rem; width: min(18rem, calc(100vw - 1.5rem)); padding: 0.75rem 0.9rem 1rem; border: 1px solid #3a4250; border-radius: 0.4rem; background: rgba(14, 17, 22, 0.96); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);}#settings-panel[hidden] { display: none !important;}#settings-panel header { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; margin-bottom: 0.65rem;}#settings-panel h2 { margin: 0; font-size: 1.05rem; font-weight: 600;}#settings-panel h3 { margin: 0 0 0.35rem; font-size: 0.8rem; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase; color: #9aa3b2;}.settings-group + .settings-group { margin-top: 0.85rem;}.settings-options { display: flex; flex-wrap: wrap; gap: 0.35rem;}.settings-options button { flex: 1 1 auto; min-width: 4.5rem; padding: 0.35rem 0.55rem; border: 1px solid #3a4250; border-radius: 0.3rem; background: #1a2029; color: #c8cdd6; cursor: pointer;}.settings-options button.active { border-color: #7a91b8; background: #2a3648; color: #f0f2f6;}#toast-stack {#toast-stack { position: fixed; position: fixed; top: 3.4rem; top: 3.4rem;@@ -101,6 +189,62 @@ html, body { padding: 1.25rem; padding: 1.25rem;}}#character-list { margin: 0.75rem 0 1rem; max-height: min(40vh, 20rem); overflow: auto;}#create-character-open { width: 100%; margin-top: 0.25rem;}#create-panel { position: fixed; z-index: 6; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(420px, 92vw); max-height: min(90vh, 40rem); overflow: auto; padding: 1rem 1.1rem 1.15rem; border: 1px solid #3a4250; border-radius: 0.4rem; background: rgba(18, 22, 28, 0.98); box-shadow: 0 12px 36px rgba(0, 0, 0, 0.5);}#create-panel[hidden] { display: none !important;}#create-panel header { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; margin-bottom: 0.5rem;}#create-panel h2 { margin: 0; font-size: 1.1rem;}#create-panel label { display: flex; gap: 0.5rem; align-items: center; margin: 0.5rem 0;}#create-panel #create-form > button[type="submit"] { width: 100%; margin-top: 0.75rem;}label, .character-row {label, .character-row { display: flex; display: flex; gap: 0.5rem; gap: 0.5rem;@@ -124,6 +268,65 @@ button {.hint { color: #9aa3b2; font-size: 0.9rem; }.hint { color: #9aa3b2; font-size: 0.9rem; }a { color: #d4c48a; }a { color: #d4c48a; }.hair-controls { display: grid; grid-template-columns: 72px 1fr; gap: 0.45rem 0.75rem; align-items: center; margin: 0.75rem 0;}.hair-controls canvas { grid-row: 1 / span 5; width: 64px; height: 96px; image-rendering: pixelated; background: #0c0e12; border: 1px solid #2c3340;}.hair-controls label { display: flex; flex-direction: column; align-items: stretch; gap: 0.2rem; margin: 0; font-size: 0.8rem;}.hair-controls input[type="range"] { width: 100%; padding: 0;}.hair-swatch { display: inline-block; width: 1.25rem; height: 1.25rem; border: 1px solid #3a4250; border-radius: 2px;}#barber-panel { position: fixed; z-index: 6; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(360px, 92vw); background: #1a1e26; border: 1px solid #2c3340; padding: 0.75rem 1rem 1rem;}#barber-panel header { display: flex; justify-content: space-between; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;}#nametag {#nametag { position: fixed; position: fixed; z-index: 4; z-index: 4;@@ -933,11 +1136,113 @@ a { color: #d4c48a; } background: rgba(12, 14, 18, 0.92); background: rgba(12, 14, 18, 0.92);}}#stamina-bar {#vitals { position: fixed; position: fixed; z-index: 4; z-index: 4; right: 1rem; right: 1rem; bottom: 1.25rem; bottom: 1.25rem; display: flex; flex-direction: row; gap: 0.45rem; align-items: flex-end;}#vitals[hidden] { display: none !important;}#status-effects { display: flex; flex-direction: column-reverse; gap: 0.3rem; align-items: center; max-height: 120px; overflow: visible;}#status-effects[hidden] { display: none !important;}.status-effect-icon { width: 28px; height: 28px; padding: 2px; box-sizing: border-box; border: 1px solid #3a4250; background: rgba(12, 14, 18, 0.88); cursor: default; display: grid; place-items: center; image-rendering: pixelated;}.status-effect-icon img { width: 16px; height: 16px; image-rendering: pixelated; pointer-events: none;}.status-effect-buff { border-color: #4a7a58;}.status-effect-debuff { border-color: #7a4a4a;}.status-effect-icon-fallback { font-size: 0.75rem; font-weight: 700; color: #d0d6e0;}#status-effect-tooltip { position: fixed; z-index: 20; min-width: 10rem; max-width: 16rem; padding: 0.45rem 0.55rem; background: rgba(12, 14, 18, 0.96); border: 1px solid #3a4250; color: #d0d6e0; font-size: 0.78rem; line-height: 1.35; pointer-events: none;}#status-effect-tooltip[hidden] { display: none !important;}#status-effect-tooltip strong { display: block; margin-bottom: 0.2rem; color: #f0f2f6; font-size: 0.82rem;}#status-effect-tooltip p { margin: 0.15rem 0 0;}#status-effect-tooltip .status-effect-tooltip-time { color: #9aa3b2; font-size: 0.72rem;}#status-effect-tooltip[data-polarity="buff"] { border-color: #4a7a58;}#status-effect-tooltip[data-polarity="debuff"] { border-color: #7a4a4a;}#stamina-bar,#health-bar { position: relative; width: 14px; width: 14px; height: 120px; height: 120px; padding: 3px; padding: 3px;@@ -950,33 +1255,52 @@ a { color: #d4c48a; } align-items: stretch; align-items: stretch;}}#stamina-bar[hidden] {#stamina-bar[hidden],#health-bar[hidden] { display: none !important; display: none !important;}}#stamina-bar-fill {#stamina-bar-fill,#health-bar-fill { flex: 1; flex: 1; width: 100%; width: 100%; transform-origin: bottom center; transform-origin: bottom center; transform: scaleY(1); transform: scaleY(1); background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%); border-radius: 1px; border-radius: 1px; transition: transform 80ms linear; transition: transform 80ms linear;}}#stamina-bar-fill { background: linear-gradient(180deg, #6ecf8a 0%, #3a8a58 100%);}#health-bar-fill { background: linear-gradient(180deg, #e06060 0%, #a02828 100%);}#stamina-bar.empty #stamina-bar-fill {#stamina-bar.empty #stamina-bar-fill { background: #4a3030; background: #4a3030;}}#health-bar.empty #health-bar-fill { background: #3a2020;}#stamina-bar.low #stamina-bar-fill {#stamina-bar.low #stamina-bar-fill { background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%); background: linear-gradient(180deg, #d4c48a 0%, #a08040 100%);}}.stamina-bar-label {#health-bar.low #health-bar-fill { background: linear-gradient(180deg, #f0a040 0%, #c05020 100%);}.stamina-bar-label,.health-bar-label { position: absolute; position: absolute; right: calc(100% + 0.4rem); left: 50%; bottom: 0; top: calc(100% + 0.25rem); font-size: 0.75rem; transform: translateX(-50%); font-size: 0.65rem; color: #9aa3b2; color: #9aa3b2; white-space: nowrap; white-space: nowrap; pointer-events: none; pointer-events: none;@@ -1364,3 +1688,91 @@ a { color: #d4c48a; }.item-bubble[hidden] {.item-bubble[hidden] { display: none !important; display: none !important;}}#bounty-panel { position: fixed; z-index: 6; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(420px, 92vw); max-height: min(70vh, 520px); overflow: auto; background: #1a1e26; border: 1px solid #2c3340; padding: 0.75rem 1rem 1rem;}#bounty-panel header { display: flex; justify-content: space-between; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;}.bounty-tabs { display: flex; gap: 0.25rem; margin: 0.5rem 0 0.75rem;}.bounty-tab { flex: 1; font-size: 0.85rem; padding: 0.35rem 0.4rem; background: #12151b; border: 1px solid #2c3340; color: inherit;}.bounty-tab.active { outline: 1px solid #6a8caf; border-color: #6a8caf;}.bounty-search-row { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: end; margin-bottom: 0.75rem;}.bounty-search-row label { display: flex; flex-direction: column; gap: 0.2rem; font-size: 0.8rem;}.bounty-search-row input,.bounty-amount-label input { background: #12151b; border: 1px solid #2c3340; color: inherit; padding: 0.35rem 0.4rem; min-width: 6rem;}.bounty-target { display: flex; gap: 0.75rem; align-items: center; margin-bottom: 0.75rem; min-height: 48px;}.bounty-amount-label { display: flex; flex-direction: column; gap: 0.25rem; margin-bottom: 0.75rem; font-size: 0.85rem;}.bounty-my-amount { font-size: 1.25rem; font-weight: 700; margin: 0.5rem 0 0;}@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## World settings
**Status:** full
**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.
**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.
**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`
## Baked lighting
@@ -94,8 +94,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Characters
**Status:** full
**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.
**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`
**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.
**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
## Character deletion and inheritance
@@ -106,8 +106,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## 3×3 chunk replication
**Status:** full
**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.
**Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)
**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.
**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
## Click-to-move and A\* pathfinding
@@ -130,13 +130,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Play viewport and camera
**Status:** full
**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.
**Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
**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.
**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
## Client graphics settings
**Status:** full
**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.
**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
## Night shading
**Status:** full
**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.
**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.
**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
## FrameworkV3 client bootstrap
@@ -208,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Combat, skills, groups, pigeons
**Status:** partial
**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.
**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.
**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)
## Player death and respawn
@@ -235,7 +241,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Gathering, crafting, and production skills
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
**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.
**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`
@@ -260,14 +266,45 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Stamina and running
**Status:** full
**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.
**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.
**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`
## Alchemy / cauldron
**Status:** partial (potion scaffolding + flower→dye + dye mixing live)
**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.
**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`
**Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
**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).
**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`
### Folklore herb associations (design only — not in code)
Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
| Tier | Herb | Associations |
| --- | --- | --- |
| 1 | Mint | Refreshment, stamina, antidotes |
| 1 | Garlic | Undead protection, disease resistance |
| 2 | Thyme | Courage, vitality, resistance |
| 2 | Sage | Healing, wisdom, longevity |
| 2 | Rosemary | Memory, protection, clarity |
| 3 | Lavender | Sleep, calm, dreams |
| 3 | Chamomile | Restoration, sleep, soothing |
| 3 | Nettle | Vigour, resilience, protection |
| 4 | Yarrow | Wound healing, battle medicine |
| 4 | Juniper | Purification, disease resistance |
| 4 | Elder | Spirits, protection, healing |
| 4 | Rue | Curse resistance, purification |
| 5 | Valerian | Sleep, sedation, tranquillity |
| 5 | Mugwort | Dreams, visions, divination |
| 5 | Wormwood | Poison resistance, spirits, bitterness |
| 5 | St. John's wort | Holy protection, dispel darkness |
| 6 | Hawthorn | Fey, barriers, enchantment |
| 6 | Foxglove | Fairy magic, heart magic, poison |
| 6 | Mistletoe | Life, fertility, druidic magic |
| 6 | Datura | Visions, insanity, spirit walking |
| 7 | Belladonna | Poison, hallucination, witchcraft |
| 7 | Henbane | Trance, madness, sleep, poison |
| 7 | Mandrake | Powerful potions, curses, life magic |
| 7 | Aconite | Werewolves, lethal poison, curses |
## Inventory, items, equipment, ground drops
@@ -287,20 +324,25 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
**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.
**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
## Hair & barber
**Status:** full
**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).
**Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
## Bounty offices
**Status:** not implemented
**Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:
**Status:** full
**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
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).
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).
2. **My bounty** — Shows how much coin is currently on **your** head.
**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**.
**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**.
**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
**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.
**Code:** —
**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`
## Banking, cheques, shops, player-driven marketplace
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## World settings## World settings**Status:** full **Status:** full **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. **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. **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`**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`## Baked lighting## Baked lighting@@ -94,8 +94,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Characters## Characters**Status:** full **Status:** full **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. **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. **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`## Character deletion and inheritance## Character deletion and inheritance@@ -106,8 +106,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## 3×3 chunk replication## 3×3 chunk replication**Status:** full **Status:** full **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. **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. **Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`## Click-to-move and A\* pathfinding## Click-to-move and A\* pathfinding@@ -130,13 +130,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Play viewport and camera## Play viewport and camera**Status:** full **Status:** full **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. **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. **Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`## Client graphics settings**Status:** full **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. **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`## Night shading## Night shading**Status:** full **Status:** full **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. **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. **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`## FrameworkV3 client bootstrap## FrameworkV3 client bootstrap@@ -208,7 +214,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Combat, skills, groups, pigeons## Combat, skills, groups, pigeons**Status:** partial **Status:** partial **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. **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. **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)**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)## Player death and respawn## Player death and respawn@@ -235,7 +241,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Gathering, crafting, and production skills## Gathering, crafting, and production skills**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live) **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live) **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. **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. **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`**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`@@ -260,14 +266,45 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Stamina and running## Stamina and running**Status:** full **Status:** full **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. **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. **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`**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`## Alchemy / cauldron## Alchemy / cauldron**Status:** partial (potion scaffolding + flower→dye + dye mixing live) **Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD) **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.**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). **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`**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`### Folklore herb associations (design only — not in code)Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.| Tier | Herb | Associations || --- | --- | --- || 1 | Mint | Refreshment, stamina, antidotes || 1 | Garlic | Undead protection, disease resistance || 2 | Thyme | Courage, vitality, resistance || 2 | Sage | Healing, wisdom, longevity || 2 | Rosemary | Memory, protection, clarity || 3 | Lavender | Sleep, calm, dreams || 3 | Chamomile | Restoration, sleep, soothing || 3 | Nettle | Vigour, resilience, protection || 4 | Yarrow | Wound healing, battle medicine || 4 | Juniper | Purification, disease resistance || 4 | Elder | Spirits, protection, healing || 4 | Rue | Curse resistance, purification || 5 | Valerian | Sleep, sedation, tranquillity || 5 | Mugwort | Dreams, visions, divination || 5 | Wormwood | Poison resistance, spirits, bitterness || 5 | St. John's wort | Holy protection, dispel darkness || 6 | Hawthorn | Fey, barriers, enchantment || 6 | Foxglove | Fairy magic, heart magic, poison || 6 | Mistletoe | Life, fertility, druidic magic || 6 | Datura | Visions, insanity, spirit walking || 7 | Belladonna | Poison, hallucination, witchcraft || 7 | Henbane | Trance, madness, sleep, poison || 7 | Mandrake | Powerful potions, curses, life magic || 7 | Aconite | Werewolves, lethal poison, curses |## Inventory, items, equipment, ground drops## Inventory, items, equipment, ground drops@@ -287,20 +324,25 @@ Each entry is a short note on behaviour and where the code lives. Update this fi**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. **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. **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`## Hair & barber**Status:** full **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). **Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`## Bounty offices## Bounty offices**Status:** not implemented **Status:** full **Spec:** Placeable **Bounty Office** blocks (sprite/form TBD). Interacting opens a modal with two tabs:**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs: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).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).2. **My bounty** — Shows how much coin is currently on **your** head.2. **My bounty** — Shows how much coin is currently on **your** head.**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**.**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**.**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.**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. **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`**Code:** —## Banking, cheques, shops, player-driven marketplace## Banking, cheques, shops, player-driven marketplace@@ -1,8 +1,9 @@
import { readdirSync } from "node:fs";
import { extname, join } from "node:path";
import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";
import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
import { HERB_ORDER } from "../../../shared/definitions/herbs.js";
import {
ORE_BEARING_MATERIALS,
oreBoulderState,
@@ -32,9 +33,15 @@ const CHARACTER_DEFINITIONS = Object.freeze({
export function buildSpriteCatalog (assetRoot)
{
const blockDefs = Object.fromEntries(
Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
);
const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
const herbs = scanHerbAssets(join(assetRoot, "herbs"));
Object.assign(blocks.types, herbs.blockTypes);
Object.assign(items.types, herbs.itemTypes);
const mobs = scanMobLayers(assetRoot);
const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
const fx = scanFx(join(assetRoot, "fx"));
@@ -49,6 +56,7 @@ export function buildSpriteCatalog (assetRoot)
...grounds.images,
...blocks.images,
...items.images,
...herbs.images,
...mobs.images,
...characters.images,
...fx.images
@@ -56,11 +64,80 @@ export function buildSpriteCatalog (assetRoot)
};
}
/**
* Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
*/
function scanHerbAssets (herbRoot)
{
const stems = new Set(listPngStems(herbRoot));
const missing = HERB_ORDER.filter((id) => !stems.has(id));
if (missing.length)
{ throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
const images = [];
for (const herbId of HERB_ORDER)
{
const url = `/assets/herbs/${herbId}.png`;
images.push({
name: spriteImageName("block", "herb", herbId),
url,
subImgTotal: 1,
perRow: 1,
loop: false,
animationSpeed: 0
});
images.push({
name: spriteImageName("item", "herbs", herbId),
url,
subImgTotal: 1,
perRow: 1,
loop: false,
animationSpeed: 0
});
}
const blockTypes = {
herb: {
key: "herb",
typeId: BlockType.herbPlant,
states: [...HERB_ORDER],
defaultState: HERB_ORDER[0],
blooms: {},
equips: {},
equipBlooms: {},
frames: 1,
framesPerRow: 1,
animationSpeed: 0,
outdoor: true,
seasonal: false
}
};
const itemTypes = {
herbs: {
key: "herbs",
typeId: "herbs",
states: [...HERB_ORDER],
defaultState: HERB_ORDER[0],
blooms: {},
equips: {},
equipBlooms: {},
frames: 1,
framesPerRow: 1,
animationSpeed: 0,
outdoor: false,
seasonal: false
}
};
return { images, blockTypes, itemTypes };
}
function itemScanDefs ()
{
const defs = {};
for (const def of Object.values(ITEM_DEFINITIONS))
{
if (def?.herb)
{ continue; }
const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
if (!folderKey || defs[folderKey])
{ continue; }
@@ -1,8 +1,9 @@import { readdirSync } from "node:fs";import { readdirSync } from "node:fs";import { extname, join } from "node:path";import { extname, join } from "node:path";import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";import { HERB_ORDER } from "../../../shared/definitions/herbs.js";import {import { ORE_BEARING_MATERIALS, ORE_BEARING_MATERIALS, oreBoulderState, oreBoulderState,@@ -32,9 +33,15 @@ const CHARACTER_DEFINITIONS = Object.freeze({export function buildSpriteCatalog (assetRoot)export function buildSpriteCatalog (assetRoot){{ const blockDefs = Object.fromEntries( Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb") ); const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds"); const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds"); const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks"); const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks"); const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items"); const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items"); const herbs = scanHerbAssets(join(assetRoot, "herbs")); Object.assign(blocks.types, herbs.blockTypes); Object.assign(items.types, herbs.itemTypes); const mobs = scanMobLayers(assetRoot); const mobs = scanMobLayers(assetRoot); const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters"); const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters"); const fx = scanFx(join(assetRoot, "fx")); const fx = scanFx(join(assetRoot, "fx"));@@ -49,6 +56,7 @@ export function buildSpriteCatalog (assetRoot) ...grounds.images, ...grounds.images, ...blocks.images, ...blocks.images, ...items.images, ...items.images, ...herbs.images, ...mobs.images, ...mobs.images, ...characters.images, ...characters.images, ...fx.images ...fx.images@@ -56,11 +64,80 @@ export function buildSpriteCatalog (assetRoot) }; };}}/** * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons. */function scanHerbAssets (herbRoot){ const stems = new Set(listPngStems(herbRoot)); const missing = HERB_ORDER.filter((id) => !stems.has(id)); if (missing.length) { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); } const images = []; for (const herbId of HERB_ORDER) { const url = `/assets/herbs/${herbId}.png`; images.push({ name: spriteImageName("block", "herb", herbId), url, subImgTotal: 1, perRow: 1, loop: false, animationSpeed: 0 }); images.push({ name: spriteImageName("item", "herbs", herbId), url, subImgTotal: 1, perRow: 1, loop: false, animationSpeed: 0 }); } const blockTypes = { herb: { key: "herb", typeId: BlockType.herbPlant, states: [...HERB_ORDER], defaultState: HERB_ORDER[0], blooms: {}, equips: {}, equipBlooms: {}, frames: 1, framesPerRow: 1, animationSpeed: 0, outdoor: true, seasonal: false } }; const itemTypes = { herbs: { key: "herbs", typeId: "herbs", states: [...HERB_ORDER], defaultState: HERB_ORDER[0], blooms: {}, equips: {}, equipBlooms: {}, frames: 1, framesPerRow: 1, animationSpeed: 0, outdoor: false, seasonal: false } }; return { images, blockTypes, itemTypes };}function itemScanDefs ()function itemScanDefs (){{ const defs = {}; const defs = {}; for (const def of Object.values(ITEM_DEFINITIONS)) for (const def of Object.values(ITEM_DEFINITIONS)) { { if (def?.herb) { continue; } const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key; const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key; if (!folderKey || defs[folderKey]) if (!folderKey || defs[folderKey]) { continue; } { continue; }@@ -0,0 +1,139 @@
import {
DEFAULT_HAIR_STYLE,
hairFromCharacterRow,
isValidHairStyle,
listHairStyles,
normalizeHairSliders,
normalizeHairStyle
} from "../../../shared/appearance/hair.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
function userError (message)
{
const error = new Error(message);
error.userFacing = true;
return error;
}
export class BarberService
{
constructor (stateDb, simulation)
{
this.stateDb = stateDb;
this.simulation = simulation;
}
handleCommand (sessionId, command)
{
switch (command.type)
{
case "open-barber":
return this.open(sessionId, command.characterId);
case "set-hair":
return this.setHair(sessionId, command.characterId, command.hair);
case "close-barber":
return { events: [{ type: "barber-closed", sessionId, characterId: command.characterId }] };
default:
return null;
}
}
open (sessionId, characterId)
{
this.#requireNearBarber(characterId);
const row = this.stateDb.getCharacter(characterId);
if (!row)
{ throw userError("Character not found."); }
const hair = hairFromCharacterRow(row);
const sex = row.sex === "female" ? "female" : "male";
return {
events: [{
type: "barber-snapshot",
sessionId,
characterId,
sex,
styles: listHairStyles(sex),
hair: {
style: hair?.style ?? DEFAULT_HAIR_STYLE,
hue: hair?.hue ?? 30,
saturation: hair?.saturation ?? 0.55,
darkness: hair?.darkness ?? 0.45
}
}]
};
}
setHair (sessionId, characterId, hairInput)
{
this.#requireNearBarber(characterId);
const row = this.stateDb.getCharacter(characterId);
if (!row)
{ throw userError("Character not found."); }
const sex = row.sex === "female" ? "female" : "male";
if (!isValidHairStyle(sex, hairInput?.style))
{ throw userError("Unknown hair style."); }
const style = normalizeHairStyle(sex, hairInput?.style ?? DEFAULT_HAIR_STYLE);
const sliders = normalizeHairSliders(hairInput);
const hair = {
style,
hue: sliders.hue,
saturation: sliders.saturation,
darkness: sliders.darkness
};
this.simulation.setCharacterHair(characterId, hair);
return {
events: [{
type: "barber-snapshot",
sessionId,
characterId,
sex,
styles: listHairStyles(sex),
hair,
message: "Hair updated."
}]
};
}
#requireNearBarber (characterId)
{
const entityId = this.simulation.characterEntities.get(characterId);
const position = entityId ? this.simulation.positionOf(entityId) : null;
if (!position)
{ throw userError("Enter the world before visiting the barber."); }
if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY))
{ throw userError("Stand next to a Barber."); }
return position;
}
}
function isAdjacentToBarber (simulation, tileX, tileY)
{
for (let dy = -1; dy <= 1; dy++)
{
for (let dx = -1; dx <= 1; dx++)
{
if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber)
{ return true; }
}
}
return false;
}
function blockTypeAt (simulation, tileX, tileY)
{
const chunkX = tileToChunk(tileX);
const chunkY = tileToChunk(tileY);
for (const worker of simulation.workers ?? [])
{
const data = worker.world?.chunkData?.(chunkX, chunkY);
if (!data?.blocks)
{ continue; }
const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
const typeId = data.blocks[index]?.typeId;
if (typeId != null)
{ return typeId; }
}
return null;
}
@@ -0,0 +1,139 @@import { DEFAULT_HAIR_STYLE, hairFromCharacterRow, isValidHairStyle, listHairStyles, normalizeHairSliders, normalizeHairStyle} from "../../../shared/appearance/hair.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { tileToChunk, tileToLocal } from "../world/coordinates.js";function userError (message){ const error = new Error(message); error.userFacing = true; return error;}export class BarberService{ constructor (stateDb, simulation) { this.stateDb = stateDb; this.simulation = simulation; } handleCommand (sessionId, command) { switch (command.type) { case "open-barber": return this.open(sessionId, command.characterId); case "set-hair": return this.setHair(sessionId, command.characterId, command.hair); case "close-barber": return { events: [{ type: "barber-closed", sessionId, characterId: command.characterId }] }; default: return null; } } open (sessionId, characterId) { this.#requireNearBarber(characterId); const row = this.stateDb.getCharacter(characterId); if (!row) { throw userError("Character not found."); } const hair = hairFromCharacterRow(row); const sex = row.sex === "female" ? "female" : "male"; return { events: [{ type: "barber-snapshot", sessionId, characterId, sex, styles: listHairStyles(sex), hair: { style: hair?.style ?? DEFAULT_HAIR_STYLE, hue: hair?.hue ?? 30, saturation: hair?.saturation ?? 0.55, darkness: hair?.darkness ?? 0.45 } }] }; } setHair (sessionId, characterId, hairInput) { this.#requireNearBarber(characterId); const row = this.stateDb.getCharacter(characterId); if (!row) { throw userError("Character not found."); } const sex = row.sex === "female" ? "female" : "male"; if (!isValidHairStyle(sex, hairInput?.style)) { throw userError("Unknown hair style."); } const style = normalizeHairStyle(sex, hairInput?.style ?? DEFAULT_HAIR_STYLE); const sliders = normalizeHairSliders(hairInput); const hair = { style, hue: sliders.hue, saturation: sliders.saturation, darkness: sliders.darkness }; this.simulation.setCharacterHair(characterId, hair); return { events: [{ type: "barber-snapshot", sessionId, characterId, sex, styles: listHairStyles(sex), hair, message: "Hair updated." }] }; } #requireNearBarber (characterId) { const entityId = this.simulation.characterEntities.get(characterId); const position = entityId ? this.simulation.positionOf(entityId) : null; if (!position) { throw userError("Enter the world before visiting the barber."); } if (!isAdjacentToBarber(this.simulation, position.tileX, position.tileY)) { throw userError("Stand next to a Barber."); } return position; }}function isAdjacentToBarber (simulation, tileX, tileY){ for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (blockTypeAt(simulation, tileX + dx, tileY + dy) === BlockType.barber) { return true; } } } return false;}function blockTypeAt (simulation, tileX, tileY){ const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); for (const worker of simulation.workers ?? []) { const data = worker.world?.chunkData?.(chunkX, chunkY); if (!data?.blocks) { continue; } const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX); const typeId = data.blocks[index]?.typeId; if (typeId != null) { return typeId; } } return null;}@@ -0,0 +1,321 @@
import { randomUUID } from "node:crypto";
import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";
import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";
import { layersFromBag } from "../../../shared/appearance/layers.js";
import {
addCoinsToSlots,
normalizeVault,
takeCoinsFromSlots
} from "../../../shared/items/inventory.js";
function userError (message)
{
const error = new Error(message);
error.userFacing = true;
return error;
}
function chebyshev (ax, ay, bx, by)
{
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
}
/**
* Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter.
*/
export class BountyService
{
constructor (stateDb, simulation, courier)
{
this.stateDb = stateDb;
this.simulation = simulation;
this.courier = courier;
}
handleCommand (sessionId, command)
{
switch (command.type)
{
case "open-bounty":
return this.open(sessionId, command.characterId);
case "raise-bounty":
return this.placeOrRaise(
sessionId,
command.characterId,
command.firstName,
command.lastName,
command.amountCopper
);
case "get-character-bounty":
return this.lookup(
sessionId,
command.characterId,
command.targetCharacterId,
command.firstName,
command.lastName
);
case "close-bounty":
return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] };
default:
return null;
}
}
open (sessionId, characterId)
{
this.#requireNearOffice(characterId);
return {
events: [{
type: "bounty-snapshot",
sessionId,
characterId,
...this.#myBountyPayload(characterId)
}]
};
}
/**
* Lookup target by characterId or first+last name. Adjacency not required (inspect UI).
*/
lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName)
{
let row = null;
if (targetCharacterId)
{ row = this.stateDb.getCharacter(targetCharacterId | 0); }
else
{
const first = String(firstName ?? "").trim();
const last = String(lastName ?? "").trim();
if (!first || !last)
{ throw userError("Enter a first and last name."); }
row = this.stateDb.getCharacterByName(first, last);
}
if (!row)
{ throw userError("No adventurer by that name."); }
const amountCopper = this.stateDb.getCharacterBounty(row.character_id);
const bag = this.#loadBagQuiet(row.character_id);
return {
events: [{
type: "character-bounty",
sessionId,
characterId: requesterCharacterId,
target: {
characterId: row.character_id,
firstName: row.first_name,
lastName: row.last_name,
sex: row.sex,
layers: layersFromBag(row.sex, bag),
amountCopper,
amountLabel: formatBountyCopper(amountCopper)
}
}]
};
}
placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper)
{
this.#requireNearOffice(placerCharacterId);
const first = String(firstName ?? "").trim();
const last = String(lastName ?? "").trim();
if (!first || !last)
{ throw userError("Enter a first and last name."); }
const copper = Math.floor(Number(amountCopper) || 0);
if (!Number.isFinite(copper) || copper <= 0)
{ throw userError("Enter a positive coin amount."); }
const target = this.stateDb.getCharacterByName(first, last);
if (!target)
{ throw userError("No adventurer by that name."); }
const targetId = target.character_id | 0;
if (targetId === (placerCharacterId | 0))
{ throw userError("You cannot place a bounty on yourself."); }
const previous = this.stateDb.getCharacterBounty(targetId);
const bag = this.#loadBag(placerCharacterId);
const paid = takeCoinsFromSlots(bag.inventory ?? [], copper);
if (!paid.ok)
{ throw userError(`Need ${formatQuantity(copper)} in your inventory.`); }
bag.inventory = paid.slots;
this.#persistBag(placerCharacterId, bag);
const nextAmount = this.stateDb.addCharacterBounty(targetId, copper);
this.simulation.pendingPrivate.push({
type: "toast",
characterId: targetId,
message: previous > 0
? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.`
: `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.`
});
return {
events: [{
type: "bounty-snapshot",
sessionId,
characterId: placerCharacterId,
...this.#myBountyPayload(placerCharacterId),
raised: {
characterId: targetId,
firstName: target.first_name,
lastName: target.last_name,
amountCopper: nextAmount,
amountLabel: formatBountyCopper(nextAmount),
addedCopper: copper,
message: previous > 0
? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.`
: `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.`
}
}]
};
}
/**
* Called when a player dies. PvP killer collects full bounty into vault + office letter.
* @returns {{ paidCopper: number, victimName: string } | null}
*/
settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
{
const attackerId = attackerEntityId | 0;
if (!attackerId)
{ return null; }
const attackerRec = this.simulation.directory.get(attackerId);
const killerCharacterId = attackerRec?.characterId | 0;
if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0))
{ return null; }
const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId);
if (paidCopper <= 0)
{ return null; }
const bag = this.#loadBag(killerCharacterId);
const vault = normalizeVault(
bag.vaultReserved != null
? { slots: bag.vault, reserved: bag.vaultReserved }
: bag.vault
);
const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true });
bag.vault = added.slots;
bag.vaultReserved = vault.reserved;
this.#persistBag(killerCharacterId, bag);
const victim = this.stateDb.getCharacter(victimCharacterId);
const killer = this.stateDb.getCharacter(killerCharacterId);
const victimName = victim
? `${victim.first_name} ${victim.last_name}`.trim()
: "someone";
const killerName = killer
? `${killer.first_name} ${killer.last_name}`.trim()
: "Adventurer";
this.#dispatchPayoutLetter({
killerCharacterId,
killerName,
victimName,
paidCopper,
deathTileX,
deathTileY
});
this.simulation.pendingPrivate.push({
type: "toast",
characterId: killerCharacterId,
message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).`
});
return { paidCopper, victimName };
}
#myBountyPayload (characterId)
{
const amountCopper = this.stateDb.getCharacterBounty(characterId);
return {
myAmountCopper: amountCopper,
myAmountLabel: formatBountyCopper(amountCopper),
message: amountCopper > 0
? `Bounty on your head: ${formatBountyCopper(amountCopper)}.`
: "No bounty on your head."
};
}
#dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
{
const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
const body = bountyPayoutLetterBody({
killerName,
victimName,
amountCopper: paidCopper
}).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
const stack = {
itemId: ItemId.letter,
quantity: 1,
instance: {
kind: "letter",
letterId: randomUUID(),
authorCharacterId: 0,
authorDisplayName: "Bounty Office",
body,
opened: false,
writtenAt: Date.now()
}
};
try
{
this.courier.dispatchHeldCargo({
senderCharacterId: killerCharacterId,
originTileX: office.tileX,
originTileY: office.tileY,
destination: { kind: "bank" },
cargo: { kind: "item", stack },
vaultCharacterId: killerCharacterId
});
}
catch
{
/* Coins already vaulted; letter is best-effort if no bank exists. */
}
}
#requireNearOffice (characterId)
{
const entityId = this.simulation.characterEntities.get(characterId);
const position = entityId ? this.simulation.positionOf(entityId) : null;
if (!position)
{ throw userError("Enter the world before using a Bounty Office."); }
const tiles = this.courier?.bountyOfficeTiles ?? [];
if (!tiles.length)
{ throw userError("No Bounty Office exists in this world yet."); }
const near = tiles.some((tile) =>
chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
if (!near)
{ throw userError("Stand next to a Bounty Office."); }
return position;
}
#loadBagQuiet (characterId)
{
const onlineId = this.simulation.characterEntities.get(characterId);
return onlineId
? this.simulation.bagOf(onlineId)
: this.stateDb.getBag(characterId);
}
#loadBag (characterId)
{
const bag = this.#loadBagQuiet(characterId);
if (!bag)
{ throw userError("No bag."); }
return bag;
}
#persistBag (characterId, bag)
{
this.stateDb.saveBag(characterId, bag);
const onlineId = this.simulation.characterEntities.get(characterId);
if (onlineId)
{
this.simulation.applyBag(onlineId, bag);
this.simulation.pushInventory(characterId, bag);
}
}
}
@@ -0,0 +1,321 @@import { randomUUID } from "node:crypto";import { ItemId, LETTER_MAX_BODY_CHARS, formatQuantity } from "../../../shared/definitions/items.js";import { bountyPayoutLetterBody, formatBountyCopper } from "../../../shared/bounty/pricing.js";import { layersFromBag } from "../../../shared/appearance/layers.js";import { addCoinsToSlots, normalizeVault, takeCoinsFromSlots} from "../../../shared/items/inventory.js";function userError (message){ const error = new Error(message); error.userFacing = true; return error;}function chebyshev (ax, ay, bx, by){ return Math.max(Math.abs(ax - bx), Math.abs(ay - by));}/** * Bounty office: place/raise bounties (near office), settle PvP kills into killer vault + letter. */export class BountyService{ constructor (stateDb, simulation, courier) { this.stateDb = stateDb; this.simulation = simulation; this.courier = courier; } handleCommand (sessionId, command) { switch (command.type) { case "open-bounty": return this.open(sessionId, command.characterId); case "raise-bounty": return this.placeOrRaise( sessionId, command.characterId, command.firstName, command.lastName, command.amountCopper ); case "get-character-bounty": return this.lookup( sessionId, command.characterId, command.targetCharacterId, command.firstName, command.lastName ); case "close-bounty": return { events: [{ type: "bounty-closed", sessionId, characterId: command.characterId }] }; default: return null; } } open (sessionId, characterId) { this.#requireNearOffice(characterId); return { events: [{ type: "bounty-snapshot", sessionId, characterId, ...this.#myBountyPayload(characterId) }] }; } /** * Lookup target by characterId or first+last name. Adjacency not required (inspect UI). */ lookup (sessionId, requesterCharacterId, targetCharacterId, firstName, lastName) { let row = null; if (targetCharacterId) { row = this.stateDb.getCharacter(targetCharacterId | 0); } else { const first = String(firstName ?? "").trim(); const last = String(lastName ?? "").trim(); if (!first || !last) { throw userError("Enter a first and last name."); } row = this.stateDb.getCharacterByName(first, last); } if (!row) { throw userError("No adventurer by that name."); } const amountCopper = this.stateDb.getCharacterBounty(row.character_id); const bag = this.#loadBagQuiet(row.character_id); return { events: [{ type: "character-bounty", sessionId, characterId: requesterCharacterId, target: { characterId: row.character_id, firstName: row.first_name, lastName: row.last_name, sex: row.sex, layers: layersFromBag(row.sex, bag), amountCopper, amountLabel: formatBountyCopper(amountCopper) } }] }; } placeOrRaise (sessionId, placerCharacterId, firstName, lastName, amountCopper) { this.#requireNearOffice(placerCharacterId); const first = String(firstName ?? "").trim(); const last = String(lastName ?? "").trim(); if (!first || !last) { throw userError("Enter a first and last name."); } const copper = Math.floor(Number(amountCopper) || 0); if (!Number.isFinite(copper) || copper <= 0) { throw userError("Enter a positive coin amount."); } const target = this.stateDb.getCharacterByName(first, last); if (!target) { throw userError("No adventurer by that name."); } const targetId = target.character_id | 0; if (targetId === (placerCharacterId | 0)) { throw userError("You cannot place a bounty on yourself."); } const previous = this.stateDb.getCharacterBounty(targetId); const bag = this.#loadBag(placerCharacterId); const paid = takeCoinsFromSlots(bag.inventory ?? [], copper); if (!paid.ok) { throw userError(`Need ${formatQuantity(copper)} in your inventory.`); } bag.inventory = paid.slots; this.#persistBag(placerCharacterId, bag); const nextAmount = this.stateDb.addCharacterBounty(targetId, copper); this.simulation.pendingPrivate.push({ type: "toast", characterId: targetId, message: previous > 0 ? `Someone raised the bounty on your head to ${formatBountyCopper(nextAmount)}.` : `A bounty of ${formatBountyCopper(nextAmount)} has been placed on your head.` }); return { events: [{ type: "bounty-snapshot", sessionId, characterId: placerCharacterId, ...this.#myBountyPayload(placerCharacterId), raised: { characterId: targetId, firstName: target.first_name, lastName: target.last_name, amountCopper: nextAmount, amountLabel: formatBountyCopper(nextAmount), addedCopper: copper, message: previous > 0 ? `Raised bounty on ${target.first_name} ${target.last_name} to ${formatBountyCopper(nextAmount)}.` : `Placed a ${formatBountyCopper(nextAmount)} bounty on ${target.first_name} ${target.last_name}.` } }] }; } /** * Called when a player dies. PvP killer collects full bounty into vault + office letter. * @returns {{ paidCopper: number, victimName: string } | null} */ settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY) { const attackerId = attackerEntityId | 0; if (!attackerId) { return null; } const attackerRec = this.simulation.directory.get(attackerId); const killerCharacterId = attackerRec?.characterId | 0; if (!killerCharacterId || killerCharacterId === (victimCharacterId | 0)) { return null; } const paidCopper = this.stateDb.takeCharacterBounty(victimCharacterId); if (paidCopper <= 0) { return null; } const bag = this.#loadBag(killerCharacterId); const vault = normalizeVault( bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); const added = addCoinsToSlots(vault.slots, paidCopper, { growable: true }); bag.vault = added.slots; bag.vaultReserved = vault.reserved; this.#persistBag(killerCharacterId, bag); const victim = this.stateDb.getCharacter(victimCharacterId); const killer = this.stateDb.getCharacter(killerCharacterId); const victimName = victim ? `${victim.first_name} ${victim.last_name}`.trim() : "someone"; const killerName = killer ? `${killer.first_name} ${killer.last_name}`.trim() : "Adventurer"; this.#dispatchPayoutLetter({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY }); this.simulation.pendingPrivate.push({ type: "toast", characterId: killerCharacterId, message: `Bounty collected: ${formatBountyCopper(paidCopper)} for defeating ${victimName} (sent to vault).` }); return { paidCopper, victimName }; } #myBountyPayload (characterId) { const amountCopper = this.stateDb.getCharacterBounty(characterId); return { myAmountCopper: amountCopper, myAmountLabel: formatBountyCopper(amountCopper), message: amountCopper > 0 ? `Bounty on your head: ${formatBountyCopper(amountCopper)}.` : "No bounty on your head." }; } #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY }) { const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0) ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 }; const body = bountyPayoutLetterBody({ killerName, victimName, amountCopper: paidCopper }).replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS); const stack = { itemId: ItemId.letter, quantity: 1, instance: { kind: "letter", letterId: randomUUID(), authorCharacterId: 0, authorDisplayName: "Bounty Office", body, opened: false, writtenAt: Date.now() } }; try { this.courier.dispatchHeldCargo({ senderCharacterId: killerCharacterId, originTileX: office.tileX, originTileY: office.tileY, destination: { kind: "bank" }, cargo: { kind: "item", stack }, vaultCharacterId: killerCharacterId }); } catch { /* Coins already vaulted; letter is best-effort if no bank exists. */ } } #requireNearOffice (characterId) { const entityId = this.simulation.characterEntities.get(characterId); const position = entityId ? this.simulation.positionOf(entityId) : null; if (!position) { throw userError("Enter the world before using a Bounty Office."); } const tiles = this.courier?.bountyOfficeTiles ?? []; if (!tiles.length) { throw userError("No Bounty Office exists in this world yet."); } const near = tiles.some((tile) => chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1); if (!near) { throw userError("Stand next to a Bounty Office."); } return position; } #loadBagQuiet (characterId) { const onlineId = this.simulation.characterEntities.get(characterId); return onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); } #loadBag (characterId) { const bag = this.#loadBagQuiet(characterId); if (!bag) { throw userError("No bag."); } return bag; } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId); if (onlineId) { this.simulation.applyBag(onlineId, bag); this.simulation.pushInventory(characterId, bag); } }}@@ -1,5 +1,11 @@
import { SEX } from "../../../shared/protocol/constants.js";
import { normalizeName } from "../persistence/stateDb.js";
import {
DEFAULT_HAIR_STYLE,
isValidHairStyle,
normalizeHairSliders,
normalizeHairStyle
} from "../../../shared/appearance/hair.js";
export class CharacterService
{
@@ -14,7 +20,7 @@ export class CharacterService
return this.stateDb.listCharacters(accountId).map(publicCharacter);
}
create (account, firstName, lastName, sex)
create (account, firstName, lastName, sex, hair = null, starterSettings = null)
{
const first = String(firstName ?? "").trim();
const last = String(lastName ?? "").trim();
@@ -33,7 +39,17 @@ export class CharacterService
if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized))
{ throw userError("You already have a character with that name."); }
const character = this.stateDb.createCharacter(account.account_id, first, last, sex, 8, 8);
const hairFields = normalizeCreateHair(sex, hair);
const character = this.stateDb.createCharacter(
account.account_id,
first,
last,
sex,
8,
8,
hairFields,
starterSettings
);
return publicCharacter(character);
}
@@ -91,6 +107,11 @@ export class CharacterService
export function publicCharacter (row)
{
const sliders = normalizeHairSliders({
hue: row.hair_hue,
saturation: row.hair_saturation,
darkness: row.hair_darkness
});
return {
characterId: row.character_id,
firstName: row.first_name,
@@ -99,7 +120,25 @@ export function publicCharacter (row)
tileX: row.tile_x,
tileY: row.tile_y,
gait: row.gait,
deletionScheduledAt: row.deletion_scheduled_at ?? null
deletionScheduledAt: row.deletion_scheduled_at ?? null,
hairStyle: row.hair_style ?? null,
hairHue: sliders.hue,
hairSaturation: sliders.saturation,
hairDarkness: sliders.darkness
};
}
export function normalizeCreateHair (sex, hair)
{
if (!isValidHairStyle(sex, hair?.style))
{ throw userError("Unknown hair style."); }
const style = normalizeHairStyle(sex, hair?.style ?? DEFAULT_HAIR_STYLE);
const sliders = normalizeHairSliders(hair);
return {
style,
hue: sliders.hue,
saturation: sliders.saturation,
darkness: sliders.darkness
};
}
@@ -1,5 +1,11 @@import { SEX } from "../../../shared/protocol/constants.js";import { SEX } from "../../../shared/protocol/constants.js";import { normalizeName } from "../persistence/stateDb.js";import { normalizeName } from "../persistence/stateDb.js";import { DEFAULT_HAIR_STYLE, isValidHairStyle, normalizeHairSliders, normalizeHairStyle} from "../../../shared/appearance/hair.js";export class CharacterServiceexport class CharacterService{{@@ -14,7 +20,7 @@ export class CharacterService return this.stateDb.listCharacters(accountId).map(publicCharacter); return this.stateDb.listCharacters(accountId).map(publicCharacter); } } create (account, firstName, lastName, sex) create (account, firstName, lastName, sex, hair = null, starterSettings = null) { { const first = String(firstName ?? "").trim(); const first = String(firstName ?? "").trim(); const last = String(lastName ?? "").trim(); const last = String(lastName ?? "").trim();@@ -33,7 +39,17 @@ export class CharacterService if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized)) if (existing.some((row) => row.first_normalized === firstNormalized && row.last_normalized === lastNormalized)) { throw userError("You already have a character with that name."); } { throw userError("You already have a character with that name."); } const character = this.stateDb.createCharacter(account.account_id, first, last, sex, 8, 8); const hairFields = normalizeCreateHair(sex, hair); const character = this.stateDb.createCharacter( account.account_id, first, last, sex, 8, 8, hairFields, starterSettings ); return publicCharacter(character); return publicCharacter(character); } }@@ -91,6 +107,11 @@ export class CharacterServiceexport function publicCharacter (row)export function publicCharacter (row){{ const sliders = normalizeHairSliders({ hue: row.hair_hue, saturation: row.hair_saturation, darkness: row.hair_darkness }); return { return { characterId: row.character_id, characterId: row.character_id, firstName: row.first_name, firstName: row.first_name,@@ -99,7 +120,25 @@ export function publicCharacter (row) tileX: row.tile_x, tileX: row.tile_x, tileY: row.tile_y, tileY: row.tile_y, gait: row.gait, gait: row.gait, deletionScheduledAt: row.deletion_scheduled_at ?? null deletionScheduledAt: row.deletion_scheduled_at ?? null, hairStyle: row.hair_style ?? null, hairHue: sliders.hue, hairSaturation: sliders.saturation, hairDarkness: sliders.darkness };}export function normalizeCreateHair (sex, hair){ if (!isValidHairStyle(sex, hair?.style)) { throw userError("Unknown hair style."); } const style = normalizeHairStyle(sex, hair?.style ?? DEFAULT_HAIR_STYLE); const sliders = normalizeHairSliders(hair); return { style, hue: sliders.hue, saturation: sliders.saturation, darkness: sliders.darkness }; };}}@@ -14,6 +14,7 @@ import {
effectiveSkillLevel,
equipmentBonusesFromSlots
} from "../../../shared/equipment/stats.js";
import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";
import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -78,6 +79,9 @@ function playerCombatLevels (ecs, handle, profile)
const skills = ecs.get(handle, Component.skills);
const equipment = ecs.get(handle, Component.equipment);
const bonuses = equipmentBonusesFromSlots(equipment?.slots);
const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now());
bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0);
bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0);
return {
hitLevel: skillLevel(skills, profile.hitSkillId),
damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
@@ -14,6 +14,7 @@ import { effectiveSkillLevel, effectiveSkillLevel, equipmentBonusesFromSlots equipmentBonusesFromSlots} from "../../../shared/equipment/stats.js";} from "../../../shared/equipment/stats.js";import { statusSkillBonuses } from "../../../shared/statusEffects/rules.js";import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";import { chunkBoundsAround, findPath } from "../navigation/astar.js";import { chunkBoundsAround, findPath } from "../navigation/astar.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -78,6 +79,9 @@ function playerCombatLevels (ecs, handle, profile) const skills = ecs.get(handle, Component.skills); const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots); const bonuses = equipmentBonusesFromSlots(equipment?.slots); const status = statusSkillBonuses(ecs.get(handle, Component.statusEffects), Date.now()); bonuses[SkillId.strength] = (bonuses[SkillId.strength] ?? 0) + (status.strength ?? 0); bonuses[SkillId.mind] = (bonuses[SkillId.mind] ?? 0) + (status.mind ?? 0); return { return { hitLevel: skillLevel(skills, profile.hitSkillId), hitLevel: skillLevel(skills, profile.hitSkillId), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),@@ -26,49 +26,77 @@ export class CourierService
this.worldDb = worldDb;
this.simulation = simulation;
this.bankTiles = [];
this.bountyOfficeTiles = [];
this.refreshBankIndex();
this.refreshBountyOfficeIndex();
}
refreshBankIndex ()
{
this.bankTiles = this.#listBlockTiles(BlockType.bank);
}
refreshBountyOfficeIndex ()
{
this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
}
#listBlockTiles (typeId)
{
const revisionId = this.worldDb.getActiveRevisionId();
const banks = [];
const tiles = [];
for (const coord of this.worldDb.listChunkCoords(revisionId))
{
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
if (!row)
{ continue; }
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
for (let localY = 0; localY < CHUNK_SIZE; localY++)
{
for (let localX = 0; localX < CHUNK_SIZE; localX++)
{
const block = data.blocks[localY * CHUNK_SIZE + localX];
if (block?.typeId !== BlockType.bank)
if (block?.typeId !== typeId)
{ continue; }
banks.push({
tiles.push({
tileX: coord.chunk_x * CHUNK_SIZE + localX,
tileY: coord.chunk_y * CHUNK_SIZE + localY
});
}
}
}
this.bankTiles = banks;
return tiles;
}
nearestBank (tileX, tileY)
{
if (!this.bankTiles.length)
return this.#nearestTile(this.bankTiles, tileX, tileY);
}
nearestBountyOffice (tileX, tileY)
{
return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY);
}
isAdjacentToBountyOffice (tileX, tileY)
{
return this.bountyOfficeTiles.some((office) =>
Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1);
}
#nearestTile (tiles, tileX, tileY)
{
if (!tiles.length)
{ return null; }
let best = null;
let bestDist = Infinity;
for (const bank of this.bankTiles)
for (const tile of tiles)
{
const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);
const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
if (dist < bestDist)
{
bestDist = dist;
best = bank;
best = tile;
}
}
return best;
@@ -26,49 +26,77 @@ export class CourierService this.worldDb = worldDb; this.worldDb = worldDb; this.simulation = simulation; this.simulation = simulation; this.bankTiles = []; this.bankTiles = []; this.bountyOfficeTiles = []; this.refreshBankIndex(); this.refreshBankIndex(); this.refreshBountyOfficeIndex(); } } refreshBankIndex () refreshBankIndex () { this.bankTiles = this.#listBlockTiles(BlockType.bank); } refreshBountyOfficeIndex () { this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice); } #listBlockTiles (typeId) { { const revisionId = this.worldDb.getActiveRevisionId(); const revisionId = this.worldDb.getActiveRevisionId(); const banks = []; const tiles = []; for (const coord of this.worldDb.listChunkCoords(revisionId)) for (const coord of this.worldDb.listChunkCoords(revisionId)) { { const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); if (!row) if (!row) { continue; } { continue; } const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId); const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y); for (let localY = 0; localY < CHUNK_SIZE; localY++) for (let localY = 0; localY < CHUNK_SIZE; localY++) { { for (let localX = 0; localX < CHUNK_SIZE; localX++) for (let localX = 0; localX < CHUNK_SIZE; localX++) { { const block = data.blocks[localY * CHUNK_SIZE + localX]; const block = data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== BlockType.bank) if (block?.typeId !== typeId) { continue; } { continue; } banks.push({ tiles.push({ tileX: coord.chunk_x * CHUNK_SIZE + localX, tileX: coord.chunk_x * CHUNK_SIZE + localX, tileY: coord.chunk_y * CHUNK_SIZE + localY tileY: coord.chunk_y * CHUNK_SIZE + localY }); }); } } } } } } this.bankTiles = banks; return tiles; } } nearestBank (tileX, tileY) nearestBank (tileX, tileY) { { if (!this.bankTiles.length) return this.#nearestTile(this.bankTiles, tileX, tileY); } nearestBountyOffice (tileX, tileY) { return this.#nearestTile(this.bountyOfficeTiles, tileX, tileY); } isAdjacentToBountyOffice (tileX, tileY) { return this.bountyOfficeTiles.some((office) => Math.max(Math.abs(office.tileX - tileX), Math.abs(office.tileY - tileY)) <= 1); } #nearestTile (tiles, tileX, tileY) { if (!tiles.length) { return null; } { return null; } let best = null; let best = null; let bestDist = Infinity; let bestDist = Infinity; for (const bank of this.bankTiles) for (const tile of tiles) { { const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY); const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY); if (dist < bestDist) if (dist < bestDist) { { bestDist = dist; bestDist = dist; best = bank; best = tile; } } } } return best; return best;@@ -20,5 +20,6 @@ export const Component = Object.freeze({
dead: "dead",
stamina: "stamina",
gather: "gather",
shop: "shop"
shop: "shop",
statusEffects: "statusEffects"
});
@@ -20,5 +20,6 @@ export const Component = Object.freeze({ dead: "dead", dead: "dead", stamina: "stamina", stamina: "stamina", gather: "gather", gather: "gather", shop: "shop" shop: "shop", statusEffects: "statusEffects"});});@@ -1,16 +1,14 @@
import { Component } from "./components.js";
import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
import { resolveEquipTint } from "../../../shared/render/tint.js";
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
import {
statusExtraLightRadius,
statusVisualScale,
publicStatusEffectsView
} from "../../../shared/statusEffects/rules.js";
import { mobDefinition } from "../../../shared/definitions/mobs.js";
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
import { shopHasInterface } from "../shop/service.js";
function bodySprite (sex)
{
const key = sex === "female" ? "player-body-female" : "player-body-male";
return spriteImageName("character", key, key);
}
import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";
export function normalizeMobileComponents (components)
{
@@ -68,9 +66,13 @@ export function publicEntityView (ecs, entityId)
const flight = ecs.get(handle, Component.flight);
const health = ecs.get(handle, Component.health);
const equipment = ecs.get(handle, Component.equipment);
const statusEffects = ecs.get(handle, Component.statusEffects);
const now = Date.now();
const layers = appearanceLayers(ecs, handle, appearance);
const mob = creature ? mobDefinition(creature.mobTypeId) : null;
const isMob = !!creature && !character;
const gearLight = equippedLightRadiusTiles(equipment);
const effectLight = statusExtraLightRadius(statusEffects, now);
return {
entityId,
tileX: position.tileX,
@@ -93,32 +95,16 @@ export function publicEntityView (ecs, entityId)
maxHealth: health ? health.max : undefined,
sprite: layers[0]?.sprite ?? null,
layers,
lightRadiusTiles: equippedLightRadiusTiles(equipment)
lightRadiusTiles: Math.max(gearLight, effectLight),
visualScale: statusVisualScale(statusEffects, now),
statusEffects: publicStatusEffectsView(statusEffects, now)
};
}
export function appearanceLayers (ecs, handle, appearance)
{
const sprite = appearance?.sprite ?? bodySprite(appearance?.sex);
const layers = [{ sprite }];
const equipment = ecs.get(handle, Component.equipment);
for (const slot of EQUIPMENT_DRAW_ORDER)
{
const worn = equipment?.slots?.[slot];
if (!worn)
{ continue; }
const overlay = itemEquipSprite(worn.itemId);
if (overlay)
{
const tint = resolveEquipTint(worn.itemId, worn.instance);
layers.push({
sprite: overlay,
itemId: worn.itemId,
...(tint ? { tint } : {})
});
}
}
return layers;
return composeAppearanceLayers(appearance, equipment?.slots ?? {});
}
export function replicationSpawn (view)
@@ -147,7 +133,9 @@ export function replicationSpawn (view)
untargetable: !!view.untargetable,
freeFlight: !!view.freeFlight,
health: view.health,
maxHealth: view.maxHealth
maxHealth: view.maxHealth,
lightRadiusTiles: view.lightRadiusTiles ?? 0,
visualScale: view.visualScale ?? 1
};
}
@@ -180,7 +168,8 @@ export function replicationAppearance (view)
tileY: view.tileY,
sprite: view.sprite ?? null,
layers: view.layers ?? [],
lightRadiusTiles: view.lightRadiusTiles ?? 0
lightRadiusTiles: view.lightRadiusTiles ?? 0,
visualScale: view.visualScale ?? 1
};
}
@@ -1,16 +1,14 @@import { Component } from "./components.js";import { Component } from "./components.js";import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";import { resolveEquipTint } from "../../../shared/render/tint.js";import {import { spriteImageName } from "../../../shared/definitions/tileSprites.js"; statusExtraLightRadius, statusVisualScale, publicStatusEffectsView} from "../../../shared/statusEffects/rules.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobCanFight } from "../../../shared/definitions/mobCombat.js";import { mobCanFight } from "../../../shared/definitions/mobCombat.js";import { shopHasInterface } from "../shop/service.js";import { shopHasInterface } from "../shop/service.js";import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";function bodySprite (sex){ const key = sex === "female" ? "player-body-female" : "player-body-male"; return spriteImageName("character", key, key);}export function normalizeMobileComponents (components)export function normalizeMobileComponents (components){{@@ -68,9 +66,13 @@ export function publicEntityView (ecs, entityId) const flight = ecs.get(handle, Component.flight); const flight = ecs.get(handle, Component.flight); const health = ecs.get(handle, Component.health); const health = ecs.get(handle, Component.health); const equipment = ecs.get(handle, Component.equipment); const equipment = ecs.get(handle, Component.equipment); const statusEffects = ecs.get(handle, Component.statusEffects); const now = Date.now(); const layers = appearanceLayers(ecs, handle, appearance); const layers = appearanceLayers(ecs, handle, appearance); const mob = creature ? mobDefinition(creature.mobTypeId) : null; const mob = creature ? mobDefinition(creature.mobTypeId) : null; const isMob = !!creature && !character; const isMob = !!creature && !character; const gearLight = equippedLightRadiusTiles(equipment); const effectLight = statusExtraLightRadius(statusEffects, now); return { return { entityId, entityId, tileX: position.tileX, tileX: position.tileX,@@ -93,32 +95,16 @@ export function publicEntityView (ecs, entityId) maxHealth: health ? health.max : undefined, maxHealth: health ? health.max : undefined, sprite: layers[0]?.sprite ?? null, sprite: layers[0]?.sprite ?? null, layers, layers, lightRadiusTiles: equippedLightRadiusTiles(equipment) lightRadiusTiles: Math.max(gearLight, effectLight), visualScale: statusVisualScale(statusEffects, now), statusEffects: publicStatusEffectsView(statusEffects, now) }; };}}export function appearanceLayers (ecs, handle, appearance)export function appearanceLayers (ecs, handle, appearance){{ const sprite = appearance?.sprite ?? bodySprite(appearance?.sex); const layers = [{ sprite }]; const equipment = ecs.get(handle, Component.equipment); const equipment = ecs.get(handle, Component.equipment); for (const slot of EQUIPMENT_DRAW_ORDER) return composeAppearanceLayers(appearance, equipment?.slots ?? {}); { const worn = equipment?.slots?.[slot]; if (!worn) { continue; } const overlay = itemEquipSprite(worn.itemId); if (overlay) { const tint = resolveEquipTint(worn.itemId, worn.instance); layers.push({ sprite: overlay, itemId: worn.itemId, ...(tint ? { tint } : {}) }); } } return layers;}}export function replicationSpawn (view)export function replicationSpawn (view)@@ -147,7 +133,9 @@ export function replicationSpawn (view) untargetable: !!view.untargetable, untargetable: !!view.untargetable, freeFlight: !!view.freeFlight, freeFlight: !!view.freeFlight, health: view.health, health: view.health, maxHealth: view.maxHealth maxHealth: view.maxHealth, lightRadiusTiles: view.lightRadiusTiles ?? 0, visualScale: view.visualScale ?? 1 }; };}}@@ -180,7 +168,8 @@ export function replicationAppearance (view) tileY: view.tileY, tileY: view.tileY, sprite: view.sprite ?? null, sprite: view.sprite ?? null, layers: view.layers ?? [], layers: view.layers ?? [], lightRadiusTiles: view.lightRadiusTiles ?? 0 lightRadiusTiles: view.lightRadiusTiles ?? 0, visualScale: view.visualScale ?? 1 }; };}}@@ -9,6 +9,11 @@ import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields,
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
import {
normalizeStarterLoadout,
starterLoadoutsEqual,
diffStarterLoadout
} from "../../../shared/items/starterLoadout.js";
export class EditorService
{
@@ -23,14 +28,14 @@ export class EditorService
const settings = this.worldDb.getLiveSettings();
const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
const data = row
? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY)
: createEmptyChunkData(settings.defaultGroundTypeId);
const isOpen = (x, y) =>
{
const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
if (!neighbor)
{ return false; }
return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId).open;
return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open;
};
return {
chunkX,
@@ -124,6 +129,20 @@ export class EditorService
{
next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues);
}
if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
|| Object.prototype.hasOwnProperty.call(partial, "starterInventory"))
{
const loadout = normalizeStarterLoadout({
starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
? partial.starterEquipment
: current.starterEquipment,
starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory")
? partial.starterInventory
: current.starterInventory
});
next.starterEquipment = loadout.equipment;
next.starterInventory = loadout.inventory;
}
const { bullets: scalarBullets, changed } = diffSettings(current, next);
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
? diffItemSeedValues(
@@ -137,7 +156,18 @@ export class EditorService
{
changed.itemSeedValues = next.itemSeedValues;
}
const bullets = [...scalarBullets, ...seedBullets];
const starterChanged = !starterLoadoutsEqual(current, next)
&& (Object.prototype.hasOwnProperty.call(partial, "starterEquipment")
|| Object.prototype.hasOwnProperty.call(partial, "starterInventory"));
if (starterChanged)
{
changed.starterEquipment = next.starterEquipment;
changed.starterInventory = next.starterInventory;
}
const starterBullets = starterChanged
? diffStarterLoadout(current, next)
: [];
const bullets = [...scalarBullets, ...seedBullets, ...starterBullets];
if (Object.keys(changed).length === 0)
{
return {
@@ -151,8 +181,15 @@ export class EditorService
...changed,
itemSeedValues: changed.itemSeedValues
?? normalizeItemSeedValues(current.itemSeedValues)
?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }
?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) },
starterEquipment: changed.starterEquipment ?? current.starterEquipment
?? DEFAULT_WORLD_SETTINGS.starterEquipment,
starterInventory: changed.starterInventory ?? current.starterInventory
?? DEFAULT_WORLD_SETTINGS.starterInventory
};
const normalized = normalizeStarterLoadout(settings);
settings.starterEquipment = normalized.equipment;
settings.starterInventory = normalized.inventory;
this.worldDb.saveLiveSettings(settings, editorAdminId);
this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
return {
@@ -183,7 +220,7 @@ export class EditorService
const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
return row
? decodeChunkBlob(row.data_blob, defaultGroundTypeId)
? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
: createEmptyChunkData(defaultGroundTypeId);
}
}
@@ -9,6 +9,11 @@ import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields,import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";import { normalizeStarterLoadout, starterLoadoutsEqual, diffStarterLoadout} from "../../../shared/items/starterLoadout.js";export class EditorServiceexport class EditorService{{@@ -23,14 +28,14 @@ export class EditorService const settings = this.worldDb.getLiveSettings(); const settings = this.worldDb.getLiveSettings(); const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId); const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId); const data = row const data = row ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId) ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(settings.defaultGroundTypeId); : createEmptyChunkData(settings.defaultGroundTypeId); const isOpen = (x, y) => const isOpen = (x, y) => { { const neighbor = this.worldDb.getChunkVersion(x, y, revisionId); const neighbor = this.worldDb.getChunkVersion(x, y, revisionId); if (!neighbor) if (!neighbor) { return false; } { return false; } return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId).open; return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open; }; }; return { return { chunkX, chunkX,@@ -124,6 +129,20 @@ export class EditorService { { next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues); next.itemSeedValues = normalizeItemSeedValues(partial.itemSeedValues); } } if (Object.prototype.hasOwnProperty.call(partial, "starterEquipment") || Object.prototype.hasOwnProperty.call(partial, "starterInventory")) { const loadout = normalizeStarterLoadout({ starterEquipment: Object.prototype.hasOwnProperty.call(partial, "starterEquipment") ? partial.starterEquipment : current.starterEquipment, starterInventory: Object.prototype.hasOwnProperty.call(partial, "starterInventory") ? partial.starterInventory : current.starterInventory }); next.starterEquipment = loadout.equipment; next.starterInventory = loadout.inventory; } const { bullets: scalarBullets, changed } = diffSettings(current, next); const { bullets: scalarBullets, changed } = diffSettings(current, next); const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues") const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues") ? diffItemSeedValues( ? diffItemSeedValues(@@ -137,7 +156,18 @@ export class EditorService { { changed.itemSeedValues = next.itemSeedValues; changed.itemSeedValues = next.itemSeedValues; } } const bullets = [...scalarBullets, ...seedBullets]; const starterChanged = !starterLoadoutsEqual(current, next) && (Object.prototype.hasOwnProperty.call(partial, "starterEquipment") || Object.prototype.hasOwnProperty.call(partial, "starterInventory")); if (starterChanged) { changed.starterEquipment = next.starterEquipment; changed.starterInventory = next.starterInventory; } const starterBullets = starterChanged ? diffStarterLoadout(current, next) : []; const bullets = [...scalarBullets, ...seedBullets, ...starterBullets]; if (Object.keys(changed).length === 0) if (Object.keys(changed).length === 0) { { return { return {@@ -151,8 +181,15 @@ export class EditorService ...changed, ...changed, itemSeedValues: changed.itemSeedValues itemSeedValues: changed.itemSeedValues ?? normalizeItemSeedValues(current.itemSeedValues) ?? normalizeItemSeedValues(current.itemSeedValues) ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) } ?? { ...(DEFAULT_WORLD_SETTINGS.itemSeedValues ?? {}) }, starterEquipment: changed.starterEquipment ?? current.starterEquipment ?? DEFAULT_WORLD_SETTINGS.starterEquipment, starterInventory: changed.starterInventory ?? current.starterInventory ?? DEFAULT_WORLD_SETTINGS.starterInventory }; }; const normalized = normalizeStarterLoadout(settings); settings.starterEquipment = normalized.equipment; settings.starterInventory = normalized.inventory; this.worldDb.saveLiveSettings(settings, editorAdminId); this.worldDb.saveLiveSettings(settings, editorAdminId); this.worldDb.appendSettingsChangelog(editorAdminId, bullets); this.worldDb.appendSettingsChangelog(editorAdminId, bullets); return { return {@@ -183,7 +220,7 @@ export class EditorService const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId); const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId); return row return row ? decodeChunkBlob(row.data_blob, defaultGroundTypeId) ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(defaultGroundTypeId); : createEmptyChunkData(defaultGroundTypeId); } }}}@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
import { publicSkillsView } from "../../../shared/skills/state.js";
@@ -24,9 +25,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
authSubject: identity.authSubject,
characterId: null,
entityId: null,
/** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
viewDistance: ViewDistance.long,
/** Chunks where entity / ground-item replication is active (3×3). */
entitySubscribed: new Set(),
/** Chunks with map + baked lighting only (5×5). */
/** Chunks with map + baked lighting only (5×5 when long). */
staticSubscribed: new Set()
};
auth.register(session);
@@ -82,8 +85,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
switch (message.type)
{
case MessageType.createCharacter:
characters.create(session.account, message.firstName, message.lastName, message.sex);
send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
{
const created = characters.create(
session.account,
message.firstName,
message.lastName,
message.sex,
message.hair ?? null,
simulation.settings
);
enterWorld(session, created.characterId);
}
break;
case MessageType.selectCharacter:
enterWorld(session, message.characterId);
@@ -204,6 +216,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
characterId: session.characterId
});
break;
case MessageType.openBounty:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "open-bounty",
characterId: session.characterId
});
break;
case MessageType.raiseBounty:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "raise-bounty",
characterId: session.characterId,
firstName: message.firstName,
lastName: message.lastName,
amountCopper: message.amountCopper
});
break;
case MessageType.getCharacterBounty:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "get-character-bounty",
characterId: session.characterId,
targetCharacterId: message.characterId,
firstName: message.firstName,
lastName: message.lastName
});
break;
case MessageType.closeBounty:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "close-bounty",
characterId: session.characterId
});
break;
case MessageType.openBarber:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "open-barber",
characterId: session.characterId
});
break;
case MessageType.setHair:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "set-hair",
characterId: session.characterId,
hair: message.hair ?? null
});
break;
case MessageType.closeBarber:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "close-barber",
characterId: session.characterId
});
break;
case MessageType.openCauldron:
requirePlaying(session);
simulation.enqueue(session.id, {
@@ -644,6 +712,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
});
}
break;
case MessageType.setGraphicsSettings:
{
const next = normalizeGraphicsSettings({
viewDistance: message.viewDistance ?? session.viewDistance
});
const changed = next.viewDistance !== session.viewDistance;
session.viewDistance = next.viewDistance;
if (changed && session.entityId)
{ syncSubscriptions(session, true); }
}
break;
default:
send(session, { type: MessageType.error, message: `Unknown message ${message.type}` });
}
@@ -682,6 +761,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
firstName: spawned.firstName,
lastName: spawned.lastName,
layers: spawned.layers ?? [],
health: spawned.health,
maxHealth: spawned.maxHealth,
settings: simulation.settings,
worldTime: simulation.worldTime()
});
@@ -735,8 +816,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
const centerChunkX = tileToChunk(position.tileX);
const centerChunkY = tileToChunk(position.tileY);
const mapRadius = staticChunkRadiusForViewDistance(
session.viewDistance,
STATIC_CHUNK_RADIUS,
VISIBLE_CHUNK_RADIUS
);
const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS);
const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
@@ -749,7 +835,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
}
}
const snapshots = simulation.snapshotsForView(session.entityId);
const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
for (const snapshot of snapshots)
{
const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
@@ -895,6 +981,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
});
continue;
}
if (event.type === "status-effects")
{
const session = event.sessionId != null
? sessions.get(event.sessionId)
: [...sessions.values()].find((entry) => entry.characterId === event.characterId);
if (!session)
{ continue; }
send(session, {
type: MessageType.statusEffects,
effects: event.effects ?? [],
blind: !!event.blind
});
continue;
}
if (event.type === "toast")
{
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
@@ -1027,6 +1127,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
{ send(session, { type: MessageType.marketClosed }); }
continue;
}
if (event.type === "bounty-snapshot")
{
const session = sessions.get(event.sessionId);
if (session)
{
send(session, {
type: MessageType.bountySnapshot,
myAmountCopper: event.myAmountCopper | 0,
myAmountLabel: event.myAmountLabel ?? "",
message: event.message ?? "",
raised: event.raised ?? null
});
}
continue;
}
if (event.type === "bounty-closed")
{
const session = sessions.get(event.sessionId);
if (session)
{ send(session, { type: MessageType.closeBounty }); }
continue;
}
if (event.type === "character-bounty")
{
const session = sessions.get(event.sessionId);
if (session)
{
send(session, {
type: MessageType.characterBounty,
target: event.target ?? null
});
}
continue;
}
if (event.type === "barber-snapshot")
{
const session = sessions.get(event.sessionId);
if (session)
{
send(session, {
type: MessageType.barberSnapshot,
sex: event.sex,
styles: event.styles ?? [],
hair: event.hair ?? null,
message: event.message ?? ""
});
}
continue;
}
if (event.type === "barber-closed")
{
const session = sessions.get(event.sessionId);
if (session)
{ send(session, { type: MessageType.closeBarber }); }
continue;
}
if (event.type === "market-trade")
{
for (const session of sessions.values())
@@ -1085,7 +1241,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
}
continue;
}
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")
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")
{ publishEntity(event); }
}
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -1177,6 +1333,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
});
continue;
}
if (event.type === "entity-health")
{
if (!seesTo && !seesFrom)
{ continue; }
send(session, {
type: MessageType.entityHealth,
entityId: event.entityId,
health: event.health,
maxHealth: event.maxHealth
});
continue;
}
if (event.type === "gather-swing" || event.type === "tile-shove")
{
if (!seesTo && !seesFrom)
@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";import { MessageType, GAIT } from "../../../shared/protocol/constants.js";import { MessageType, GAIT } from "../../../shared/protocol/constants.js";import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";import { publicSkillsView } from "../../../shared/skills/state.js";import { publicSkillsView } from "../../../shared/skills/state.js";@@ -24,9 +25,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, authSubject: identity.authSubject, authSubject: identity.authSubject, characterId: null, characterId: null, entityId: null, entityId: null, /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */ viewDistance: ViewDistance.long, /** Chunks where entity / ground-item replication is active (3×3). */ /** Chunks where entity / ground-item replication is active (3×3). */ entitySubscribed: new Set(), entitySubscribed: new Set(), /** Chunks with map + baked lighting only (5×5). */ /** Chunks with map + baked lighting only (5×5 when long). */ staticSubscribed: new Set() staticSubscribed: new Set() }; }; auth.register(session); auth.register(session);@@ -82,8 +85,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, switch (message.type) switch (message.type) { { case MessageType.createCharacter: case MessageType.createCharacter: characters.create(session.account, message.firstName, message.lastName, message.sex); { send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) }); const created = characters.create( session.account, message.firstName, message.lastName, message.sex, message.hair ?? null, simulation.settings ); enterWorld(session, created.characterId); } break; break; case MessageType.selectCharacter: case MessageType.selectCharacter: enterWorld(session, message.characterId); enterWorld(session, message.characterId);@@ -204,6 +216,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, characterId: session.characterId characterId: session.characterId }); }); break; break; case MessageType.openBounty: requirePlaying(session); simulation.enqueue(session.id, { type: "open-bounty", characterId: session.characterId }); break; case MessageType.raiseBounty: requirePlaying(session); simulation.enqueue(session.id, { type: "raise-bounty", characterId: session.characterId, firstName: message.firstName, lastName: message.lastName, amountCopper: message.amountCopper }); break; case MessageType.getCharacterBounty: requirePlaying(session); simulation.enqueue(session.id, { type: "get-character-bounty", characterId: session.characterId, targetCharacterId: message.characterId, firstName: message.firstName, lastName: message.lastName }); break; case MessageType.closeBounty: requirePlaying(session); simulation.enqueue(session.id, { type: "close-bounty", characterId: session.characterId }); break; case MessageType.openBarber: requirePlaying(session); simulation.enqueue(session.id, { type: "open-barber", characterId: session.characterId }); break; case MessageType.setHair: requirePlaying(session); simulation.enqueue(session.id, { type: "set-hair", characterId: session.characterId, hair: message.hair ?? null }); break; case MessageType.closeBarber: requirePlaying(session); simulation.enqueue(session.id, { type: "close-barber", characterId: session.characterId }); break; case MessageType.openCauldron: case MessageType.openCauldron: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, {@@ -644,6 +712,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, }); }); } } break; break; case MessageType.setGraphicsSettings: { const next = normalizeGraphicsSettings({ viewDistance: message.viewDistance ?? session.viewDistance }); const changed = next.viewDistance !== session.viewDistance; session.viewDistance = next.viewDistance; if (changed && session.entityId) { syncSubscriptions(session, true); } } break; default: default: send(session, { type: MessageType.error, message: `Unknown message ${message.type}` }); send(session, { type: MessageType.error, message: `Unknown message ${message.type}` }); } }@@ -682,6 +761,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, firstName: spawned.firstName, firstName: spawned.firstName, lastName: spawned.lastName, lastName: spawned.lastName, layers: spawned.layers ?? [], layers: spawned.layers ?? [], health: spawned.health, maxHealth: spawned.maxHealth, settings: simulation.settings, settings: simulation.settings, worldTime: simulation.worldTime() worldTime: simulation.worldTime() }); });@@ -735,8 +816,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, const centerChunkX = tileToChunk(position.tileX); const centerChunkX = tileToChunk(position.tileX); const centerChunkY = tileToChunk(position.tileY); const centerChunkY = tileToChunk(position.tileY); const mapRadius = staticChunkRadiusForViewDistance( session.viewDistance, STATIC_CHUNK_RADIUS, VISIBLE_CHUNK_RADIUS ); const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS); const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS); const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS); const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius); const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY))); const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY))); const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY))); const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));@@ -749,7 +835,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, } } } } const snapshots = simulation.snapshotsForView(session.entityId); const snapshots = simulation.snapshotsForView(session.entityId, mapRadius); for (const snapshot of snapshots) for (const snapshot of snapshots) { { const key = chunkKey(snapshot.chunkX, snapshot.chunkY); const key = chunkKey(snapshot.chunkX, snapshot.chunkY);@@ -895,6 +981,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, }); }); continue; continue; } } if (event.type === "status-effects") { const session = event.sessionId != null ? sessions.get(event.sessionId) : [...sessions.values()].find((entry) => entry.characterId === event.characterId); if (!session) { continue; } send(session, { type: MessageType.statusEffects, effects: event.effects ?? [], blind: !!event.blind }); continue; } if (event.type === "toast") if (event.type === "toast") { { const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId); const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);@@ -1027,6 +1127,62 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, { send(session, { type: MessageType.marketClosed }); } { send(session, { type: MessageType.marketClosed }); } continue; continue; } } if (event.type === "bounty-snapshot") { const session = sessions.get(event.sessionId); if (session) { send(session, { type: MessageType.bountySnapshot, myAmountCopper: event.myAmountCopper | 0, myAmountLabel: event.myAmountLabel ?? "", message: event.message ?? "", raised: event.raised ?? null }); } continue; } if (event.type === "bounty-closed") { const session = sessions.get(event.sessionId); if (session) { send(session, { type: MessageType.closeBounty }); } continue; } if (event.type === "character-bounty") { const session = sessions.get(event.sessionId); if (session) { send(session, { type: MessageType.characterBounty, target: event.target ?? null }); } continue; } if (event.type === "barber-snapshot") { const session = sessions.get(event.sessionId); if (session) { send(session, { type: MessageType.barberSnapshot, sex: event.sex, styles: event.styles ?? [], hair: event.hair ?? null, message: event.message ?? "" }); } continue; } if (event.type === "barber-closed") { const session = sessions.get(event.sessionId); if (session) { send(session, { type: MessageType.closeBarber }); } continue; } if (event.type === "market-trade") if (event.type === "market-trade") { { for (const session of sessions.values()) for (const session of sessions.values())@@ -1085,7 +1241,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, } } continue; continue; } } 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") 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") { publishEntity(event); } { publishEntity(event); } } } if (simulation.tickIndex % simulation.settings.simulationTickHz === 0) if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -1177,6 +1333,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, }); }); continue; continue; } } if (event.type === "entity-health") { if (!seesTo && !seesFrom) { continue; } send(session, { type: MessageType.entityHealth, entityId: event.entityId, health: event.health, maxHealth: event.maxHealth }); continue; } if (event.type === "gather-swing" || event.type === "tile-shove") if (event.type === "gather-swing" || event.type === "tile-shove") { { if (!seesTo && !seesFrom) if (!seesTo && !seesFrom)@@ -13,6 +13,7 @@ import {
resolveMiningPickaxe,
resolveWoodcuttingAxe,
resolvePlantClippers,
resolveHerbGather,
woodcuttingDurationMs,
woodcuttingXpForWood,
treeExhaustDurationMs,
@@ -27,8 +28,10 @@ import {
flowerItemInstance,
flowerColorIdFromBlockState,
flowerBlockState,
flowerColorIdForTile,
randomFlowerColorId
} from "../../../shared/definitions/dyes.js";
import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
import { insertStack } from "../../../shared/items/inventory.js";
import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -304,7 +307,7 @@ export function stepPlantRespawns (world, now)
{ continue; }
const state = entry.typeId === BlockType.flower
? flowerBlockState(randomFlowerColorId())
: (entry.state ?? "cotton-plant");
: (entry.state ?? defaultPlantState(entry.typeId));
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
if (delta)
{ events.push(delta); }
@@ -466,8 +469,19 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
if (!clippers.ok)
{ throw userError(clippers.reason); }
let herbId = null;
let herbTier = null;
if (plant.kind === "herb")
{
const gate = resolveHerbGather({ herbId: block.state, skills });
if (!gate.ok)
{ throw userError(gate.reason); }
herbId = gate.herb.herbId;
herbTier = gate.herb.tier;
}
const toolTier = clippers.tool?.tier ?? null;
const durationMs = herbalismDurationMs(plant.kind, toolTier);
const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier);
const toolItemId = clippers.tool?.stack?.itemId ?? null;
const prefixEvents = [];
let flowerColorId = null;
@@ -477,7 +491,7 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
if (!flowerColorId)
{
// Legacy / uncoloured placements: lock a colour before the pick starts.
flowerColorId = randomFlowerColorId();
flowerColorId = flowerColorIdForTile(tileX, tileY);
const delta = setBlockState(
world,
tileX,
@@ -492,6 +506,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
const started = beginGatherSwing(world, handle, entityId, position, {
kind: "plant",
plantKind: plant.kind,
herbId,
herbTier,
tileX,
tileY,
typeId: block.typeId,
@@ -690,6 +706,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
{
itemId = rawClothItemId(ClothTier.cotton);
}
else if (gather.plantKind === "herb")
{
const herb = herbDefinition(gather.herbId);
itemId = herb?.itemId ?? null;
}
else
{
clearGather(world.ecs, handle);
@@ -728,7 +749,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv
const levelUps = [];
if (skills?.xp)
{
const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier));
if (result.changed)
{ skillsChanged = true; }
if (result.levelUp)
@@ -743,7 +764,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
tileY: gather.tileY,
typeId: gather.typeId,
// Colour is chosen when the node refreshes (see stepPlantRespawns).
state: gather.plantKind === "flower" ? null : "cotton-plant",
state: gather.plantKind === "flower"
? null
: (gather.plantKind === "herb" && isHerbId(gather.herbId)
? gather.herbId
: defaultPlantState(gather.typeId)),
respawnsAt: now + PLANT_EXHAUST_MS
});
@@ -863,3 +888,10 @@ export function handleGatherCommand (world, sessionId, command, now)
return null;
}
}
function defaultPlantState (typeId)
{
if (typeId === BlockType.herbPlant)
{ return "mint"; }
return "cotton-plant";
}
@@ -13,6 +13,7 @@ import { resolveMiningPickaxe, resolveMiningPickaxe, resolveWoodcuttingAxe, resolveWoodcuttingAxe, resolvePlantClippers, resolvePlantClippers, resolveHerbGather, woodcuttingDurationMs, woodcuttingDurationMs, woodcuttingXpForWood, woodcuttingXpForWood, treeExhaustDurationMs, treeExhaustDurationMs,@@ -27,8 +28,10 @@ import { flowerItemInstance, flowerItemInstance, flowerColorIdFromBlockState, flowerColorIdFromBlockState, flowerBlockState, flowerBlockState, flowerColorIdForTile, randomFlowerColorId randomFlowerColorId} from "../../../shared/definitions/dyes.js";} from "../../../shared/definitions/dyes.js";import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";import { insertStack } from "../../../shared/items/inventory.js";import { insertStack } from "../../../shared/items/inventory.js";import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";@@ -304,7 +307,7 @@ export function stepPlantRespawns (world, now) { continue; } { continue; } const state = entry.typeId === BlockType.flower const state = entry.typeId === BlockType.flower ? flowerBlockState(randomFlowerColorId()) ? flowerBlockState(randomFlowerColorId()) : (entry.state ?? "cotton-plant"); : (entry.state ?? defaultPlantState(entry.typeId)); const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state); const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state); if (delta) if (delta) { events.push(delta); } { events.push(delta); }@@ -466,8 +469,19 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now) if (!clippers.ok) if (!clippers.ok) { throw userError(clippers.reason); } { throw userError(clippers.reason); } let herbId = null; let herbTier = null; if (plant.kind === "herb") { const gate = resolveHerbGather({ herbId: block.state, skills }); if (!gate.ok) { throw userError(gate.reason); } herbId = gate.herb.herbId; herbTier = gate.herb.tier; } const toolTier = clippers.tool?.tier ?? null; const toolTier = clippers.tool?.tier ?? null; const durationMs = herbalismDurationMs(plant.kind, toolTier); const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier); const toolItemId = clippers.tool?.stack?.itemId ?? null; const toolItemId = clippers.tool?.stack?.itemId ?? null; const prefixEvents = []; const prefixEvents = []; let flowerColorId = null; let flowerColorId = null;@@ -477,7 +491,7 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now) if (!flowerColorId) if (!flowerColorId) { { // Legacy / uncoloured placements: lock a colour before the pick starts. // Legacy / uncoloured placements: lock a colour before the pick starts. flowerColorId = randomFlowerColorId(); flowerColorId = flowerColorIdForTile(tileX, tileY); const delta = setBlockState( const delta = setBlockState( world, world, tileX, tileX,@@ -492,6 +506,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now) const started = beginGatherSwing(world, handle, entityId, position, { const started = beginGatherSwing(world, handle, entityId, position, { kind: "plant", kind: "plant", plantKind: plant.kind, plantKind: plant.kind, herbId, herbTier, tileX, tileX, tileY, tileY, typeId: block.typeId, typeId: block.typeId,@@ -690,6 +706,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv { { itemId = rawClothItemId(ClothTier.cotton); itemId = rawClothItemId(ClothTier.cotton); } } else if (gather.plantKind === "herb") { const herb = herbDefinition(gather.herbId); itemId = herb?.itemId ?? null; } else else { { clearGather(world.ecs, handle); clearGather(world.ecs, handle);@@ -728,7 +749,7 @@ function completePlant (world, handle, entityId, character, gather, events, priv const levelUps = []; const levelUps = []; if (skills?.xp) if (skills?.xp) { { const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind)); const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier)); if (result.changed) if (result.changed) { skillsChanged = true; } { skillsChanged = true; } if (result.levelUp) if (result.levelUp)@@ -743,7 +764,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv tileY: gather.tileY, tileY: gather.tileY, typeId: gather.typeId, typeId: gather.typeId, // Colour is chosen when the node refreshes (see stepPlantRespawns). // Colour is chosen when the node refreshes (see stepPlantRespawns). state: gather.plantKind === "flower" ? null : "cotton-plant", state: gather.plantKind === "flower" ? null : (gather.plantKind === "herb" && isHerbId(gather.herbId) ? gather.herbId : defaultPlantState(gather.typeId)), respawnsAt: now + PLANT_EXHAUST_MS respawnsAt: now + PLANT_EXHAUST_MS }); });@@ -863,3 +888,10 @@ export function handleGatherCommand (world, sessionId, command, now) return null; return null; } }}}function defaultPlantState (typeId){ if (typeId === BlockType.herbPlant) { return "mint"; } return "cotton-plant";}@@ -24,6 +24,11 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { randomUUID } from "node:crypto";
import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
import {
applyStatusEffect,
emptyStatusEffects,
StatusEffectType
} from "../../../shared/statusEffects/rules.js";
export function publicGroundItem (item)
{
@@ -350,7 +355,11 @@ function eatItem (world, sessionId, command)
{ throw userError("That inventory slot is empty."); }
inventory.slots = taken.slots;
health.current = Math.min(health.max | 0, (health.current | 0) + healing);
return { events: [], private: bagView(world.ecs, handle) };
return {
events: [],
private: bagView(world.ecs, handle),
healthChanged: true
};
}
function drinkItem (world, sessionId, command)
@@ -378,27 +387,74 @@ function drinkItem (world, sessionId, command)
throw userError("That inventory slot is empty.");
}
inventory.slots = consumed.slots;
applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
return { events: [], private: bagView(world.ecs, handle) };
const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
return {
events: effectResult.events ?? [],
private: bagView(world.ecs, handle),
healthChanged: !!effectResult.healthChanged,
appearanceChanged: !!effectResult.appearanceChanged,
statusEffectsChanged: !!effectResult.statusEffectsChanged
};
}
function ensureStatusEffects (ecs, handle)
{
let component = ecs.get(handle, Component.statusEffects);
if (!component)
{ component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); }
if (!Array.isArray(component.effects))
{ component.effects = []; }
return component;
}
function applyPotionEffect (ecs, handle, effect)
{
const result = {
healthChanged: false,
appearanceChanged: false,
statusEffectsChanged: false,
events: []
};
if (!effect || typeof effect !== "object")
{ return; }
{ return result; }
const health = ecs.get(handle, Component.health);
if (effect.type === "heal" && health)
const type = effect.type;
if (type === "heal" && health)
{
const amount = Math.max(0, effect.amount | 0 || 0);
health.current = Math.min(health.max | 0, (health.current | 0) + amount);
return;
result.healthChanged = true;
return result;
}
if (effect.type === "damage" && health)
if (type === "damage" && health)
{
const amount = Math.max(0, effect.amount | 0 || 0);
health.current = Math.max(0, (health.current | 0) - amount);
result.healthChanged = true;
return result;
}
// slow / blind / queasy: stub until status-effect systems exist
const timed = {
[StatusEffectType.healthRegen]: true,
[StatusEffectType.staminaRegen]: true,
[StatusEffectType.strengthBonus]: true,
[StatusEffectType.mindBonus]: true,
[StatusEffectType.staminaDrain]: true,
[StatusEffectType.glow]: true,
[StatusEffectType.shrink]: true,
[StatusEffectType.blind]: true
};
if (!timed[type])
{ return result; }
const component = ensureStatusEffects(ecs, handle);
applyStatusEffect(component, effect, Date.now());
result.statusEffectsChanged = true;
if (type === StatusEffectType.glow || type === StatusEffectType.shrink)
{ result.appearanceChanged = true; }
return result;
}
function openBank (world, sessionId, command)
@@ -24,6 +24,11 @@ import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { randomUUID } from "node:crypto";import { randomUUID } from "node:crypto";import { tileShoveTowardBlock } from "../simulation/tileInteract.js";import { tileShoveTowardBlock } from "../simulation/tileInteract.js";import { applyStatusEffect, emptyStatusEffects, StatusEffectType} from "../../../shared/statusEffects/rules.js";export function publicGroundItem (item)export function publicGroundItem (item){{@@ -350,7 +355,11 @@ function eatItem (world, sessionId, command) { throw userError("That inventory slot is empty."); } { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; inventory.slots = taken.slots; health.current = Math.min(health.max | 0, (health.current | 0) + healing); health.current = Math.min(health.max | 0, (health.current | 0) + healing); return { events: [], private: bagView(world.ecs, handle) }; return { events: [], private: bagView(world.ecs, handle), healthChanged: true };}}function drinkItem (world, sessionId, command)function drinkItem (world, sessionId, command)@@ -378,27 +387,74 @@ function drinkItem (world, sessionId, command) throw userError("That inventory slot is empty."); throw userError("That inventory slot is empty."); } } inventory.slots = consumed.slots; inventory.slots = consumed.slots; applyPotionEffect(world.ecs, handle, consumed.instance?.effect); const effectResult = applyPotionEffect(world.ecs, handle, consumed.instance?.effect); return { events: [], private: bagView(world.ecs, handle) }; return { events: effectResult.events ?? [], private: bagView(world.ecs, handle), healthChanged: !!effectResult.healthChanged, appearanceChanged: !!effectResult.appearanceChanged, statusEffectsChanged: !!effectResult.statusEffectsChanged };}function ensureStatusEffects (ecs, handle){ let component = ecs.get(handle, Component.statusEffects); if (!component) { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } if (!Array.isArray(component.effects)) { component.effects = []; } return component;}}function applyPotionEffect (ecs, handle, effect)function applyPotionEffect (ecs, handle, effect){{ const result = { healthChanged: false, appearanceChanged: false, statusEffectsChanged: false, events: [] }; if (!effect || typeof effect !== "object") if (!effect || typeof effect !== "object") { return; } { return result; } const health = ecs.get(handle, Component.health); const health = ecs.get(handle, Component.health); if (effect.type === "heal" && health) const type = effect.type; if (type === "heal" && health) { { const amount = Math.max(0, effect.amount | 0 || 0); const amount = Math.max(0, effect.amount | 0 || 0); health.current = Math.min(health.max | 0, (health.current | 0) + amount); health.current = Math.min(health.max | 0, (health.current | 0) + amount); return; result.healthChanged = true; return result; } } if (effect.type === "damage" && health) if (type === "damage" && health) { { const amount = Math.max(0, effect.amount | 0 || 0); const amount = Math.max(0, effect.amount | 0 || 0); health.current = Math.max(0, (health.current | 0) - amount); health.current = Math.max(0, (health.current | 0) - amount); result.healthChanged = true; return result; } } // slow / blind / queasy: stub until status-effect systems exist const timed = { [StatusEffectType.healthRegen]: true, [StatusEffectType.staminaRegen]: true, [StatusEffectType.strengthBonus]: true, [StatusEffectType.mindBonus]: true, [StatusEffectType.staminaDrain]: true, [StatusEffectType.glow]: true, [StatusEffectType.shrink]: true, [StatusEffectType.blind]: true }; if (!timed[type]) { return result; } const component = ensureStatusEffects(ecs, handle); applyStatusEffect(component, effect, Date.now()); result.statusEffectsChanged = true; if (type === StatusEffectType.glow || type === StatusEffectType.shrink) { result.appearanceChanged = true; } return result;}}function openBank (world, sessionId, command)function openBank (world, sessionId, command)@@ -70,7 +70,7 @@ export class MarketService
const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
if (!row)
{ continue; }
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
for (let localY = 0; localY < CHUNK_SIZE; localY++)
{
for (let localX = 0; localX < CHUNK_SIZE; localX++)
@@ -70,7 +70,7 @@ export class MarketService const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId); if (!row) if (!row) { continue; } { continue; } const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId); const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y); for (let localY = 0; localY < CHUNK_SIZE; localY++) for (let localY = 0; localY < CHUNK_SIZE; localY++) { { for (let localX = 0; localX < CHUNK_SIZE; localX++) for (let localX = 0; localX < CHUNK_SIZE; localX++)@@ -1,6 +1,7 @@
import { openDatabase } from "./database.js";
import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
const STATE_SCHEMA = `
@@ -28,7 +29,11 @@ CREATE TABLE IF NOT EXISTS characters (
tile_y INTEGER NOT NULL DEFAULT 8,
gait TEXT NOT NULL DEFAULT 'walk',
is_dead INTEGER NOT NULL DEFAULT 0,
deletion_scheduled_at INTEGER
deletion_scheduled_at INTEGER,
hair_style TEXT,
hair_hue REAL NOT NULL DEFAULT 30,
hair_saturation REAL NOT NULL DEFAULT 0.55,
hair_darkness REAL NOT NULL DEFAULT 0.45
);
CREATE TABLE IF NOT EXISTS friend_requests (
request_id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -150,6 +155,11 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries (
cargo_blob TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS character_bounties (
character_id INTEGER PRIMARY KEY,
amount INTEGER NOT NULL DEFAULT 0
);
`;
export class StateDatabase
@@ -171,6 +181,13 @@ export class StateDatabase
const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
if (!characterColumns.some((column) => column.name === "is_dead"))
{ this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
if (!characterColumns.some((column) => column.name === "hair_style"))
{
this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT");
this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30");
this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
}
const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
if (!courierColumns.some((column) => column.name === "vault_character_id"))
{ this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
@@ -253,18 +270,36 @@ export class StateDatabase
return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
}
createCharacter (accountId, firstName, lastName, sex, tileX, tileY)
createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null)
{
const firstNormalized = normalizeName(firstName);
const lastNormalized = normalizeName(lastName);
const hairStyle = hair?.style ?? null;
const hairHue = Number(hair?.hue) || 30;
const hairSaturation = Number(hair?.saturation);
const hairDarkness = Number(hair?.darkness);
this.db.exec("BEGIN");
try
{
this.db.prepare(`
INSERT INTO characters (
account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY);
account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
hair_style, hair_hue, hair_saturation, hair_darkness
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
accountId,
firstName,
lastName,
firstNormalized,
lastNormalized,
sex,
tileX,
tileY,
hairStyle,
hairHue,
Number.isFinite(hairSaturation) ? hairSaturation : 0.55,
Number.isFinite(hairDarkness) ? hairDarkness : 0.45
);
const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id);
const claim = this.findSurnameClaim(lastNormalized);
@@ -277,7 +312,7 @@ export class StateDatabase
}
this.db.exec("COMMIT");
this.#ensureBag(characterId);
this.#ensureBag(characterId, starterSettings);
return this.getCharacter(characterId);
}
catch (error)
@@ -287,6 +322,22 @@ export class StateDatabase
}
}
updateCharacterHair (characterId, { style, hue, saturation, darkness })
{
this.db.prepare(`
UPDATE characters
SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ?
WHERE character_id = ?
`).run(
style ?? null,
Number(hue) || 30,
Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55,
Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45,
characterId | 0
);
return this.getCharacter(characterId);
}
scheduleDeletion (characterId, at)
{
this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);
@@ -371,6 +422,42 @@ export class StateDatabase
`).get(normalizeName(firstName), normalizeName(lastName)) ?? null;
}
getCharacterBounty (characterId)
{
const row = this.db.prepare(`
SELECT amount FROM character_bounties WHERE character_id = ?
`).get(characterId | 0);
return Math.max(0, row?.amount | 0);
}
/** Add coins to a bounty; returns the new total. */
addCharacterBounty (characterId, amount)
{
const id = characterId | 0;
const add = Math.max(0, amount | 0);
if (add <= 0)
{ return this.getCharacterBounty(id); }
this.db.prepare(`
INSERT INTO character_bounties (character_id, amount) VALUES (?, ?)
ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount
`).run(id, add);
return this.getCharacterBounty(id);
}
/** Zero out and return the previous bounty amount. */
takeCharacterBounty (characterId)
{
const id = characterId | 0;
const amount = this.getCharacterBounty(id);
if (amount <= 0)
{ return 0; }
this.db.prepare(`
INSERT INTO character_bounties (character_id, amount) VALUES (?, 0)
ON CONFLICT(character_id) DO UPDATE SET amount = 0
`).run(id);
return amount;
}
listFriendRecords (characterId)
{
return this.db.prepare(`
@@ -492,28 +579,20 @@ export class StateDatabase
}
}
#ensureBag (characterId)
#ensureBag (characterId, starterSettings = null)
{
const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
if (existing)
{ return parseBag(existing, characterId); }
const slots = emptySlots();
for (const starter of STARTER_ITEMS)
{
const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId));
if (result.ok)
{ slots.splice(0, slots.length, ...result.slots); }
}
const equipment = emptyEquipment();
equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 };
const contents = buildStarterBagContents(starterSettings);
this.db.prepare(`
INSERT INTO character_bags (
character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
) VALUES (?, ?, ?, 0, ?, 0, ?)
`).run(
characterId,
JSON.stringify(slots),
JSON.stringify(equipment),
JSON.stringify(contents.slots),
JSON.stringify(contents.equipment),
JSON.stringify({ slots: [], reserved: [] }),
JSON.stringify(storedSkillXp(defaultPlayerSkills()))
);
@@ -1,6 +1,7 @@import { openDatabase } from "./database.js";import { openDatabase } from "./database.js";import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";import { STARTER_ITEMS, ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";import { buildStarterBagContents } from "../../../shared/items/starterLoadout.js";import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";const STATE_SCHEMA = `const STATE_SCHEMA = `@@ -28,7 +29,11 @@ CREATE TABLE IF NOT EXISTS characters ( tile_y INTEGER NOT NULL DEFAULT 8, tile_y INTEGER NOT NULL DEFAULT 8, gait TEXT NOT NULL DEFAULT 'walk', gait TEXT NOT NULL DEFAULT 'walk', is_dead INTEGER NOT NULL DEFAULT 0, is_dead INTEGER NOT NULL DEFAULT 0, deletion_scheduled_at INTEGER deletion_scheduled_at INTEGER, hair_style TEXT, hair_hue REAL NOT NULL DEFAULT 30, hair_saturation REAL NOT NULL DEFAULT 0.55, hair_darkness REAL NOT NULL DEFAULT 0.45););CREATE TABLE IF NOT EXISTS friend_requests (CREATE TABLE IF NOT EXISTS friend_requests ( request_id INTEGER PRIMARY KEY AUTOINCREMENT, request_id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -150,6 +155,11 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries ( cargo_blob TEXT NOT NULL, cargo_blob TEXT NOT NULL, created_at INTEGER NOT NULL created_at INTEGER NOT NULL););CREATE TABLE IF NOT EXISTS character_bounties ( character_id INTEGER PRIMARY KEY, amount INTEGER NOT NULL DEFAULT 0);`;`;export class StateDatabaseexport class StateDatabase@@ -171,6 +181,13 @@ export class StateDatabase const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all(); const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all(); if (!characterColumns.some((column) => column.name === "is_dead")) if (!characterColumns.some((column) => column.name === "is_dead")) { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); } { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); } if (!characterColumns.some((column) => column.name === "hair_style")) { this.db.exec("ALTER TABLE characters ADD COLUMN hair_style TEXT"); this.db.exec("ALTER TABLE characters ADD COLUMN hair_hue REAL NOT NULL DEFAULT 30"); this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55"); this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45"); } const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all(); const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all(); if (!courierColumns.some((column) => column.name === "vault_character_id")) if (!courierColumns.some((column) => column.name === "vault_character_id")) { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); } { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }@@ -253,18 +270,36 @@ export class StateDatabase return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null; return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null; } } createCharacter (accountId, firstName, lastName, sex, tileX, tileY) createCharacter (accountId, firstName, lastName, sex, tileX, tileY, hair = null, starterSettings = null) { { const firstNormalized = normalizeName(firstName); const firstNormalized = normalizeName(firstName); const lastNormalized = normalizeName(lastName); const lastNormalized = normalizeName(lastName); const hairStyle = hair?.style ?? null; const hairHue = Number(hair?.hue) || 30; const hairSaturation = Number(hair?.saturation); const hairDarkness = Number(hair?.darkness); this.db.exec("BEGIN"); this.db.exec("BEGIN"); try try { { this.db.prepare(` this.db.prepare(` INSERT INTO characters ( INSERT INTO characters ( account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y, ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) hair_style, hair_hue, hair_saturation, hair_darkness `).run(accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY); ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run( accountId, firstName, lastName, firstNormalized, lastNormalized, sex, tileX, tileY, hairStyle, hairHue, Number.isFinite(hairSaturation) ? hairSaturation : 0.55, Number.isFinite(hairDarkness) ? hairDarkness : 0.45 ); const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id); const characterId = Number(this.db.prepare("SELECT last_insert_rowid() AS id").get().id); const claim = this.findSurnameClaim(lastNormalized); const claim = this.findSurnameClaim(lastNormalized);@@ -277,7 +312,7 @@ export class StateDatabase } } this.db.exec("COMMIT"); this.db.exec("COMMIT"); this.#ensureBag(characterId); this.#ensureBag(characterId, starterSettings); return this.getCharacter(characterId); return this.getCharacter(characterId); } } catch (error) catch (error)@@ -287,6 +322,22 @@ export class StateDatabase } } } } updateCharacterHair (characterId, { style, hue, saturation, darkness }) { this.db.prepare(` UPDATE characters SET hair_style = ?, hair_hue = ?, hair_saturation = ?, hair_darkness = ? WHERE character_id = ? `).run( style ?? null, Number(hue) || 30, Number.isFinite(Number(saturation)) ? Number(saturation) : 0.55, Number.isFinite(Number(darkness)) ? Number(darkness) : 0.45, characterId | 0 ); return this.getCharacter(characterId); } scheduleDeletion (characterId, at) scheduleDeletion (characterId, at) { { this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId); this.db.prepare("UPDATE characters SET deletion_scheduled_at = ? WHERE character_id = ?").run(at, characterId);@@ -371,6 +422,42 @@ export class StateDatabase `).get(normalizeName(firstName), normalizeName(lastName)) ?? null; `).get(normalizeName(firstName), normalizeName(lastName)) ?? null; } } getCharacterBounty (characterId) { const row = this.db.prepare(` SELECT amount FROM character_bounties WHERE character_id = ? `).get(characterId | 0); return Math.max(0, row?.amount | 0); } /** Add coins to a bounty; returns the new total. */ addCharacterBounty (characterId, amount) { const id = characterId | 0; const add = Math.max(0, amount | 0); if (add <= 0) { return this.getCharacterBounty(id); } this.db.prepare(` INSERT INTO character_bounties (character_id, amount) VALUES (?, ?) ON CONFLICT(character_id) DO UPDATE SET amount = amount + excluded.amount `).run(id, add); return this.getCharacterBounty(id); } /** Zero out and return the previous bounty amount. */ takeCharacterBounty (characterId) { const id = characterId | 0; const amount = this.getCharacterBounty(id); if (amount <= 0) { return 0; } this.db.prepare(` INSERT INTO character_bounties (character_id, amount) VALUES (?, 0) ON CONFLICT(character_id) DO UPDATE SET amount = 0 `).run(id); return amount; } listFriendRecords (characterId) listFriendRecords (characterId) { { return this.db.prepare(` return this.db.prepare(`@@ -492,28 +579,20 @@ export class StateDatabase } } } } #ensureBag (characterId) #ensureBag (characterId, starterSettings = null) { { const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId); const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId); if (existing) if (existing) { return parseBag(existing, characterId); } { return parseBag(existing, characterId); } const slots = emptySlots(); const contents = buildStarterBagContents(starterSettings); for (const starter of STARTER_ITEMS) { const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId)); if (result.ok) { slots.splice(0, slots.length, ...result.slots); } } const equipment = emptyEquipment(); equipment.slots.offhand = { itemId: ItemId.lantern, quantity: 1 }; this.db.prepare(` this.db.prepare(` INSERT INTO character_bags ( INSERT INTO character_bags ( character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob ) VALUES (?, ?, ?, 0, ?, 0, ?) ) VALUES (?, ?, ?, 0, ?, 0, ?) `).run( `).run( characterId, characterId, JSON.stringify(slots), JSON.stringify(contents.slots), JSON.stringify(equipment), JSON.stringify(contents.equipment), JSON.stringify({ slots: [], reserved: [] }), JSON.stringify({ slots: [], reserved: [] }), JSON.stringify(storedSkillXp(defaultPlayerSkills())) JSON.stringify(storedSkillXp(defaultPlayerSkills())) ); );@@ -1,4 +1,5 @@
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
import { openDatabase, withTransaction } from "./database.js";
const WORLD_SCHEMA = `
@@ -100,9 +101,13 @@ export class WorldDatabase
{
this.#ensureLiveSettings();
const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
return row
const merged = row
? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
: { ...DEFAULT_WORLD_SETTINGS };
const loadout = normalizeStarterLoadout(merged);
merged.starterEquipment = loadout.equipment;
merged.starterInventory = loadout.inventory;
return merged;
}
saveLiveSettings (settings, updatedBy)
@@ -1,4 +1,5 @@import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";import { openDatabase, withTransaction } from "./database.js";import { openDatabase, withTransaction } from "./database.js";const WORLD_SCHEMA = `const WORLD_SCHEMA = `@@ -100,9 +101,13 @@ export class WorldDatabase { { this.#ensureLiveSettings(); this.#ensureLiveSettings(); const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get(); const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get(); return row const merged = row ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) } ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) } : { ...DEFAULT_WORLD_SETTINGS }; : { ...DEFAULT_WORLD_SETTINGS }; const loadout = normalizeStarterLoadout(merged); merged.starterEquipment = loadout.equipment; merged.starterInventory = loadout.inventory; return merged; } } saveLiveSettings (settings, updatedBy) saveLiveSettings (settings, updatedBy)@@ -36,5 +36,6 @@ export const WorkerMessage = Object.freeze({
clearCombat: "clearCombat",
setItemLastSales: "setItemLastSales",
stationExchangeClerk: "stationExchangeClerk",
releaseExchangeClerk: "releaseExchangeClerk"
releaseExchangeClerk: "releaseExchangeClerk",
applyAppearance: "applyAppearance"
});
@@ -36,5 +36,6 @@ export const WorkerMessage = Object.freeze({ clearCombat: "clearCombat", clearCombat: "clearCombat", setItemLastSales: "setItemLastSales", setItemLastSales: "setItemLastSales", stationExchangeClerk: "stationExchangeClerk", stationExchangeClerk: "stationExchangeClerk", releaseExchangeClerk: "releaseExchangeClerk" releaseExchangeClerk: "releaseExchangeClerk", applyAppearance: "applyAppearance"});});@@ -37,7 +37,11 @@ import { ItemId } from "../../../shared/definitions/items.js";
import { seasonIdAt } from "../../../shared/world/season.js";
import { CourierService } from "../courier/service.js";
import { MarketService } from "../market/service.js";
import { BountyService } from "../bounty/service.js";
import { BarberService } from "../barber/service.js";
import { findReservedChequeIndex } from "../items/bags.js";
import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
export class Simulation
{
@@ -99,6 +103,8 @@ export class Simulation
worldDb: this.worldDb,
simulation: this
});
this.bounty = new BountyService(this.stateDb, this, this.courier);
this.barber = new BarberService(this.stateDb, this);
this.#refreshAltarIndex();
}
@@ -149,6 +155,7 @@ export class Simulation
}
this.#syncAllReplicas();
this.courier?.refreshBankIndex();
this.courier?.refreshBountyOfficeIndex();
this.market?.refreshIndex();
this.#refreshAltarIndex();
}
@@ -346,7 +353,8 @@ export class Simulation
appearance: {
sex: character.sex ?? row.sex,
firstName: character.first_name ?? row.first_name,
lastName: character.last_name ?? row.last_name
lastName: character.last_name ?? row.last_name,
...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character))
},
character: {
characterId: character.character_id ?? row.character_id,
@@ -507,6 +515,38 @@ export class Simulation
});
}
/**
* Persist hair + patch live appearance; returns public view.
*/
setCharacterHair (characterId, hair)
{
const row = this.stateDb.updateCharacterHair(characterId, hair);
const entityId = this.characterEntities.get(characterId);
if (!entityId)
{ return { row, view: null }; }
const fields = appearanceHairFields({
sex: row.sex,
style: hair.style,
hue: hair.hue,
saturation: hair.saturation,
darkness: hair.darkness
});
const record = this.directory.get(entityId);
if (!record)
{ return { row, view: null }; }
const view = this.workers[record.workerId].call({
type: WorkerMessage.applyAppearance,
entityId,
appearance: fields
});
if (view)
{
this.#remember(view, record.workerId);
this.#queueReplication(replicationAppearance(view));
}
return { row, view };
}
pushSkills (characterId, skills)
{
this.pendingPrivate.push({
@@ -688,19 +728,20 @@ export class Simulation
return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
}
/** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */
snapshotsForView (entityId)
/** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS)
{
const record = this.directory.get(entityId);
if (!record)
{ return []; }
const centerChunkX = tileToChunk(record.tileX);
const centerChunkY = tileToChunk(record.tileY);
const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
const entityKeys = new Set(
visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
.map((coord) => chunkKey(coord.chunkX, coord.chunkY))
);
return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS)
return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
.map((coord) =>
{
const key = chunkKey(coord.chunkX, coord.chunkY);
@@ -853,6 +894,25 @@ export class Simulation
const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now);
return result?.events ?? [];
}
if (
item.command.type === "open-bounty"
|| item.command.type === "raise-bounty"
|| item.command.type === "get-character-bounty"
|| item.command.type === "close-bounty"
)
{
const result = this.bounty.handleCommand(item.sessionId, item.command);
return result?.events ?? [];
}
if (
item.command.type === "open-barber"
|| item.command.type === "set-hair"
|| item.command.type === "close-barber"
)
{
const result = this.barber.handleCommand(item.sessionId, item.command);
return result?.events ?? [];
}
const entityId = this.characterEntities.get(item.command.characterId);
const record = entityId ? this.directory.get(entityId) : null;
if (!record)
@@ -927,6 +987,28 @@ export class Simulation
...result.private
});
}
if (result?.statusEffectsChanged && view)
{
events.push({
type: "status-effects",
sessionId: item.sessionId,
characterId: view.characterId ?? item.command.characterId,
effects: view.statusEffects ?? [],
blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind")
});
}
if (result?.healthChanged && view)
{
events.push({
type: "entity-health",
entityId: view.entityId,
characterId: view.characterId ?? item.command.characterId,
health: view.health,
maxHealth: view.maxHealth,
tileX: view.tileX,
tileY: view.tileY
});
}
return events;
}
@@ -997,6 +1079,12 @@ export class Simulation
event.tileY,
record.gait ?? GAIT.walk
);
this.bounty?.settleKill(
event.characterId,
event.attackerId,
event.tileX,
event.tileY
);
for (const worker of this.workers)
{
worker.call({
@@ -1558,7 +1646,7 @@ export class Simulation
{ return this.authoredCache.get(key); }
const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
const data = row
? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
: createEmptyChunkData(this.settings.defaultGroundTypeId);
this.authoredCache.set(key, data);
return data;
@@ -37,7 +37,11 @@ import { ItemId } from "../../../shared/definitions/items.js";import { seasonIdAt } from "../../../shared/world/season.js";import { seasonIdAt } from "../../../shared/world/season.js";import { CourierService } from "../courier/service.js";import { CourierService } from "../courier/service.js";import { MarketService } from "../market/service.js";import { MarketService } from "../market/service.js";import { BountyService } from "../bounty/service.js";import { BarberService } from "../barber/service.js";import { findReservedChequeIndex } from "../items/bags.js";import { findReservedChequeIndex } from "../items/bags.js";import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";export class Simulationexport class Simulation{{@@ -99,6 +103,8 @@ export class Simulation worldDb: this.worldDb, worldDb: this.worldDb, simulation: this simulation: this }); }); this.bounty = new BountyService(this.stateDb, this, this.courier); this.barber = new BarberService(this.stateDb, this); this.#refreshAltarIndex(); this.#refreshAltarIndex(); } }@@ -149,6 +155,7 @@ export class Simulation } } this.#syncAllReplicas(); this.#syncAllReplicas(); this.courier?.refreshBankIndex(); this.courier?.refreshBankIndex(); this.courier?.refreshBountyOfficeIndex(); this.market?.refreshIndex(); this.market?.refreshIndex(); this.#refreshAltarIndex(); this.#refreshAltarIndex(); } }@@ -346,7 +353,8 @@ export class Simulation appearance: { appearance: { sex: character.sex ?? row.sex, sex: character.sex ?? row.sex, firstName: character.first_name ?? row.first_name, firstName: character.first_name ?? row.first_name, lastName: character.last_name ?? row.last_name lastName: character.last_name ?? row.last_name, ...appearanceHairFields(hairFromCharacterRow(row) ?? hairFromCharacterRow(character)) }, }, character: { character: { characterId: character.character_id ?? row.character_id, characterId: character.character_id ?? row.character_id,@@ -507,6 +515,38 @@ export class Simulation }); }); } } /** * Persist hair + patch live appearance; returns public view. */ setCharacterHair (characterId, hair) { const row = this.stateDb.updateCharacterHair(characterId, hair); const entityId = this.characterEntities.get(characterId); if (!entityId) { return { row, view: null }; } const fields = appearanceHairFields({ sex: row.sex, style: hair.style, hue: hair.hue, saturation: hair.saturation, darkness: hair.darkness }); const record = this.directory.get(entityId); if (!record) { return { row, view: null }; } const view = this.workers[record.workerId].call({ type: WorkerMessage.applyAppearance, entityId, appearance: fields }); if (view) { this.#remember(view, record.workerId); this.#queueReplication(replicationAppearance(view)); } return { row, view }; } pushSkills (characterId, skills) pushSkills (characterId, skills) { { this.pendingPrivate.push({ this.pendingPrivate.push({@@ -688,19 +728,20 @@ export class Simulation return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false)); return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false)); } } /** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */ /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */ snapshotsForView (entityId) snapshotsForView (entityId, staticRadius = STATIC_CHUNK_RADIUS) { { const record = this.directory.get(entityId); const record = this.directory.get(entityId); if (!record) if (!record) { return []; } { return []; } const centerChunkX = tileToChunk(record.tileX); const centerChunkX = tileToChunk(record.tileX); const centerChunkY = tileToChunk(record.tileY); const centerChunkY = tileToChunk(record.tileY); const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0); const entityKeys = new Set( const entityKeys = new Set( visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS) visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS) .map((coord) => chunkKey(coord.chunkX, coord.chunkY)) .map((coord) => chunkKey(coord.chunkX, coord.chunkY)) ); ); return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS) return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius) .map((coord) => .map((coord) => { { const key = chunkKey(coord.chunkX, coord.chunkY); const key = chunkKey(coord.chunkX, coord.chunkY);@@ -853,6 +894,25 @@ export class Simulation const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); const result = this.market.handleCommand(item.sessionId, item.command, item.receivedAt ?? this.now); return result?.events ?? []; return result?.events ?? []; } } if ( item.command.type === "open-bounty" || item.command.type === "raise-bounty" || item.command.type === "get-character-bounty" || item.command.type === "close-bounty" ) { const result = this.bounty.handleCommand(item.sessionId, item.command); return result?.events ?? []; } if ( item.command.type === "open-barber" || item.command.type === "set-hair" || item.command.type === "close-barber" ) { const result = this.barber.handleCommand(item.sessionId, item.command); return result?.events ?? []; } const entityId = this.characterEntities.get(item.command.characterId); const entityId = this.characterEntities.get(item.command.characterId); const record = entityId ? this.directory.get(entityId) : null; const record = entityId ? this.directory.get(entityId) : null; if (!record) if (!record)@@ -927,6 +987,28 @@ export class Simulation ...result.private ...result.private }); }); } } if (result?.statusEffectsChanged && view) { events.push({ type: "status-effects", sessionId: item.sessionId, characterId: view.characterId ?? item.command.characterId, effects: view.statusEffects ?? [], blind: (view.statusEffects ?? []).some((entry) => entry.type === "blind") }); } if (result?.healthChanged && view) { events.push({ type: "entity-health", entityId: view.entityId, characterId: view.characterId ?? item.command.characterId, health: view.health, maxHealth: view.maxHealth, tileX: view.tileX, tileY: view.tileY }); } return events; return events; } }@@ -997,6 +1079,12 @@ export class Simulation event.tileY, event.tileY, record.gait ?? GAIT.walk record.gait ?? GAIT.walk ); ); this.bounty?.settleKill( event.characterId, event.attackerId, event.tileX, event.tileY ); for (const worker of this.workers) for (const worker of this.workers) { { worker.call({ worker.call({@@ -1558,7 +1646,7 @@ export class Simulation { return this.authoredCache.get(key); } { return this.authoredCache.get(key); } const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId); const data = row const data = row ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId) ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY) : createEmptyChunkData(this.settings.defaultGroundTypeId); : createEmptyChunkData(this.settings.defaultGroundTypeId); this.authoredCache.set(key, data); this.authoredCache.set(key, data); return data; return data;@@ -11,6 +11,7 @@ import {
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
import { emptyEquipment } from "../../../shared/items/inventory.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";
import { Component } from "../ecs/components.js";
import { tileToChunk, tileToRegion } from "../world/coordinates.js";
@@ -117,7 +118,11 @@ export function mobComponents (request)
firstName: displayName,
lastName: ""
};
if (!def.usePlayerBody)
if (def.usePlayerBody)
{
Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex)));
}
else
{
const sprite = mobSpriteName(def.mobTypeId);
if (sprite)
@@ -11,6 +11,7 @@ import {import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";import { emptyEquipment } from "../../../shared/items/inventory.js";import { emptyEquipment } from "../../../shared/items/inventory.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { appearanceHairFields, hairFromNameSeed } from "../../../shared/appearance/hair.js";import { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";import { tileToChunk, tileToRegion } from "../world/coordinates.js";import { tileToChunk, tileToRegion } from "../world/coordinates.js";@@ -117,7 +118,11 @@ export function mobComponents (request) firstName: displayName, firstName: displayName, lastName: "" lastName: "" }; }; if (!def.usePlayerBody) if (def.usePlayerBody) { Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex))); } else { { const sprite = mobSpriteName(def.mobTypeId); const sprite = mobSpriteName(def.mobTypeId); if (sprite) if (sprite)@@ -62,6 +62,7 @@ import {
} from "../../../shared/stamina/rules.js";
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
import { stepStatusEffects } from "../statusEffects/service.js";
export class WorkerWorld
{
@@ -127,6 +128,8 @@ export class WorkerWorld
return this.#inspectStamina(message.entityId);
case WorkerMessage.applyBag:
return this.#applyBag(message.entityId, message.bag);
case WorkerMessage.applyAppearance:
return this.#applyAppearance(message.entityId, message.appearance);
case WorkerMessage.updateFlight:
return this.#updateFlight(message.entityId, message.flight, message.now);
case WorkerMessage.chunkIsSimulating:
@@ -572,6 +575,18 @@ export class WorkerWorld
return applyBagView(this.ecs, handle, bag);
}
#applyAppearance (entityId, appearancePatch)
{
const handle = this.ecs.handleOf(entityId);
if (handle == null)
{ return null; }
const appearance = this.ecs.get(handle, Component.appearance);
if (!appearance)
{ return null; }
Object.assign(appearance, appearancePatch ?? {});
return publicEntityView(this.ecs, entityId);
}
#updateFlight (entityId, flightPatch, now = Date.now())
{
const handle = this.ecs.handleOf(entityId);
@@ -945,6 +960,7 @@ export class WorkerWorld
const events = [];
const transferRequests = [];
this.#regenStamina(dt, events);
events.push(...stepStatusEffects(this, now, dt));
const flight = stepFreeFlight(this, now);
for (const event of flight)
{
@@ -62,6 +62,7 @@ import {} from "../../../shared/stamina/rules.js";} from "../../../shared/stamina/rules.js";import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";import { stepStatusEffects } from "../statusEffects/service.js";export class WorkerWorldexport class WorkerWorld{{@@ -127,6 +128,8 @@ export class WorkerWorld return this.#inspectStamina(message.entityId); return this.#inspectStamina(message.entityId); case WorkerMessage.applyBag: case WorkerMessage.applyBag: return this.#applyBag(message.entityId, message.bag); return this.#applyBag(message.entityId, message.bag); case WorkerMessage.applyAppearance: return this.#applyAppearance(message.entityId, message.appearance); case WorkerMessage.updateFlight: case WorkerMessage.updateFlight: return this.#updateFlight(message.entityId, message.flight, message.now); return this.#updateFlight(message.entityId, message.flight, message.now); case WorkerMessage.chunkIsSimulating: case WorkerMessage.chunkIsSimulating:@@ -572,6 +575,18 @@ export class WorkerWorld return applyBagView(this.ecs, handle, bag); return applyBagView(this.ecs, handle, bag); } } #applyAppearance (entityId, appearancePatch) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const appearance = this.ecs.get(handle, Component.appearance); if (!appearance) { return null; } Object.assign(appearance, appearancePatch ?? {}); return publicEntityView(this.ecs, entityId); } #updateFlight (entityId, flightPatch, now = Date.now()) #updateFlight (entityId, flightPatch, now = Date.now()) { { const handle = this.ecs.handleOf(entityId); const handle = this.ecs.handleOf(entityId);@@ -945,6 +960,7 @@ export class WorkerWorld const events = []; const events = []; const transferRequests = []; const transferRequests = []; this.#regenStamina(dt, events); this.#regenStamina(dt, events); events.push(...stepStatusEffects(this, now, dt)); const flight = stepFreeFlight(this, now); const flight = stepFreeFlight(this, now); for (const event of flight) for (const event of flight) { {@@ -0,0 +1,124 @@
import { Component } from "../ecs/components.js";
import {
activeStatusEffects,
pruneStatusEffects,
StatusEffectType,
publicStatusEffectsView,
hasStatusEffect
} from "../../../shared/statusEffects/rules.js";
import { publicEntityView } from "../ecs/serialize.js";
import { syncPlayerHealth } from "../skills/service.js";
/**
* Tick timed potion effects: health/stamina regen & drain.
* Returns replication events (health/stamina/appearance/status-effects).
*/
export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
{
const events = [];
for (const entity of world.ecs.query(Component.character, Component.statusEffects))
{
const { handle, entityId, character, statusEffects } = entity;
if (world.ecs.has(handle, Component.dead))
{ continue; }
const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
const beforeBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
pruneStatusEffects(statusEffects, now);
const afterScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink);
const afterGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow);
const afterBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind);
let healthChanged = false;
let staminaChanged = false;
const health = world.ecs.get(handle, Component.health);
const stamina = world.ecs.get(handle, Component.stamina);
for (const entry of activeStatusEffects(statusEffects, now))
{
const rate = Number(entry.amountPerSecond) || 0;
if (!rate)
{ continue; }
if (entry.type === StatusEffectType.healthRegen && health)
{
const before = health.current | 0;
health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
if ((health.current | 0) !== before)
{ healthChanged = true; }
}
if (entry.type === StatusEffectType.staminaRegen && stamina)
{
const before = Number(stamina.current) || 0;
stamina.current = Math.min(stamina.max, before + rate * dt);
if (Math.ceil(before) !== Math.ceil(stamina.current))
{ staminaChanged = true; }
}
if (entry.type === StatusEffectType.staminaDrain && stamina)
{
const before = Number(stamina.current) || 0;
stamina.current = Math.max(0, before - rate * dt);
if (Math.ceil(before) !== Math.ceil(stamina.current))
{ staminaChanged = true; }
}
}
if (healthChanged)
{
syncPlayerHealth(world.ecs, handle);
const view = publicEntityView(world.ecs, entityId);
if (view)
{
events.push({
type: "entity-health",
entityId,
characterId: character.characterId,
health: view.health,
maxHealth: view.maxHealth,
tileX: view.tileX,
tileY: view.tileY
});
}
}
if (staminaChanged)
{
events.push({
type: "stamina",
characterId: character.characterId,
current: Number(stamina.current) || 0,
max: Math.max(1, stamina.max | 0)
});
}
const appearanceChanged = beforeScale !== afterScale || beforeGlow !== afterGlow;
const statusChanged = appearanceChanged || beforeBlind !== afterBlind;
if (appearanceChanged)
{
const view = publicEntityView(world.ecs, entityId);
if (view)
{
events.push({
type: "entity-appearance",
entityId: view.entityId,
tileX: view.tileX,
tileY: view.tileY,
sprite: view.sprite ?? null,
layers: view.layers ?? [],
lightRadiusTiles: view.lightRadiusTiles ?? 0,
visualScale: view.visualScale ?? 1
});
}
}
if (statusChanged || healthChanged)
{
events.push({
type: "status-effects",
characterId: character.characterId,
effects: publicStatusEffectsView(statusEffects, now),
blind: hasStatusEffect(statusEffects, StatusEffectType.blind, now)
});
}
}
return events;
}
@@ -0,0 +1,124 @@import { Component } from "../ecs/components.js";import { activeStatusEffects, pruneStatusEffects, StatusEffectType, publicStatusEffectsView, hasStatusEffect} from "../../../shared/statusEffects/rules.js";import { publicEntityView } from "../ecs/serialize.js";import { syncPlayerHealth } from "../skills/service.js";/** * Tick timed potion effects: health/stamina regen & drain. * Returns replication events (health/stamina/appearance/status-effects). */export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20){ const events = []; for (const entity of world.ecs.query(Component.character, Component.statusEffects)) { const { handle, entityId, character, statusEffects } = entity; if (world.ecs.has(handle, Component.dead)) { continue; } const beforeScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink); const beforeGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow); const beforeBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind); pruneStatusEffects(statusEffects, now); const afterScale = statusEffects.effects?.some((e) => e.type === StatusEffectType.shrink); const afterGlow = statusEffects.effects?.some((e) => e.type === StatusEffectType.glow); const afterBlind = statusEffects.effects?.some((e) => e.type === StatusEffectType.blind); let healthChanged = false; let staminaChanged = false; const health = world.ecs.get(handle, Component.health); const stamina = world.ecs.get(handle, Component.stamina); for (const entry of activeStatusEffects(statusEffects, now)) { const rate = Number(entry.amountPerSecond) || 0; if (!rate) { continue; } if (entry.type === StatusEffectType.healthRegen && health) { const before = health.current | 0; health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt); if ((health.current | 0) !== before) { healthChanged = true; } } if (entry.type === StatusEffectType.staminaRegen && stamina) { const before = Number(stamina.current) || 0; stamina.current = Math.min(stamina.max, before + rate * dt); if (Math.ceil(before) !== Math.ceil(stamina.current)) { staminaChanged = true; } } if (entry.type === StatusEffectType.staminaDrain && stamina) { const before = Number(stamina.current) || 0; stamina.current = Math.max(0, before - rate * dt); if (Math.ceil(before) !== Math.ceil(stamina.current)) { staminaChanged = true; } } } if (healthChanged) { syncPlayerHealth(world.ecs, handle); const view = publicEntityView(world.ecs, entityId); if (view) { events.push({ type: "entity-health", entityId, characterId: character.characterId, health: view.health, maxHealth: view.maxHealth, tileX: view.tileX, tileY: view.tileY }); } } if (staminaChanged) { events.push({ type: "stamina", characterId: character.characterId, current: Number(stamina.current) || 0, max: Math.max(1, stamina.max | 0) }); } const appearanceChanged = beforeScale !== afterScale || beforeGlow !== afterGlow; const statusChanged = appearanceChanged || beforeBlind !== afterBlind; if (appearanceChanged) { const view = publicEntityView(world.ecs, entityId); if (view) { events.push({ type: "entity-appearance", entityId: view.entityId, tileX: view.tileX, tileY: view.tileY, sprite: view.sprite ?? null, layers: view.layers ?? [], lightRadiusTiles: view.lightRadiusTiles ?? 0, visualScale: view.visualScale ?? 1 }); } } if (statusChanged || healthChanged) { events.push({ type: "status-effects", characterId: character.characterId, effects: publicStatusEffectsView(statusEffects, now), blind: hasStatusEffect(statusEffects, StatusEffectType.blind, now) }); } } return events;}@@ -10,6 +10,11 @@ import {
normalizeGround,
normalizeBlock
} from "../../../shared/definitions/tiles.js";
import {
flowerBlockState,
flowerColorIdFromBlockState,
flowerColorIdForTile
} from "../../../shared/definitions/dyes.js";
import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
import { tileIndex } from "./coordinates.js";
@@ -50,7 +55,7 @@ export function encodeChunkBlob (data)
});
}
export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId, chunkX = 0, chunkY = 0)
{
if (!blob)
{ return createEmptyChunkData(groundTypeId); }
@@ -70,14 +75,25 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
{ light.push(0); }
const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
const originX = (chunkX | 0) * CHUNK_SIZE;
const originY = (chunkY | 0) * CHUNK_SIZE;
return {
open: !!parsed.open,
grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
blocks: blocks.map((block) => {
blocks: blocks.map((block, index) =>
{
const normalized = normalizeBlock(block);
if (normalized?.typeId === BlockType.spawner)
{ return null; }
if (normalized?.typeId === BlockType.flower && !flowerColorIdFromBlockState(normalized.state))
{
const localX = index % CHUNK_SIZE;
const localY = (index / CHUNK_SIZE) | 0;
normalized.state = flowerBlockState(
flowerColorIdForTile(originX + localX, originY + localY)
);
}
return normalized;
}),
light,
@@ -10,6 +10,11 @@ import { normalizeGround, normalizeGround, normalizeBlock normalizeBlock} from "../../../shared/definitions/tiles.js";} from "../../../shared/definitions/tiles.js";import { flowerBlockState, flowerColorIdFromBlockState, flowerColorIdForTile} from "../../../shared/definitions/dyes.js";import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";import { tileIndex } from "./coordinates.js";import { tileIndex } from "./coordinates.js";@@ -50,7 +55,7 @@ export function encodeChunkBlob (data) }); });}}export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId, chunkX = 0, chunkY = 0){{ if (!blob) if (!blob) { return createEmptyChunkData(groundTypeId); } { return createEmptyChunkData(groundTypeId); }@@ -70,14 +75,25 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def { light.push(0); } { light.push(0); } const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed); const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed); const originX = (chunkX | 0) * CHUNK_SIZE; const originY = (chunkY | 0) * CHUNK_SIZE; return { return { open: !!parsed.open, open: !!parsed.open, grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)), grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)), blocks: blocks.map((block) => { blocks: blocks.map((block, index) => { const normalized = normalizeBlock(block); const normalized = normalizeBlock(block); if (normalized?.typeId === BlockType.spawner) if (normalized?.typeId === BlockType.spawner) { return null; } { return null; } if (normalized?.typeId === BlockType.flower && !flowerColorIdFromBlockState(normalized.state)) { const localX = index % CHUNK_SIZE; const localY = (index / CHUNK_SIZE) | 0; normalized.state = flowerBlockState( flowerColorIdForTile(originX + localX, originY + localY) ); } return normalized; return normalized; }), }), light, light,@@ -41,27 +41,26 @@ function countItem (slots, itemId)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
test("green draught ratios and steps evaluate to a success batch", () =>
test("lesser health tonic ratios and steps evaluate to a success batch", () =>
{
const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught");
const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
assert.ok(potion);
const evaluation = evaluateAlchemyBottle({
skills: { levels: { alchemy: 1 } },
brewStacks: [
{ itemId: ItemId.greenHerb, quantity: 4 },
{ itemId: ItemId.apple, quantity: 2 }
{ itemId: ItemId.thyme, quantity: 2 },
{ itemId: ItemId.mint, quantity: 2 }
],
takenSteps: [
{ kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
{ kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
{ kind: AlchemyStepKind.heat },
{ kind: AlchemyStepKind.stir },
{ kind: AlchemyStepKind.insert, itemId: ItemId.apple },
{ kind: AlchemyStepKind.cool }
{ kind: AlchemyStepKind.insert, itemId: ItemId.mint },
{ kind: AlchemyStepKind.stir }
]
});
assert.equal(evaluation.success, true);
assert.equal(evaluation.batch, 2);
assert.equal(evaluation.result.potionKey, "greenDraught");
assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
});
test("same wrong steps hash to the same unstable potion", () =>
@@ -75,9 +74,10 @@ test("same wrong steps hash to the same unstable potion", () =>
const b = unstablePotionFromSteps(steps);
assert.equal(a.potionKey, b.potionKey);
assert.equal(a.stepsHash, hashAlchemySteps(steps));
assert.ok(["stamina-drain", "glow", "shrink", "blind"].includes(a.effectKey));
});
test("cauldron bottles green draught when steps and ratios match", () =>
test("cauldron bottles lesser health tonic when steps and ratios match", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
@@ -86,8 +86,8 @@ test("cauldron bottles green draught when steps and ratios match", () =>
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const inventory = emptySlots();
inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 };
inventory[1] = { itemId: ItemId.apple, quantity: 2 };
inventory[0] = { itemId: ItemId.thyme, quantity: 2 };
inventory[1] = { itemId: ItemId.mint, quantity: 2 };
inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 };
inventory[3] = { itemId: ItemId.paper, quantity: 1 };
harness.stateDb.saveBag(character.character_id, {
@@ -106,14 +106,14 @@ test("cauldron bottles green draught when steps and ratios match", () =>
type: "cauldron-set-slot",
characterId: cid,
slotIndex: 0,
itemId: ItemId.greenHerb,
quantity: 4
itemId: ItemId.thyme,
quantity: 2
});
harness.simulation.enqueue(1, {
type: "cauldron-set-slot",
characterId: cid,
slotIndex: 1,
itemId: ItemId.apple,
itemId: ItemId.mint,
quantity: 2
});
harness.simulation.step();
@@ -124,27 +124,22 @@ test("cauldron bottles green draught when steps and ratios match", () =>
characterId: cid,
action: AlchemyStepKind.heat
});
harness.simulation.enqueue(1, {
type: "cauldron-action",
characterId: cid,
action: AlchemyStepKind.stir
});
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 });
harness.simulation.enqueue(1, {
type: "cauldron-action",
characterId: cid,
action: AlchemyStepKind.cool
action: AlchemyStepKind.stir
});
harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid });
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0);
assert.equal(countItem(bag.inventory, ItemId.apple), 0);
assert.equal(countItem(bag.inventory, ItemId.thyme), 0);
assert.equal(countItem(bag.inventory, ItemId.mint), 0);
assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0);
assert.equal(countItem(bag.inventory, ItemId.potion), 2);
const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion);
assert.equal(potion.instance?.potionKey, "greenDraught");
assert.equal(potion.instance?.potionKey, "lesserHealthTonic");
assert.equal(potion.instance?.unstable, false);
harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });
@@ -153,7 +148,7 @@ test("cauldron bottles green draught when steps and ratios match", () =>
assert.equal(countItem(after.inventory, ItemId.paper), 0);
assert.equal(countItem(after.inventory, ItemId.recipePaper), 1);
const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper);
assert.match(recipe.instance?.body ?? "", /Green draught/);
assert.match(recipe.instance?.body ?? "", /Lesser health tonic/);
assert.match(recipe.instance?.body ?? "", /Alchemy level required/);
}
finally
@@ -41,27 +41,26 @@ function countItem (slots, itemId) .reduce((sum, slot) => sum + (slot.quantity | 0), 0); .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}}test("green draught ratios and steps evaluate to a success batch", () =>test("lesser health tonic ratios and steps evaluate to a success batch", () =>{{ const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "greenDraught"); const potion = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic"); assert.ok(potion); assert.ok(potion); const evaluation = evaluateAlchemyBottle({ const evaluation = evaluateAlchemyBottle({ skills: { levels: { alchemy: 1 } }, skills: { levels: { alchemy: 1 } }, brewStacks: [ brewStacks: [ { itemId: ItemId.greenHerb, quantity: 4 }, { itemId: ItemId.thyme, quantity: 2 }, { itemId: ItemId.apple, quantity: 2 } { itemId: ItemId.mint, quantity: 2 } ], ], takenSteps: [ takenSteps: [ { kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb }, { kind: AlchemyStepKind.insert, itemId: ItemId.thyme }, { kind: AlchemyStepKind.heat }, { kind: AlchemyStepKind.heat }, { kind: AlchemyStepKind.stir }, { kind: AlchemyStepKind.insert, itemId: ItemId.mint }, { kind: AlchemyStepKind.insert, itemId: ItemId.apple }, { kind: AlchemyStepKind.stir } { kind: AlchemyStepKind.cool } ] ] }); }); assert.equal(evaluation.success, true); assert.equal(evaluation.success, true); assert.equal(evaluation.batch, 2); assert.equal(evaluation.batch, 2); assert.equal(evaluation.result.potionKey, "greenDraught"); assert.equal(evaluation.result.potionKey, "lesserHealthTonic");});});test("same wrong steps hash to the same unstable potion", () =>test("same wrong steps hash to the same unstable potion", () =>@@ -75,9 +74,10 @@ test("same wrong steps hash to the same unstable potion", () => const b = unstablePotionFromSteps(steps); const b = unstablePotionFromSteps(steps); assert.equal(a.potionKey, b.potionKey); assert.equal(a.potionKey, b.potionKey); assert.equal(a.stepsHash, hashAlchemySteps(steps)); assert.equal(a.stepsHash, hashAlchemySteps(steps)); assert.ok(["stamina-drain", "glow", "shrink", "blind"].includes(a.effectKey));});});test("cauldron bottles green draught when steps and ratios match", () =>test("cauldron bottles lesser health tonic when steps and ratios match", () =>{{ const harness = makeSimulation({ workerCount: 1 }); const harness = makeSimulation({ workerCount: 1 }); try try@@ -86,8 +86,8 @@ test("cauldron bottles green draught when steps and ratios match", () => harness.simulation.reloadWorld(); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const inventory = emptySlots(); const inventory = emptySlots(); inventory[0] = { itemId: ItemId.greenHerb, quantity: 4 }; inventory[0] = { itemId: ItemId.thyme, quantity: 2 }; inventory[1] = { itemId: ItemId.apple, quantity: 2 }; inventory[1] = { itemId: ItemId.mint, quantity: 2 }; inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 }; inventory[2] = { itemId: ItemId.glassBottle, quantity: 2 }; inventory[3] = { itemId: ItemId.paper, quantity: 1 }; inventory[3] = { itemId: ItemId.paper, quantity: 1 }; harness.stateDb.saveBag(character.character_id, { harness.stateDb.saveBag(character.character_id, {@@ -106,14 +106,14 @@ test("cauldron bottles green draught when steps and ratios match", () => type: "cauldron-set-slot", type: "cauldron-set-slot", characterId: cid, characterId: cid, slotIndex: 0, slotIndex: 0, itemId: ItemId.greenHerb, itemId: ItemId.thyme, quantity: 4 quantity: 2 }); }); harness.simulation.enqueue(1, { harness.simulation.enqueue(1, { type: "cauldron-set-slot", type: "cauldron-set-slot", characterId: cid, characterId: cid, slotIndex: 1, slotIndex: 1, itemId: ItemId.apple, itemId: ItemId.mint, quantity: 2 quantity: 2 }); }); harness.simulation.step(); harness.simulation.step();@@ -124,27 +124,22 @@ test("cauldron bottles green draught when steps and ratios match", () => characterId: cid, characterId: cid, action: AlchemyStepKind.heat action: AlchemyStepKind.heat }); }); harness.simulation.enqueue(1, { type: "cauldron-action", characterId: cid, action: AlchemyStepKind.stir }); harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 }); harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 1 }); harness.simulation.enqueue(1, { harness.simulation.enqueue(1, { type: "cauldron-action", type: "cauldron-action", characterId: cid, characterId: cid, action: AlchemyStepKind.cool action: AlchemyStepKind.stir }); }); harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid }); harness.simulation.enqueue(1, { type: "cauldron-bottle", characterId: cid }); harness.simulation.step(); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); const bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.inventory, ItemId.greenHerb), 0); assert.equal(countItem(bag.inventory, ItemId.thyme), 0); assert.equal(countItem(bag.inventory, ItemId.apple), 0); assert.equal(countItem(bag.inventory, ItemId.mint), 0); assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0); assert.equal(countItem(bag.inventory, ItemId.glassBottle), 0); assert.equal(countItem(bag.inventory, ItemId.potion), 2); assert.equal(countItem(bag.inventory, ItemId.potion), 2); const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion); const potion = bag.inventory.find((slot) => slot?.itemId === ItemId.potion); assert.equal(potion.instance?.potionKey, "greenDraught"); assert.equal(potion.instance?.potionKey, "lesserHealthTonic"); assert.equal(potion.instance?.unstable, false); assert.equal(potion.instance?.unstable, false); harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid }); harness.simulation.enqueue(1, { type: "cauldron-save-recipe", characterId: cid });@@ -153,7 +148,7 @@ test("cauldron bottles green draught when steps and ratios match", () => assert.equal(countItem(after.inventory, ItemId.paper), 0); assert.equal(countItem(after.inventory, ItemId.paper), 0); assert.equal(countItem(after.inventory, ItemId.recipePaper), 1); assert.equal(countItem(after.inventory, ItemId.recipePaper), 1); const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper); const recipe = after.inventory.find((slot) => slot?.itemId === ItemId.recipePaper); assert.match(recipe.instance?.body ?? "", /Green draught/); assert.match(recipe.instance?.body ?? "", /Lesser health tonic/); assert.match(recipe.instance?.body ?? "", /Alchemy level required/); assert.match(recipe.instance?.body ?? "", /Alchemy level required/); } } finally finally@@ -0,0 +1,194 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import { Component } from "../src/ecs/components.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
function placeBlock (worldDb, tileX, tileY, typeId)
{
const chunkX = Math.floor(tileX / 16);
const chunkY = Math.floor(tileY / 16);
const data = createEmptyChunkData();
data.open = true;
const localX = tileX - chunkX * 16;
const localY = tileY - chunkY * 16;
data.blocks[localY * 16 + localX] = { typeId, state: 0 };
worldDb.saveChunkVersion(
chunkX,
chunkY,
worldDb.getActiveRevisionId(),
true,
encodeChunkBlob(data)
);
}
function countCoins (slots)
{
return (slots ?? [])
.filter((slot) => slot?.itemId === ItemId.coins)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
function giveCoins (harness, entityId, amount)
{
const bag = harness.simulation.bagOf(entityId);
bag.inventory = emptySlots();
bag.inventory[0] = { itemId: ItemId.coins, quantity: amount };
bag.equipment = emptyEquipment();
harness.simulation.applyBag(entityId, bag);
harness.stateDb.saveBag(
harness.simulation.directory.get(entityId).characterId,
bag
);
}
function componentsOf (simulation, entityId)
{
const record = simulation.entityRecord(entityId);
const worker = simulation.workers[record.workerId];
const handle = worker.world.ecs.handleOf(entityId);
return worker.world.ecs.componentsOf(handle);
}
function withDeterministicCombat (fn)
{
const random = Math.random;
Math.random = () => 0;
try
{ fn(); }
finally
{ Math.random = random; }
}
test("raise bounty spends inventory coins and tracks ledger", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
harness.simulation.reloadWorld();
const placer = makeCharacter(harness.stateDb, {
firstName: "Place",
lastName: "R",
tileX: 8,
tileY: 9
});
const target = makeCharacter(harness.stateDb, {
firstName: "Mark",
lastName: "Ed",
tileX: 10,
tileY: 10
});
const placerId = harness.simulation.spawnCharacter(1, placer);
giveCoins(harness, placerId, 500);
harness.simulation.enqueue(1, {
type: "raise-bounty",
characterId: placer.character_id,
firstName: "Mark",
lastName: "Ed",
amountCopper: 250
});
const result = harness.simulation.step();
const snap = result.events.find((event) => event.type === "bounty-snapshot");
assert.ok(snap?.raised);
assert.equal(snap.raised.amountCopper, 250);
assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 250);
assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 250);
harness.simulation.enqueue(1, {
type: "raise-bounty",
characterId: placer.character_id,
firstName: "Mark",
lastName: "Ed",
amountCopper: 100
});
harness.simulation.step();
assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 350);
assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 150);
}
finally
{ harness.close(); }
});
test("open bounty requires standing next to a bounty office", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 12 });
harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "open-bounty",
characterId: character.character_id
});
const result = harness.simulation.step();
const error = result.events.find((event) => event.type === "command-error");
assert.ok(error);
assert.match(error.message, /Bounty Office/i);
}
finally
{ harness.close(); }
});
test("PvP kill pays bounty into killer vault and clears ledger", () =>
{
withDeterministicCombat(() =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice);
placeBlock(harness.worldDb, 7, 8, BlockType.bank);
harness.simulation.reloadWorld();
const victim = makeCharacter(harness.stateDb, {
firstName: "Vic",
lastName: "Tim",
tileX: 9,
tileY: 9
});
const killer = makeCharacter(harness.stateDb, {
firstName: "Kill",
lastName: "Er",
tileX: 10,
tileY: 9
});
harness.stateDb.addCharacterBounty(victim.character_id, 400);
const victimId = harness.simulation.spawnCharacter(1, victim);
const killerId = harness.simulation.spawnCharacter(2, killer);
const victimComps = componentsOf(harness.simulation, victimId);
victimComps.health.current = 1;
const killerComps = componentsOf(harness.simulation, killerId);
killerComps.health.current = 1_000_000;
killerComps.health.max = 1_000_000;
harness.simulation.enqueue(2, {
type: "attack",
characterId: killer.character_id,
targetEntityId: victimId
});
let died = null;
for (let i = 0; i < 200; i++)
{
harness.advance(50);
const events = harness.simulation.step().events;
died = events.find((event) => event.type === "player-died");
if (died)
{ break; }
}
assert.ok(died, "victim should die");
assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0);
assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400);
}
finally
{ harness.close(); }
});
});
@@ -0,0 +1,194 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType } from "../../shared/definitions/tiles.js";import { ItemId } from "../../shared/definitions/items.js";import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { Component } from "../src/ecs/components.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";function placeBlock (worldDb, tileX, tileY, typeId){ const chunkX = Math.floor(tileX / 16); const chunkY = Math.floor(tileY / 16); const data = createEmptyChunkData(); data.open = true; const localX = tileX - chunkX * 16; const localY = tileY - chunkY * 16; data.blocks[localY * 16 + localX] = { typeId, state: 0 }; worldDb.saveChunkVersion( chunkX, chunkY, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data) );}function countCoins (slots){ return (slots ?? []) .filter((slot) => slot?.itemId === ItemId.coins) .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}function giveCoins (harness, entityId, amount){ const bag = harness.simulation.bagOf(entityId); bag.inventory = emptySlots(); bag.inventory[0] = { itemId: ItemId.coins, quantity: amount }; bag.equipment = emptyEquipment(); harness.simulation.applyBag(entityId, bag); harness.stateDb.saveBag( harness.simulation.directory.get(entityId).characterId, bag );}function componentsOf (simulation, entityId){ const record = simulation.entityRecord(entityId); const worker = simulation.workers[record.workerId]; const handle = worker.world.ecs.handleOf(entityId); return worker.world.ecs.componentsOf(handle);}function withDeterministicCombat (fn){ const random = Math.random; Math.random = () => 0; try { fn(); } finally { Math.random = random; }}test("raise bounty spends inventory coins and tracks ledger", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice); harness.simulation.reloadWorld(); const placer = makeCharacter(harness.stateDb, { firstName: "Place", lastName: "R", tileX: 8, tileY: 9 }); const target = makeCharacter(harness.stateDb, { firstName: "Mark", lastName: "Ed", tileX: 10, tileY: 10 }); const placerId = harness.simulation.spawnCharacter(1, placer); giveCoins(harness, placerId, 500); harness.simulation.enqueue(1, { type: "raise-bounty", characterId: placer.character_id, firstName: "Mark", lastName: "Ed", amountCopper: 250 }); const result = harness.simulation.step(); const snap = result.events.find((event) => event.type === "bounty-snapshot"); assert.ok(snap?.raised); assert.equal(snap.raised.amountCopper, 250); assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 250); assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 250); harness.simulation.enqueue(1, { type: "raise-bounty", characterId: placer.character_id, firstName: "Mark", lastName: "Ed", amountCopper: 100 }); harness.simulation.step(); assert.equal(harness.stateDb.getCharacterBounty(target.character_id), 350); assert.equal(countCoins(harness.simulation.bagOf(placerId).inventory), 150); } finally { harness.close(); }});test("open bounty requires standing next to a bounty office", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 12 }); harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "open-bounty", characterId: character.character_id }); const result = harness.simulation.step(); const error = result.events.find((event) => event.type === "command-error"); assert.ok(error); assert.match(error.message, /Bounty Office/i); } finally { harness.close(); }});test("PvP kill pays bounty into killer vault and clears ledger", () =>{ withDeterministicCombat(() => { const harness = makeSimulation({ workerCount: 1 }); try { placeBlock(harness.worldDb, 8, 8, BlockType.bountyOffice); placeBlock(harness.worldDb, 7, 8, BlockType.bank); harness.simulation.reloadWorld(); const victim = makeCharacter(harness.stateDb, { firstName: "Vic", lastName: "Tim", tileX: 9, tileY: 9 }); const killer = makeCharacter(harness.stateDb, { firstName: "Kill", lastName: "Er", tileX: 10, tileY: 9 }); harness.stateDb.addCharacterBounty(victim.character_id, 400); const victimId = harness.simulation.spawnCharacter(1, victim); const killerId = harness.simulation.spawnCharacter(2, killer); const victimComps = componentsOf(harness.simulation, victimId); victimComps.health.current = 1; const killerComps = componentsOf(harness.simulation, killerId); killerComps.health.current = 1_000_000; killerComps.health.max = 1_000_000; harness.simulation.enqueue(2, { type: "attack", characterId: killer.character_id, targetEntityId: victimId }); let died = null; for (let i = 0; i < 200; i++) { harness.advance(50); const events = harness.simulation.step().events; died = events.find((event) => event.type === "player-died"); if (died) { break; } } assert.ok(died, "victim should die"); assert.equal(harness.stateDb.getCharacterBounty(victim.character_id), 0); assert.equal(countCoins(harness.simulation.bagOf(killerId).vault), 400); } finally { harness.close(); } });});@@ -32,12 +32,12 @@ function potionStack (fillLevel, quantity = 1)
itemId: ItemId.potion,
quantity,
instance: potionItemInstance({
potionKey: "greenDraught",
displayName: "Green draught",
color: { r: 0.25, g: 0.72, b: 0.35 },
potionKey: "lesserHealthTonic",
displayName: "Lesser health tonic",
color: { r: 0.35, g: 0.78, b: 0.42 },
fillLevel,
effect: { type: "heal", amount: 5 },
effectKey: "heal"
effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
effectKey: "health-regen"
})
};
}
@@ -32,12 +32,12 @@ function potionStack (fillLevel, quantity = 1) itemId: ItemId.potion, itemId: ItemId.potion, quantity, quantity, instance: potionItemInstance({ instance: potionItemInstance({ potionKey: "greenDraught", potionKey: "lesserHealthTonic", displayName: "Green draught", displayName: "Lesser health tonic", color: { r: 0.25, g: 0.72, b: 0.35 }, color: { r: 0.35, g: 0.78, b: 0.42 }, fillLevel, fillLevel, effect: { type: "heal", amount: 5 }, effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 }, effectKey: "heal" effectKey: "health-regen" }) }) }; };}}@@ -0,0 +1,142 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { HerbId } from "../../shared/definitions/herbs.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";
import { evaluateAlchemyBottle, resolvedAlchemyPotions } from "../../shared/alchemy/recipes.js";
import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
import { totalXpForLevel } from "../../shared/skills/progression.js";
import { Component } from "../src/ecs/components.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
function placeBlock (worldDb, tileX, tileY, typeId, state = 0)
{
const chunkX = Math.floor(tileX / 16);
const chunkY = Math.floor(tileY / 16);
const data = createEmptyChunkData();
data.open = true;
const localX = tileX - chunkX * 16;
const localY = tileY - chunkY * 16;
data.blocks[localY * 16 + localX] = { typeId, state };
worldDb.saveChunkVersion(
chunkX,
chunkY,
worldDb.getActiveRevisionId(),
true,
encodeChunkBlob(data)
);
}
function countItem (slots, itemId)
{
return (slots ?? [])
.filter((slot) => slot?.itemId === itemId)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
test("sage herb plant yields sage with clippers", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
const bag = harness.simulation.bagOf(entityId);
bag.inventory = emptySlots();
bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
bag.equipment = emptyEquipment();
harness.simulation.applyBag(entityId, bag);
const record = harness.simulation.entityRecord(entityId);
const worker = harness.simulation.workers[record.workerId];
const handle = worker.world.ecs.handleOf(entityId);
const skills = worker.world.ecs.get(handle, Component.skills);
skills.xp[SkillId.herbalism] = totalXpForLevel(5);
harness.simulation.enqueue(1, {
type: "pick",
characterId: character.character_id,
tileX: 8,
tileY: 8
});
harness.simulation.step();
harness.advance(4000);
harness.simulation.step();
assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.sage), 1);
}
finally
{ harness.close(); }
});
test("aconite herb plant rejects low herbalism", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.aconite);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
const bag = harness.simulation.bagOf(entityId);
bag.inventory = emptySlots();
bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 };
bag.equipment = emptyEquipment();
harness.simulation.applyBag(entityId, bag);
harness.simulation.enqueue(1, {
type: "pick",
characterId: character.character_id,
tileX: 8,
tileY: 8
});
const result = harness.simulation.step();
const error = result.events.find((event) => event.type === "command-error");
assert.ok(error);
assert.match(error.message, /Herbalism 45/i);
}
finally
{ harness.close(); }
});
test("starter potions evaluate with herb recipes", () =>
{
const tonic = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic");
assert.ok(tonic);
const evaluation = evaluateAlchemyBottle({
skills: { levels: { alchemy: 1 } },
brewStacks: [
{ itemId: ItemId.thyme, quantity: 1 },
{ itemId: ItemId.mint, quantity: 1 }
],
takenSteps: [
{ kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
{ kind: AlchemyStepKind.heat },
{ kind: AlchemyStepKind.insert, itemId: ItemId.mint },
{ kind: AlchemyStepKind.stir }
]
});
assert.equal(evaluation.success, true);
assert.equal(evaluation.result.potionKey, "lesserHealthTonic");
assert.equal(evaluation.result.effect.type, "health-regen");
const strength = evaluateAlchemyBottle({
skills: { levels: { alchemy: 1 } },
brewStacks: [
{ itemId: ItemId.thyme, quantity: 3 },
{ itemId: ItemId.nettle, quantity: 2 }
],
takenSteps: [
{ kind: AlchemyStepKind.insert, itemId: ItemId.thyme },
{ kind: AlchemyStepKind.stir },
{ kind: AlchemyStepKind.insert, itemId: ItemId.nettle },
{ kind: AlchemyStepKind.heat }
]
});
assert.equal(strength.success, true);
assert.equal(strength.result.potionKey, "strengthPotion");
});
@@ -0,0 +1,142 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType } from "../../shared/definitions/tiles.js";import { ItemId } from "../../shared/definitions/items.js";import { HerbId } from "../../shared/definitions/herbs.js";import { SkillId } from "../../shared/definitions/skills.js";import { AlchemyStepKind } from "../../shared/definitions/alchemy.js";import { evaluateAlchemyBottle, resolvedAlchemyPotions } from "../../shared/alchemy/recipes.js";import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";import { totalXpForLevel } from "../../shared/skills/progression.js";import { Component } from "../src/ecs/components.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";function placeBlock (worldDb, tileX, tileY, typeId, state = 0){ const chunkX = Math.floor(tileX / 16); const chunkY = Math.floor(tileY / 16); const data = createEmptyChunkData(); data.open = true; const localX = tileX - chunkX * 16; const localY = tileY - chunkY * 16; data.blocks[localY * 16 + localX] = { typeId, state }; worldDb.saveChunkVersion( chunkX, chunkY, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data) );}function countItem (slots, itemId){ return (slots ?? []) .filter((slot) => slot?.itemId === itemId) .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}test("sage herb plant yields sage with clippers", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.sage); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); const bag = harness.simulation.bagOf(entityId); bag.inventory = emptySlots(); bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 }; bag.equipment = emptyEquipment(); harness.simulation.applyBag(entityId, bag); const record = harness.simulation.entityRecord(entityId); const worker = harness.simulation.workers[record.workerId]; const handle = worker.world.ecs.handleOf(entityId); const skills = worker.world.ecs.get(handle, Component.skills); skills.xp[SkillId.herbalism] = totalXpForLevel(5); harness.simulation.enqueue(1, { type: "pick", characterId: character.character_id, tileX: 8, tileY: 8 }); harness.simulation.step(); harness.advance(4000); harness.simulation.step(); assert.equal(countItem(harness.simulation.bagOf(entityId).inventory, ItemId.sage), 1); } finally { harness.close(); }});test("aconite herb plant rejects low herbalism", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBlock(harness.worldDb, 8, 8, BlockType.herbPlant, HerbId.aconite); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); const bag = harness.simulation.bagOf(entityId); bag.inventory = emptySlots(); bag.inventory[0] = { itemId: ItemId.bronzePlantClippers, quantity: 1 }; bag.equipment = emptyEquipment(); harness.simulation.applyBag(entityId, bag); harness.simulation.enqueue(1, { type: "pick", characterId: character.character_id, tileX: 8, tileY: 8 }); const result = harness.simulation.step(); const error = result.events.find((event) => event.type === "command-error"); assert.ok(error); assert.match(error.message, /Herbalism 45/i); } finally { harness.close(); }});test("starter potions evaluate with herb recipes", () =>{ const tonic = resolvedAlchemyPotions().find((entry) => entry.potionKey === "lesserHealthTonic"); assert.ok(tonic); const evaluation = evaluateAlchemyBottle({ skills: { levels: { alchemy: 1 } }, brewStacks: [ { itemId: ItemId.thyme, quantity: 1 }, { itemId: ItemId.mint, quantity: 1 } ], takenSteps: [ { kind: AlchemyStepKind.insert, itemId: ItemId.thyme }, { kind: AlchemyStepKind.heat }, { kind: AlchemyStepKind.insert, itemId: ItemId.mint }, { kind: AlchemyStepKind.stir } ] }); assert.equal(evaluation.success, true); assert.equal(evaluation.result.potionKey, "lesserHealthTonic"); assert.equal(evaluation.result.effect.type, "health-regen"); const strength = evaluateAlchemyBottle({ skills: { levels: { alchemy: 1 } }, brewStacks: [ { itemId: ItemId.thyme, quantity: 3 }, { itemId: ItemId.nettle, quantity: 2 } ], takenSteps: [ { kind: AlchemyStepKind.insert, itemId: ItemId.thyme }, { kind: AlchemyStepKind.stir }, { kind: AlchemyStepKind.insert, itemId: ItemId.nettle }, { kind: AlchemyStepKind.heat } ] }); assert.equal(strength.success, true); assert.equal(strength.result.potionKey, "strengthPotion");});@@ -62,6 +62,35 @@ test("state cycling wraps and unknown values fall back to default", () =>
assert.equal(cycleState(["1", "2"], "1", -1), "2");
});
test("legacy flower blocks get a tile-seeded colour on decode", () =>
{
const data = decodeChunkBlob({
open: true,
grounds: [],
blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
light: []
}, undefined, 0, 0);
assert.notEqual(data.blocks[0].state, "flower");
assert.ok(
["red", "blue", "cyan", "violet", "yellow", "magenta", "white", "black", "pink"]
.includes(data.blocks[0].state)
);
const again = decodeChunkBlob({
open: true,
grounds: [],
blocks: [{ typeId: BlockType.flower, state: "flower", config: null }],
light: []
}, undefined, 0, 0);
assert.equal(again.blocks[0].state, data.blocks[0].state);
const coloured = decodeChunkBlob({
open: true,
grounds: [],
blocks: [{ typeId: BlockType.flower, state: "blue", config: null }],
light: []
}, undefined, 0, 0);
assert.equal(coloured.blocks[0].state, "blue");
});
test("old numeric grounds decode as default visual state", () =>
{
const data = decodeChunkBlob({
@@ -62,6 +62,35 @@ test("state cycling wraps and unknown values fall back to default", () => assert.equal(cycleState(["1", "2"], "1", -1), "2"); assert.equal(cycleState(["1", "2"], "1", -1), "2");});});test("legacy flower blocks get a tile-seeded colour on decode", () =>{ const data = decodeChunkBlob({ open: true, grounds: [], blocks: [{ typeId: BlockType.flower, state: "flower", config: null }], light: [] }, undefined, 0, 0); assert.notEqual(data.blocks[0].state, "flower"); assert.ok( ["red", "blue", "cyan", "violet", "yellow", "magenta", "white", "black", "pink"] .includes(data.blocks[0].state) ); const again = decodeChunkBlob({ open: true, grounds: [], blocks: [{ typeId: BlockType.flower, state: "flower", config: null }], light: [] }, undefined, 0, 0); assert.equal(again.blocks[0].state, data.blocks[0].state); const coloured = decodeChunkBlob({ open: true, grounds: [], blocks: [{ typeId: BlockType.flower, state: "blue", config: null }], light: [] }, undefined, 0, 0); assert.equal(coloured.blocks[0].state, "blue");});test("old numeric grounds decode as default visual state", () =>test("old numeric grounds decode as default visual state", () =>{{ const data = decodeChunkBlob({ const data = decodeChunkBlob({