rweaks
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.
@@ -227,35 +227,41 @@
<button id="market-close" type="button">Close</button>
</header>
<p id="market-hint" class="hint"></p>
<p id="market-coins" class="shop-coins">Coins: 0</p>
<section class="market-section">
<h3>Your orders</h3>
<p id="market-coins" class="shop-coins">Funds: 0</p>
<div class="market-tabs" role="tablist">
<button id="market-tab-orders" type="button" class="market-tab active" data-tab="orders">Your Orders</button>
<button id="market-tab-sell" type="button" class="market-tab" data-tab="sell">Sell</button>
<button id="market-tab-buy" type="button" class="market-tab" data-tab="buy">Buy</button>
</div>
<section id="market-pane-orders" class="market-pane" data-pane="orders">
<div id="market-orders"></div>
</section>
<section class="market-section market-columns">
<div>
<h3>Buy order</h3>
<div id="market-catalog" class="market-catalog"></div>
<p id="market-buy-item" class="hint">Select an item</p>
<label class="send-row">Quantity
<input id="market-buy-qty" type="number" min="1" step="1" value="1">
</label>
<label class="send-row">Max unit price
<input id="market-buy-max" type="number" min="1" step="1" value="1">
</label>
<button id="market-buy-confirm" type="button">Place buy order</button>
</div>
<div>
<h3>Sell order</h3>
<div id="market-sell-list" class="market-sell-list"></div>
<label class="send-row">Quantity
<input id="market-sell-qty" type="number" min="1" step="1" value="1">
</label>
<label class="send-row">Min unit price
<input id="market-sell-min" type="number" min="1" step="1" value="1">
</label>
<button id="market-sell-confirm" type="button">Place sell order</button>
</div>
<section id="market-pane-sell" class="market-pane" data-pane="sell" hidden>
<div id="market-sell-list" class="market-sell-list"></div>
<p id="market-sell-selected" class="hint">Select an item from your bag</p>
<label class="send-row">Quantity
<input id="market-sell-qty" type="number" min="1" step="1" value="1">
</label>
<label class="send-row">Min unit price
<input id="market-sell-min" type="number" min="1" step="1" value="1">
</label>
<p id="market-sell-fee" class="hint"></p>
<button id="market-sell-confirm" type="button">Place sell order</button>
</section>
<section id="market-pane-buy" class="market-pane" data-pane="buy" hidden>
<label class="send-row">Search items
<input id="market-buy-search" type="search" placeholder="Type a name and press Enter" autocomplete="off">
</label>
<div id="market-catalog" class="market-catalog"></div>
<p id="market-buy-item" class="hint">Search and select an item</p>
<label class="send-row">Quantity
<input id="market-buy-qty" type="number" min="1" step="1" value="1">
</label>
<label class="send-row">Max unit price
<input id="market-buy-max" type="number" min="1" step="1" value="1">
</label>
<p id="market-buy-fee" class="hint"></p>
<button id="market-buy-confirm" type="button">Place buy order</button>
</section>
</aside>
@@ -227,35 +227,41 @@ <button id="market-close" type="button">Close</button> <button id="market-close" type="button">Close</button> </header> </header> <p id="market-hint" class="hint"></p> <p id="market-hint" class="hint"></p> <p id="market-coins" class="shop-coins">Coins: 0</p> <p id="market-coins" class="shop-coins">Funds: 0</p> <section class="market-section"> <div class="market-tabs" role="tablist"> <h3>Your orders</h3> <button id="market-tab-orders" type="button" class="market-tab active" data-tab="orders">Your Orders</button> <button id="market-tab-sell" type="button" class="market-tab" data-tab="sell">Sell</button> <button id="market-tab-buy" type="button" class="market-tab" data-tab="buy">Buy</button> </div> <section id="market-pane-orders" class="market-pane" data-pane="orders"> <div id="market-orders"></div> <div id="market-orders"></div> </section> </section> <section class="market-section market-columns"> <section id="market-pane-sell" class="market-pane" data-pane="sell" hidden> <div> <div id="market-sell-list" class="market-sell-list"></div> <h3>Buy order</h3> <p id="market-sell-selected" class="hint">Select an item from your bag</p> <div id="market-catalog" class="market-catalog"></div> <label class="send-row">Quantity <p id="market-buy-item" class="hint">Select an item</p> <input id="market-sell-qty" type="number" min="1" step="1" value="1"> <label class="send-row">Quantity </label> <input id="market-buy-qty" type="number" min="1" step="1" value="1"> <label class="send-row">Min unit price </label> <input id="market-sell-min" type="number" min="1" step="1" value="1"> <label class="send-row">Max unit price </label> <input id="market-buy-max" type="number" min="1" step="1" value="1"> <p id="market-sell-fee" class="hint"></p> </label> <button id="market-sell-confirm" type="button">Place sell order</button> <button id="market-buy-confirm" type="button">Place buy order</button> </section> </div> <section id="market-pane-buy" class="market-pane" data-pane="buy" hidden> <div> <label class="send-row">Search items <h3>Sell order</h3> <input id="market-buy-search" type="search" placeholder="Type a name and press Enter" autocomplete="off"> <div id="market-sell-list" class="market-sell-list"></div> </label> <label class="send-row">Quantity <div id="market-catalog" class="market-catalog"></div> <input id="market-sell-qty" type="number" min="1" step="1" value="1"> <p id="market-buy-item" class="hint">Search and select an item</p> </label> <label class="send-row">Quantity <label class="send-row">Min unit price <input id="market-buy-qty" type="number" min="1" step="1" value="1"> <input id="market-sell-min" type="number" min="1" step="1" value="1"> </label> </label> <label class="send-row">Max unit price <button id="market-sell-confirm" type="button">Place sell order</button> <input id="market-buy-max" type="number" min="1" step="1" value="1"> </div> </label> <p id="market-buy-fee" class="hint"></p> <button id="market-buy-confirm" type="button">Place buy order</button> </section> </section> </aside> </aside>@@ -0,0 +1,199 @@
/**
* Generate 16×16 top-down wooden counter PNGs for neighbor-connect masks 0–15.
* Perspective: orthographic top-down (grid-aligned, not diamond isometric).
* Connections remove the shared edge rim so adjacent tiles read as one counter.
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { NeighborBit } from "../../shared/world/neighborConnect.js";
const SIZE = 16;
const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/marketplace");
/** Wood palette (RGBA). */
const RIM = [92, 58, 32, 255];
const RIM_DARK = [62, 38, 20, 255];
const TOP = [196, 148, 78, 255];
const TOP_LIGHT = [214, 170, 98, 255];
const TOP_SHADE = [168, 120, 58, 255];
const GRAIN = [180, 132, 64, 255];
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 fillRect (rgba, x0, y0, x1, y1, color)
{
for (let y = y0; y <= y1; y++)
{
for (let x = x0; x <= x1; x++)
{ setPx(rgba, x, y, color); }
}
}
function paintCounter (mask)
{
const rgba = new Uint8Array(SIZE * SIZE * 4);
const connectN = (mask & NeighborBit.n) !== 0;
const connectE = (mask & NeighborBit.e) !== 0;
const connectS = (mask & NeighborBit.s) !== 0;
const connectW = (mask & NeighborBit.w) !== 0;
const topY0 = connectN ? 0 : 2;
const topY1 = connectS ? SIZE - 1 : SIZE - 3;
const topX0 = connectW ? 0 : 2;
const topX1 = connectE ? SIZE - 1 : SIZE - 3;
// Base fill transparent then rim body where not connected.
for (let i = 0; i < rgba.length; i += 4)
{ rgba[i + 3] = 0; }
// Outer rim (only on non-connected sides).
if (!connectN)
{ fillRect(rgba, 0, 0, SIZE - 1, 1, RIM_DARK); }
if (!connectS)
{ fillRect(rgba, 0, SIZE - 2, SIZE - 1, SIZE - 1, RIM_DARK); }
if (!connectW)
{ fillRect(rgba, 0, 0, 1, SIZE - 1, RIM_DARK); }
if (!connectE)
{ fillRect(rgba, SIZE - 2, 0, SIZE - 1, SIZE - 1, RIM_DARK); }
// Inner rim bevel
if (!connectN)
{ fillRect(rgba, topX0, 1, topX1, 1, RIM); }
if (!connectS)
{ fillRect(rgba, topX0, SIZE - 2, topX1, SIZE - 2, RIM); }
if (!connectW)
{ fillRect(rgba, 1, topY0, 1, topY1, RIM); }
if (!connectE)
{ fillRect(rgba, SIZE - 2, topY0, SIZE - 2, topY1, RIM); }
// Countertop
fillRect(rgba, topX0, topY0, topX1, topY1, TOP);
// Subtle grain / highlight
for (let y = topY0; y <= topY1; y++)
{
for (let x = topX0; x <= topX1; x++)
{
if (((x + y * 3) % 7) === 0)
{ setPx(rgba, x, y, GRAIN); }
if (y === topY0 && !connectN)
{ setPx(rgba, x, y, TOP_LIGHT); }
if (y === topY1 && !connectS)
{ setPx(rgba, x, y, TOP_SHADE); }
}
}
// Corner posts when both adjacent sides are free (standalone corners).
const corners = [
{ x: 0, y: 0, n: connectN, w: connectW },
{ x: SIZE - 1, y: 0, n: connectN, e: connectE },
{ x: 0, y: SIZE - 1, s: connectS, w: connectW },
{ x: SIZE - 1, y: SIZE - 1, s: connectS, e: connectE }
];
for (const c of corners)
{
const openN = c.n === false || c.n == null;
const openS = c.s === false || c.s == null;
const openE = c.e === false || c.e == null;
const openW = c.w === false || c.w == null;
if ((c.n != null || c.s != null) && (c.e != null || c.w != null))
{
const vertOpen = (c.n != null ? !c.n : !c.s);
const horzOpen = (c.e != null ? !c.e : !c.w);
if (vertOpen && horzOpen)
{ setPx(rgba, c.x, c.y, RIM_DARK); }
}
void openN;
void openS;
void openE;
void openW;
}
return rgba;
}
mkdirSync(OUT, { recursive: true });
for (let mask = 0; mask < 16; mask++)
{
const png = encodePng(paintCounter(mask));
writeFileSync(join(OUT, `${mask}.png`), png);
}
// Keep legacy fallback name pointing at isolated counter.
writeFileSync(join(OUT, "marketplace.png"), encodePng(paintCounter(0)));
console.log(`Wrote marketplace counter sprites 0–15 to ${OUT}`);
@@ -0,0 +1,199 @@/** * Generate 16×16 top-down wooden counter PNGs for neighbor-connect masks 0–15. * Perspective: orthographic top-down (grid-aligned, not diamond isometric). * Connections remove the shared edge rim so adjacent tiles read as one counter. */import { mkdirSync, writeFileSync } from "node:fs";import { deflateSync } from "node:zlib";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { NeighborBit } from "../../shared/world/neighborConnect.js";const SIZE = 16;const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/marketplace");/** Wood palette (RGBA). */const RIM = [92, 58, 32, 255];const RIM_DARK = [62, 38, 20, 255];const TOP = [196, 148, 78, 255];const TOP_LIGHT = [214, 170, 98, 255];const TOP_SHADE = [168, 120, 58, 255];const GRAIN = [180, 132, 64, 255];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 fillRect (rgba, x0, y0, x1, y1, color){ for (let y = y0; y <= y1; y++) { for (let x = x0; x <= x1; x++) { setPx(rgba, x, y, color); } }}function paintCounter (mask){ const rgba = new Uint8Array(SIZE * SIZE * 4); const connectN = (mask & NeighborBit.n) !== 0; const connectE = (mask & NeighborBit.e) !== 0; const connectS = (mask & NeighborBit.s) !== 0; const connectW = (mask & NeighborBit.w) !== 0; const topY0 = connectN ? 0 : 2; const topY1 = connectS ? SIZE - 1 : SIZE - 3; const topX0 = connectW ? 0 : 2; const topX1 = connectE ? SIZE - 1 : SIZE - 3; // Base fill transparent then rim body where not connected. for (let i = 0; i < rgba.length; i += 4) { rgba[i + 3] = 0; } // Outer rim (only on non-connected sides). if (!connectN) { fillRect(rgba, 0, 0, SIZE - 1, 1, RIM_DARK); } if (!connectS) { fillRect(rgba, 0, SIZE - 2, SIZE - 1, SIZE - 1, RIM_DARK); } if (!connectW) { fillRect(rgba, 0, 0, 1, SIZE - 1, RIM_DARK); } if (!connectE) { fillRect(rgba, SIZE - 2, 0, SIZE - 1, SIZE - 1, RIM_DARK); } // Inner rim bevel if (!connectN) { fillRect(rgba, topX0, 1, topX1, 1, RIM); } if (!connectS) { fillRect(rgba, topX0, SIZE - 2, topX1, SIZE - 2, RIM); } if (!connectW) { fillRect(rgba, 1, topY0, 1, topY1, RIM); } if (!connectE) { fillRect(rgba, SIZE - 2, topY0, SIZE - 2, topY1, RIM); } // Countertop fillRect(rgba, topX0, topY0, topX1, topY1, TOP); // Subtle grain / highlight for (let y = topY0; y <= topY1; y++) { for (let x = topX0; x <= topX1; x++) { if (((x + y * 3) % 7) === 0) { setPx(rgba, x, y, GRAIN); } if (y === topY0 && !connectN) { setPx(rgba, x, y, TOP_LIGHT); } if (y === topY1 && !connectS) { setPx(rgba, x, y, TOP_SHADE); } } } // Corner posts when both adjacent sides are free (standalone corners). const corners = [ { x: 0, y: 0, n: connectN, w: connectW }, { x: SIZE - 1, y: 0, n: connectN, e: connectE }, { x: 0, y: SIZE - 1, s: connectS, w: connectW }, { x: SIZE - 1, y: SIZE - 1, s: connectS, e: connectE } ]; for (const c of corners) { const openN = c.n === false || c.n == null; const openS = c.s === false || c.s == null; const openE = c.e === false || c.e == null; const openW = c.w === false || c.w == null; if ((c.n != null || c.s != null) && (c.e != null || c.w != null)) { const vertOpen = (c.n != null ? !c.n : !c.s); const horzOpen = (c.e != null ? !c.e : !c.w); if (vertOpen && horzOpen) { setPx(rgba, c.x, c.y, RIM_DARK); } } void openN; void openS; void openE; void openW; } return rgba;}mkdirSync(OUT, { recursive: true });for (let mask = 0; mask < 16; mask++){ const png = encodePng(paintCounter(mask)); writeFileSync(join(OUT, `${mask}.png`), png);}// Keep legacy fallback name pointing at isolated counter.writeFileSync(join(OUT, "marketplace.png"), encodePng(paintCounter(0)));console.log(`Wrote marketplace counter sprites 0–15 to ${OUT}`);@@ -0,0 +1,289 @@
/**
* Generate 16×16 magenta table PNGs for neighbor-connect masks 0–15.
* Reads the artist `wood.png`, remaps browns → magenta (tintable), then
* extends the tabletop along connected cardinals (no diagonals).
* Legs stay on free south edges; extra legs appear on long spans.
*/
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { deflateSync, inflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { NeighborBit } from "../../shared/world/neighborConnect.js";
const SIZE = 16;
const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/table");
const SOURCE = join(OUT, "wood.png");
/** Base tabletop AABB in the artist sprite (inclusive). */
const BASE = Object.freeze({
x0: 3,
x1: 12,
y0: 2,
y1: 11
});
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 decodePngRgba (buf)
{
let off = 8;
let w = 0;
let h = 0;
const idat = [];
while (off < buf.length)
{
const len = buf.readUInt32BE(off);
const type = buf.slice(off + 4, off + 8).toString("ascii");
const data = buf.slice(off + 8, off + 8 + len);
if (type === "IHDR")
{
w = data.readUInt32BE(0);
h = data.readUInt32BE(4);
}
else if (type === "IDAT")
{ idat.push(data); }
else if (type === "IEND")
{ break; }
off += 12 + len;
}
if (w !== SIZE || h !== SIZE)
{ throw new Error(`Expected ${SIZE}×${SIZE} PNG, got ${w}×${h}`); }
const raw = inflateSync(Buffer.concat(idat));
const stride = 1 + SIZE * 4;
const rgba = new Uint8Array(SIZE * SIZE * 4);
for (let y = 0; y < SIZE; y++)
{
for (let x = 0; x < SIZE; x++)
{
const i = y * stride + 1 + x * 4;
const o = (y * SIZE + x) * 4;
rgba[o] = raw[i];
rgba[o + 1] = raw[i + 1];
rgba[o + 2] = raw[i + 2];
rgba[o + 3] = raw[i + 3];
}
}
return rgba;
}
function getPx (rgba, x, y)
{
const i = (y * SIZE + x) * 4;
return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
}
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];
}
/** Remap any opaque pixel into the magenta tint family (R≈B, G<R). */
function toMagenta (r, g, b, a)
{
if (a < 8)
{ return [0, 0, 0, 0]; }
const L = Math.max(1, Math.max(r, g, b));
const minC = Math.min(r, g, b);
const chroma = (L - minC) / 255;
// Slight G softens grain; keep rims more saturated (low G).
const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22)));
return [L, Math.max(0, gMag), L, 255];
}
function magentaize (src)
{
const out = new Uint8Array(src.length);
for (let i = 0; i < src.length; i += 4)
{
const [r, g, b, a] = toMagenta(src[i], src[i + 1], src[i + 2], src[i + 3]);
out[i] = r;
out[i + 1] = g;
out[i + 2] = b;
out[i + 3] = a;
}
return out;
}
function sampleTop (base, x, y)
{
const sx = Math.min(BASE.x1, Math.max(BASE.x0, x));
const sy = Math.min(BASE.y1, Math.max(BASE.y0, y));
return getPx(base, sx, sy);
}
function drawLeg (rgba, base, anchorX, topY)
{
// Artist legs: 3×2 under the top at (4,12) and (9,12).
const pattern = [
[getPx(base, 4, 12), getPx(base, 5, 12), getPx(base, 6, 12)],
[getPx(base, 4, 13), getPx(base, 5, 13), getPx(base, 6, 13)]
];
for (let ly = 0; ly < 2; ly++)
{
const y = topY + 1 + ly;
if (y >= SIZE)
{ break; }
for (let lx = 0; lx < 3; lx++)
{ setPx(rgba, anchorX + lx, y, pattern[ly][lx]); }
}
}
function paintTable (mask, base)
{
const rgba = new Uint8Array(SIZE * SIZE * 4);
const connectN = (mask & NeighborBit.n) !== 0;
const connectE = (mask & NeighborBit.e) !== 0;
const connectS = (mask & NeighborBit.s) !== 0;
const connectW = (mask & NeighborBit.w) !== 0;
if (mask === 0)
{
rgba.set(base);
return rgba;
}
const topX0 = connectW ? 0 : BASE.x0;
const topX1 = connectE ? SIZE - 1 : BASE.x1;
const topY0 = connectN ? 0 : BASE.y0;
const topY1 = connectS ? SIZE - 1 : BASE.y1;
for (let y = topY0; y <= topY1; y++)
{
for (let x = topX0; x <= topX1; x++)
{
const onN = y === topY0 && !connectN;
const onS = y === topY1 && !connectS;
const onW = x === topX0 && !connectW;
const onE = x === topX1 && !connectE;
let color;
if (onN)
{ color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y0); }
else if (onS)
{ color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y1); }
else if (onW)
{ color = sampleTop(base, BASE.x0, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
else if (onE)
{ color = sampleTop(base, BASE.x1, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
else
{
// Interior: wrap the artist's fill so long spans keep grain.
const ix = BASE.x0 + 1 + ((x - topX0) % (BASE.x1 - BASE.x0 - 1));
const iy = BASE.y0 + 1 + ((y - topY0) % (BASE.y1 - BASE.y0 - 1));
color = sampleTop(base, ix, iy);
}
setPx(rgba, x, y, color);
}
}
// Front legs only when this tile is a south terminus (perspective).
if (!connectS && topY1 + 2 < SIZE)
{
const span = topX1 - topX0 + 1;
const anchors = [];
if (span <= 10)
{
anchors.push(topX0 + 1);
anchors.push(Math.max(topX0 + 1, topX1 - 3));
}
else
{
for (let x = topX0 + 1; x <= topX1 - 3; x += 5)
{ anchors.push(x); }
const last = topX1 - 3;
if (anchors[anchors.length - 1] !== last)
{ anchors.push(last); }
}
const seen = new Set();
for (const ax of anchors)
{
if (seen.has(ax))
{ continue; }
seen.add(ax);
drawLeg(rgba, base, ax, topY1);
}
}
return rgba;
}
const source = decodePngRgba(readFileSync(SOURCE));
const base = magentaize(source);
mkdirSync(OUT, { recursive: true });
// Replace artist wood.png with magenta base (same silhouette).
writeFileSync(SOURCE, encodePng(base));
for (let mask = 0; mask < 16; mask++)
{
writeFileSync(join(OUT, `${mask}.png`), encodePng(paintTable(mask, base)));
}
console.log(`Wrote magenta table sprites wood.png + 0–15 to ${OUT}`);
@@ -0,0 +1,289 @@/** * Generate 16×16 magenta table PNGs for neighbor-connect masks 0–15. * Reads the artist `wood.png`, remaps browns → magenta (tintable), then * extends the tabletop along connected cardinals (no diagonals). * Legs stay on free south edges; extra legs appear on long spans. */import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { deflateSync, inflateSync } from "node:zlib";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { NeighborBit } from "../../shared/world/neighborConnect.js";const SIZE = 16;const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/table");const SOURCE = join(OUT, "wood.png");/** Base tabletop AABB in the artist sprite (inclusive). */const BASE = Object.freeze({ x0: 3, x1: 12, y0: 2, y1: 11});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 decodePngRgba (buf){ let off = 8; let w = 0; let h = 0; const idat = []; while (off < buf.length) { const len = buf.readUInt32BE(off); const type = buf.slice(off + 4, off + 8).toString("ascii"); const data = buf.slice(off + 8, off + 8 + len); if (type === "IHDR") { w = data.readUInt32BE(0); h = data.readUInt32BE(4); } else if (type === "IDAT") { idat.push(data); } else if (type === "IEND") { break; } off += 12 + len; } if (w !== SIZE || h !== SIZE) { throw new Error(`Expected ${SIZE}×${SIZE} PNG, got ${w}×${h}`); } const raw = inflateSync(Buffer.concat(idat)); const stride = 1 + SIZE * 4; const rgba = new Uint8Array(SIZE * SIZE * 4); for (let y = 0; y < SIZE; y++) { for (let x = 0; x < SIZE; x++) { const i = y * stride + 1 + x * 4; const o = (y * SIZE + x) * 4; rgba[o] = raw[i]; rgba[o + 1] = raw[i + 1]; rgba[o + 2] = raw[i + 2]; rgba[o + 3] = raw[i + 3]; } } return rgba;}function getPx (rgba, x, y){ const i = (y * SIZE + x) * 4; return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];}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];}/** Remap any opaque pixel into the magenta tint family (R≈B, G<R). */function toMagenta (r, g, b, a){ if (a < 8) { return [0, 0, 0, 0]; } const L = Math.max(1, Math.max(r, g, b)); const minC = Math.min(r, g, b); const chroma = (L - minC) / 255; // Slight G softens grain; keep rims more saturated (low G). const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22))); return [L, Math.max(0, gMag), L, 255];}function magentaize (src){ const out = new Uint8Array(src.length); for (let i = 0; i < src.length; i += 4) { const [r, g, b, a] = toMagenta(src[i], src[i + 1], src[i + 2], src[i + 3]); out[i] = r; out[i + 1] = g; out[i + 2] = b; out[i + 3] = a; } return out;}function sampleTop (base, x, y){ const sx = Math.min(BASE.x1, Math.max(BASE.x0, x)); const sy = Math.min(BASE.y1, Math.max(BASE.y0, y)); return getPx(base, sx, sy);}function drawLeg (rgba, base, anchorX, topY){ // Artist legs: 3×2 under the top at (4,12) and (9,12). const pattern = [ [getPx(base, 4, 12), getPx(base, 5, 12), getPx(base, 6, 12)], [getPx(base, 4, 13), getPx(base, 5, 13), getPx(base, 6, 13)] ]; for (let ly = 0; ly < 2; ly++) { const y = topY + 1 + ly; if (y >= SIZE) { break; } for (let lx = 0; lx < 3; lx++) { setPx(rgba, anchorX + lx, y, pattern[ly][lx]); } }}function paintTable (mask, base){ const rgba = new Uint8Array(SIZE * SIZE * 4); const connectN = (mask & NeighborBit.n) !== 0; const connectE = (mask & NeighborBit.e) !== 0; const connectS = (mask & NeighborBit.s) !== 0; const connectW = (mask & NeighborBit.w) !== 0; if (mask === 0) { rgba.set(base); return rgba; } const topX0 = connectW ? 0 : BASE.x0; const topX1 = connectE ? SIZE - 1 : BASE.x1; const topY0 = connectN ? 0 : BASE.y0; const topY1 = connectS ? SIZE - 1 : BASE.y1; for (let y = topY0; y <= topY1; y++) { for (let x = topX0; x <= topX1; x++) { const onN = y === topY0 && !connectN; const onS = y === topY1 && !connectS; const onW = x === topX0 && !connectW; const onE = x === topX1 && !connectE; let color; if (onN) { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y0); } else if (onS) { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y1); } else if (onW) { color = sampleTop(base, BASE.x0, Math.min(BASE.y1, Math.max(BASE.y0, y))); } else if (onE) { color = sampleTop(base, BASE.x1, Math.min(BASE.y1, Math.max(BASE.y0, y))); } else { // Interior: wrap the artist's fill so long spans keep grain. const ix = BASE.x0 + 1 + ((x - topX0) % (BASE.x1 - BASE.x0 - 1)); const iy = BASE.y0 + 1 + ((y - topY0) % (BASE.y1 - BASE.y0 - 1)); color = sampleTop(base, ix, iy); } setPx(rgba, x, y, color); } } // Front legs only when this tile is a south terminus (perspective). if (!connectS && topY1 + 2 < SIZE) { const span = topX1 - topX0 + 1; const anchors = []; if (span <= 10) { anchors.push(topX0 + 1); anchors.push(Math.max(topX0 + 1, topX1 - 3)); } else { for (let x = topX0 + 1; x <= topX1 - 3; x += 5) { anchors.push(x); } const last = topX1 - 3; if (anchors[anchors.length - 1] !== last) { anchors.push(last); } } const seen = new Set(); for (const ax of anchors) { if (seen.has(ax)) { continue; } seen.add(ax); drawLeg(rgba, base, ax, topY1); } } return rgba;}const source = decodePngRgba(readFileSync(SOURCE));const base = magentaize(source);mkdirSync(OUT, { recursive: true });// Replace artist wood.png with magenta base (same silhouette).writeFileSync(SOURCE, encodePng(base));for (let mask = 0; mask < 16; mask++){ writeFileSync(join(OUT, `${mask}.png`), encodePng(paintTable(mask, base)));}console.log(`Wrote magenta table sprites wood.png + 0–15 to ${OUT}`);@@ -17,6 +17,12 @@ import {
placeableStatesForType
} from "/shared/world/season.js";
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
import {
computeNeighborConnectMask,
composeNeighborConnectState,
definitionUsesNeighborConnect,
neighborConnectBlocksMatch
} from "/shared/world/neighborConnect.js";
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
import { WorldView } from "../render/worldView.js";
@@ -167,7 +173,18 @@ function paintAt (localX, localY)
if (tool.kind === "ground")
{ draft.grounds[index] = { typeId: tool.typeId, state }; }
else if (tool.kind === "erase")
{ draft.blocks[index] = null; }
{
const removed = draft.blocks[index];
draft.blocks[index] = null;
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
ground: draft.grounds[index],
block: draft.blocks[index],
light: draft.light[index]
});
if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
{ refreshNeighborConnect(localX, localY, removed.typeId); }
return;
}
else if (tool.kind === "spawner")
{
const existing = spawnerAt(localX, localY);
@@ -188,7 +205,21 @@ function paintAt (localX, localY)
return;
}
else
{ draft.blocks[index] = { typeId: tool.typeId, state, config: null }; }
{
const def = BLOCK_DEFINITIONS[tool.typeId];
const nextState = definitionUsesNeighborConnect(def)
? composeNeighborConnectState(def, state, 0)
: state;
draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
ground: draft.grounds[index],
block: draft.blocks[index],
light: draft.light[index]
});
if (definitionUsesNeighborConnect(def))
{ refreshNeighborConnect(localX, localY, tool.typeId); }
return;
}
view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
ground: draft.grounds[index],
block: draft.blocks[index],
@@ -196,6 +227,41 @@ function paintAt (localX, localY)
});
}
/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
function refreshNeighborConnect (localX, localY, typeId)
{
const def = BLOCK_DEFINITIONS[typeId];
if (!draft || !definitionUsesNeighborConnect(def))
{ return; }
const cells = [[localX, localY]];
for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
{ cells.push([localX + dx, localY + dy]); }
for (const [lx, ly] of cells)
{
if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
{ continue; }
const index = ly * CHUNK_SIZE + lx;
const block = draft.blocks[index];
if (!block || block.typeId !== typeId)
{ continue; }
const mask = computeNeighborConnectMask((dx, dy) =>
{
const nx = lx + dx;
const ny = ly + dy;
if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
{ return false; }
const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
return neighborConnectBlocksMatch(block, neighbor, def);
});
block.state = composeNeighborConnectState(def, block.state, mask);
view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
ground: draft.grounds[index],
block: draft.blocks[index],
light: draft.light[index]
});
}
}
function updateRevisionUI ()
{
const applyBtn = $("apply");
@@ -659,6 +725,8 @@ function cycleToolState (direction)
{ return; }
const layer = tool.kind === "ground" ? "ground" : "block";
const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
if (definitionUsesNeighborConnect(def))
{ return; }
const allStates = statesForType(catalog, layer, def.key);
const seasonal = seasonalCycleStates(allStates);
const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
@@ -17,6 +17,12 @@ import { placeableStatesForType placeableStatesForType} from "/shared/world/season.js";} from "/shared/world/season.js";import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";import { computeNeighborConnectMask, composeNeighborConnectState, definitionUsesNeighborConnect, neighborConnectBlocksMatch} from "/shared/world/neighborConnect.js";import { GameSocket, defaultSocketUrl } from "../net/socket.js";import { GameSocket, defaultSocketUrl } from "../net/socket.js";import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";import { WorldView } from "../render/worldView.js";import { WorldView } from "../render/worldView.js";@@ -167,7 +173,18 @@ function paintAt (localX, localY) if (tool.kind === "ground") if (tool.kind === "ground") { draft.grounds[index] = { typeId: tool.typeId, state }; } { draft.grounds[index] = { typeId: tool.typeId, state }; } else if (tool.kind === "erase") else if (tool.kind === "erase") { draft.blocks[index] = null; } { const removed = draft.blocks[index]; draft.blocks[index] = null; view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId])) { refreshNeighborConnect(localX, localY, removed.typeId); } return; } else if (tool.kind === "spawner") else if (tool.kind === "spawner") { { const existing = spawnerAt(localX, localY); const existing = spawnerAt(localX, localY);@@ -188,7 +205,21 @@ function paintAt (localX, localY) return; return; } } else else { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; } { const def = BLOCK_DEFINITIONS[tool.typeId]; const nextState = definitionUsesNeighborConnect(def) ? composeNeighborConnectState(def, state, 0) : state; draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null }; view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); if (definitionUsesNeighborConnect(def)) { refreshNeighborConnect(localX, localY, tool.typeId); } return; } view.updateAuthoredTile(chunkX, chunkY, localX, localY, { view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], ground: draft.grounds[index], block: draft.blocks[index], block: draft.blocks[index],@@ -196,6 +227,41 @@ function paintAt (localX, localY) }); });}}/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */function refreshNeighborConnect (localX, localY, typeId){ const def = BLOCK_DEFINITIONS[typeId]; if (!draft || !definitionUsesNeighborConnect(def)) { return; } const cells = [[localX, localY]]; for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) { cells.push([localX + dx, localY + dy]); } for (const [lx, ly] of cells) { if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE) { continue; } const index = ly * CHUNK_SIZE + lx; const block = draft.blocks[index]; if (!block || block.typeId !== typeId) { continue; } const mask = computeNeighborConnectMask((dx, dy) => { const nx = lx + dx; const ny = ly + dy; if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE) { return false; } const neighbor = draft.blocks[ny * CHUNK_SIZE + nx]; return neighborConnectBlocksMatch(block, neighbor, def); }); block.state = composeNeighborConnectState(def, block.state, mask); view.updateAuthoredTile(chunkX, chunkY, lx, ly, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); }}function updateRevisionUI ()function updateRevisionUI (){{ const applyBtn = $("apply"); const applyBtn = $("apply");@@ -659,6 +725,8 @@ function cycleToolState (direction) { return; } { return; } const layer = tool.kind === "ground" ? "ground" : "block"; const layer = tool.kind === "ground" ? "ground" : "block"; const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; if (definitionUsesNeighborConnect(def)) { return; } const allStates = statesForType(catalog, layer, def.key); const allStates = statesForType(catalog, layer, def.key); const seasonal = seasonalCycleStates(allStates); const seasonal = seasonalCycleStates(allStates); const states = seasonal ?? placeableStatesForType(catalog, layer, def.key); const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);@@ -5,8 +5,10 @@ import {
listSpawnableMobTypes,
normalizeSpawnerConfig,
MobId,
isHumanoidMob
isHumanoidMob,
isCentralExchangeSpawner
} from "/shared/definitions/mobs.js";
import { centralExchangeStaffCount } from "/shared/market/exchange.js";
import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
@@ -152,10 +154,21 @@ export function initTileConfigModal ({ onSave, onRemove })
const wrap = document.createElement("div");
wrap.className = "spawner-humanoid-fields";
wrap.dataset.humanoid = "1";
wrap.append(
field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
field("Sex", sexSelect("sex", config.sex))
);
const exchange = isCentralExchangeSpawner(config);
if (exchange)
{
const note = document.createElement("p");
note.className = "hint";
note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
wrap.append(note);
}
else
{
wrap.append(
field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
field("Sex", sexSelect("sex", config.sex))
);
}
for (const slot of EQUIPMENT_SLOTS)
{
wrap.append(field(
@@ -163,47 +176,52 @@ export function initTileConfigModal ({ onSave, onRemove })
equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
));
}
wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
if (!exchange)
{
wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
const sellsHeader = document.createElement("div");
sellsHeader.className = "spawner-sells-header";
const sellsTitle = document.createElement("strong");
sellsTitle.textContent = "Sells";
const addBtn = document.createElement("button");
addBtn.type = "button";
addBtn.textContent = "+";
addBtn.title = "Add item";
addBtn.addEventListener("click", () => openItemSearch());
sellsHeader.append(sellsTitle, addBtn);
wrap.append(sellsHeader);
const sellsHeader = document.createElement("div");
sellsHeader.className = "spawner-sells-header";
const sellsTitle = document.createElement("strong");
sellsTitle.textContent = "Sells";
const addBtn = document.createElement("button");
addBtn.type = "button";
addBtn.textContent = "+";
addBtn.title = "Add item";
addBtn.addEventListener("click", () => openItemSearch());
sellsHeader.append(sellsTitle, addBtn);
wrap.append(sellsHeader);
const list = document.createElement("div");
list.className = "spawner-sells-list";
list.dataset.sellsList = "1";
wrap.append(list);
const list = document.createElement("div");
list.className = "spawner-sells-list";
list.dataset.sellsList = "1";
wrap.append(list);
const buysLabel = document.createElement("label");
buysLabel.className = "spawner-buys-row";
const buys = document.createElement("input");
buys.type = "checkbox";
buys.name = "buysItems";
buys.checked = !!config.buysItems;
buysLabel.append(buys, document.createTextNode(" Buys items"));
wrap.append(buysLabel);
const buysLabel = document.createElement("label");
buysLabel.className = "spawner-buys-row";
const buys = document.createElement("input");
buys.type = "checkbox";
buys.name = "buysItems";
buys.checked = !!config.buysItems;
buysLabel.append(buys, document.createTextNode(" Buys items"));
wrap.append(buysLabel);
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
wrap.append(hint);
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock.";
wrap.append(hint);
sellsDraft = (config.sells ?? []).map((line) =>
{
if (line && typeof line === "object")
{ return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
return { itemId: line | 0, quantity: 0 };
}).filter((line) => line.itemId > 0);
sellsDraft = (config.sells ?? []).map((line) =>
{
if (line && typeof line === "object")
{ return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
return { itemId: line | 0, quantity: 0 };
}).filter((line) => line.itemId > 0);
queueMicrotask(() => renderSellsList());
queueMicrotask(() => renderSellsList());
}
else
{ sellsDraft = []; }
return wrap;
}
@@ -217,8 +235,16 @@ export function initTileConfigModal ({ onSave, onRemove })
return;
}
form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
mobTypeId: MobId.humanoid
mobTypeId: mobTypeId || MobId.humanoid
}, "spawner")));
const maxAlive = form.querySelector('[name="maxAlive"]');
if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
{
maxAlive.value = String(centralExchangeStaffCount());
maxAlive.disabled = true;
}
else if (maxAlive)
{ maxAlive.disabled = false; }
}
function openSpawner (ctx)
@@ -289,7 +315,8 @@ export function initTileConfigModal ({ onSave, onRemove })
equipment,
sells: sellsDraft,
buysItems: data.get("buysItems") === "on",
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
}, context.config.spawnerId));
show(false);
});
@@ -5,8 +5,10 @@ import { listSpawnableMobTypes, listSpawnableMobTypes, normalizeSpawnerConfig, normalizeSpawnerConfig, MobId, MobId, isHumanoidMob isHumanoidMob, isCentralExchangeSpawner} from "/shared/definitions/mobs.js";} from "/shared/definitions/mobs.js";import { centralExchangeStaffCount } from "/shared/market/exchange.js";import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";import { listNpcShopSellableItems } from "/shared/shop/pricing.js";import { listNpcShopSellableItems } from "/shared/shop/pricing.js";@@ -152,10 +154,21 @@ export function initTileConfigModal ({ onSave, onRemove }) const wrap = document.createElement("div"); const wrap = document.createElement("div"); wrap.className = "spawner-humanoid-fields"; wrap.className = "spawner-humanoid-fields"; wrap.dataset.humanoid = "1"; wrap.dataset.humanoid = "1"; wrap.append( const exchange = isCentralExchangeSpawner(config); field("Display name", textInput("displayName", config.displayName || "Shopkeeper")), if (exchange) field("Sex", sexSelect("sex", config.sex)) { ); const note = document.createElement("p"); note.className = "hint"; note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`; wrap.append(note); } else { wrap.append( field("Display name", textInput("displayName", config.displayName || "Shopkeeper")), field("Sex", sexSelect("sex", config.sex)) ); } for (const slot of EQUIPMENT_SLOTS) for (const slot of EQUIPMENT_SLOTS) { { wrap.append(field( wrap.append(field(@@ -163,47 +176,52 @@ export function initTileConfigModal ({ onSave, onRemove }) equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null) equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null) )); )); } } wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01))); if (!exchange) { wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01))); const sellsHeader = document.createElement("div"); const sellsHeader = document.createElement("div"); sellsHeader.className = "spawner-sells-header"; sellsHeader.className = "spawner-sells-header"; const sellsTitle = document.createElement("strong"); const sellsTitle = document.createElement("strong"); sellsTitle.textContent = "Sells"; sellsTitle.textContent = "Sells"; const addBtn = document.createElement("button"); const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.type = "button"; addBtn.textContent = "+"; addBtn.textContent = "+"; addBtn.title = "Add item"; addBtn.title = "Add item"; addBtn.addEventListener("click", () => openItemSearch()); addBtn.addEventListener("click", () => openItemSearch()); sellsHeader.append(sellsTitle, addBtn); sellsHeader.append(sellsTitle, addBtn); wrap.append(sellsHeader); wrap.append(sellsHeader); const list = document.createElement("div"); const list = document.createElement("div"); list.className = "spawner-sells-list"; list.className = "spawner-sells-list"; list.dataset.sellsList = "1"; list.dataset.sellsList = "1"; wrap.append(list); wrap.append(list); const buysLabel = document.createElement("label"); const buysLabel = document.createElement("label"); buysLabel.className = "spawner-buys-row"; buysLabel.className = "spawner-buys-row"; const buys = document.createElement("input"); const buys = document.createElement("input"); buys.type = "checkbox"; buys.type = "checkbox"; buys.name = "buysItems"; buys.name = "buysItems"; buys.checked = !!config.buysItems; buys.checked = !!config.buysItems; buysLabel.append(buys, document.createTextNode(" Buys items")); buysLabel.append(buys, document.createTextNode(" Buys items")); wrap.append(buysLabel); wrap.append(buysLabel); const hint = document.createElement("p"); const hint = document.createElement("p"); hint.className = "hint"; hint.className = "hint"; hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock."; hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock."; wrap.append(hint); wrap.append(hint); sellsDraft = (config.sells ?? []).map((line) => sellsDraft = (config.sells ?? []).map((line) => { { if (line && typeof line === "object") if (line && typeof line === "object") { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; } { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; } return { itemId: line | 0, quantity: 0 }; return { itemId: line | 0, quantity: 0 }; }).filter((line) => line.itemId > 0); }).filter((line) => line.itemId > 0); queueMicrotask(() => renderSellsList()); queueMicrotask(() => renderSellsList()); } else { sellsDraft = []; } return wrap; return wrap; } }@@ -217,8 +235,16 @@ export function initTileConfigModal ({ onSave, onRemove }) return; return; } } form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({ form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({ mobTypeId: MobId.humanoid mobTypeId: mobTypeId || MobId.humanoid }, "spawner"))); }, "spawner"))); const maxAlive = form.querySelector('[name="maxAlive"]'); if (maxAlive && isCentralExchangeSpawner({ mobTypeId })) { maxAlive.value = String(centralExchangeStaffCount()); maxAlive.disabled = true; } else if (maxAlive) { maxAlive.disabled = false; } } } function openSpawner (ctx) function openSpawner (ctx)@@ -289,7 +315,8 @@ export function initTileConfigModal ({ onSave, onRemove }) equipment, equipment, sells: sellsDraft, sells: sellsDraft, buysItems: data.get("buysItems") === "on", buysItems: data.get("buysItems") === "on", hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9) hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9), centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")) }, context.config.spawnerId)); }, context.config.spawnerId)); show(false); show(false); }); });@@ -4,6 +4,8 @@ import {
itemAssetPathForStack,
formatQuantity
} from "/shared/definitions/items.js";
import { marketOrderListingFee } from "/shared/market/exchange.js";
import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
import { applyItemIcon } from "../render/potionIcon.js";
export function initMarket ({
@@ -20,25 +22,54 @@ export function initMarket ({
const ordersEl = document.getElementById("market-orders");
const catalogEl = document.getElementById("market-catalog");
const sellList = document.getElementById("market-sell-list");
const sellSelected = document.getElementById("market-sell-selected");
const buyItem = document.getElementById("market-buy-item");
const buySearch = document.getElementById("market-buy-search");
const buyQty = document.getElementById("market-buy-qty");
const buyMax = document.getElementById("market-buy-max");
const buyFee = document.getElementById("market-buy-fee");
const sellQty = document.getElementById("market-sell-qty");
const sellMin = document.getElementById("market-sell-min");
const sellFee = document.getElementById("market-sell-fee");
const coinsEl = document.getElementById("market-coins");
const hintEl = document.getElementById("market-hint");
const tabs = [...document.querySelectorAll(".market-tab")];
const panes = [...document.querySelectorAll(".market-pane")];
let open = false;
let catalog = [];
let orders = [];
let searchHits = [];
let selectedSellSlot = null;
let selectedBuyItemId = null;
let activeTab = "orders";
let sellQtyLocked = false;
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; }
if (tab === "sell")
{ renderSellables(); }
if (tab === "buy")
{ updateBuyFee(); }
if (tab === "orders")
{ renderOrders(); }
}
for (const button of tabs)
{
button.addEventListener("click", () => setTab(button.dataset.tab));
}
document.getElementById("market-close")?.addEventListener("click", () => close());
backdrop?.addEventListener("mousedown", (event) =>
{
@@ -52,6 +83,19 @@ export function initMarket ({
suppressWorldClick();
});
buySearch?.addEventListener("keydown", (event) =>
{
if (event.key !== "Enter")
{ return; }
event.preventDefault();
runBuySearch(buySearch.value ?? "");
});
buyQty?.addEventListener("input", () => updateBuyFee());
buyMax?.addEventListener("input", () => updateBuyFee());
sellQty?.addEventListener("input", () => updateSellFee());
sellMin?.addEventListener("input", () => updateSellFee());
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
{
if (selectedBuyItemId == null)
@@ -88,6 +132,53 @@ export function initMarket ({
socket.send({ type: MessageType.closeMarket });
}
function runBuySearch (query)
{
const needle = String(query ?? "").trim().toLowerCase();
selectedBuyItemId = null;
if (buyItem)
{ buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }
if (!needle)
{
searchHits = [];
renderCatalog();
updateBuyFee();
return;
}
searchHits = catalog
.filter((entry) => entry.displayName.toLowerCase().includes(needle))
.slice(0, 10);
renderCatalog();
updateBuyFee();
}
function updateBuyFee ()
{
const qty = Math.max(1, buyQty?.valueAsNumber || 1);
const max = Math.max(1, buyMax?.valueAsNumber || 1);
const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty);
const escrow = selectedBuyItemId == null ? 0 : max * qty;
if (buyFee)
{
buyFee.textContent = selectedBuyItemId == null
? ""
: `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)} (3%, non-refundable)`;
}
}
function updateSellFee ()
{
const qty = Math.max(1, sellQty?.valueAsNumber || 1);
const min = Math.max(1, sellMin?.valueAsNumber || 1);
const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty);
if (sellFee)
{
sellFee.textContent = selectedSellSlot == null
? ""
: `Listing fee ${formatQuantity(fee)} (3% of min value, non-refundable)`;
}
}
function renderOrders ()
{
ordersEl.replaceChildren();
@@ -104,7 +195,10 @@ export function initMarket ({
const row = document.createElement("div");
row.className = "market-order-row";
const label = document.createElement("span");
label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`;
const priceLabel = order.side === "buy"
? `max ${order.limitUnitPrice}`
: `min ${order.limitUnitPrice}`;
label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`;
const cancel = document.createElement("button");
cancel.type = "button";
cancel.textContent = "Cancel";
@@ -123,7 +217,17 @@ export function initMarket ({
function renderCatalog ()
{
catalogEl.replaceChildren();
for (const entry of catalog)
if (!searchHits.length)
{
const empty = document.createElement("p");
empty.className = "hint";
empty.textContent = (buySearch?.value ?? "").trim()
? "No matching items."
: "Press Enter to search.";
catalogEl.append(empty);
return;
}
for (const entry of searchHits)
{
const row = document.createElement("button");
row.type = "button";
@@ -139,6 +243,7 @@ export function initMarket ({
if (buyMax && !(buyMax.valueAsNumber > 0))
{ buyMax.value = String(entry.hintPrice); }
renderCatalog();
updateBuyFee();
});
catalogEl.append(row);
}
@@ -152,6 +257,9 @@ export function initMarket ({
{
if (!slot || slot.itemId == null)
{ return; }
const listing = resolveMarketSellListing(slot);
if (!listing)
{ return; }
const def = itemDefinition(slot.itemId);
if (!def || def.marketplaceSellable === false)
{ return; }
@@ -164,14 +272,33 @@ export function initMarket ({
icon.alt = "";
applyItemIcon(icon, itemAssetPathForStack(slot));
const label = document.createElement("span");
label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
if (listing.isCheque)
{
label.textContent = `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}`;
}
else
{
label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
}
row.append(icon, label);
row.addEventListener("click", () =>
{
selectedSellSlot = slotIndex;
sellQtyLocked = !!listing.quantityLocked;
if (sellQty)
{ sellQty.value = "1"; }
{
sellQty.value = String(listing.quantity);
sellQty.readOnly = sellQtyLocked;
sellQty.disabled = sellQtyLocked;
}
if (sellSelected)
{
sellSelected.textContent = listing.isCheque
? `Selling cheque for ${listing.quantity}× ${listing.displayName} (quantity locked)`
: `Selling ${itemDisplayName(slot)}`;
}
renderSellables();
updateSellFee();
});
sellList.append(row);
});
@@ -179,9 +306,19 @@ export function initMarket ({
function refreshChrome ()
{
const slots = getInventorySlots?.() ?? [];
const funds = countMarketFunds(slots);
const loose = getCoinCount?.() ?? 0;
if (coinsEl)
{ coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; }
renderSellables();
{
coinsEl.textContent = funds === loose
? `Funds: ${formatQuantity(funds)}`
: `Funds: ${formatQuantity(funds)} (coins + coin cheques)`;
}
if (activeTab === "sell")
{ renderSellables(); }
updateBuyFee();
updateSellFee();
}
return {
@@ -190,16 +327,29 @@ export function initMarket ({
open = true;
orders = payload.orders ?? [];
catalog = payload.catalog ?? [];
searchHits = [];
selectedSellSlot = null;
selectedBuyItemId = null;
sellQtyLocked = false;
if (sellQty)
{
sellQty.readOnly = false;
sellQty.disabled = false;
sellQty.value = "1";
}
if (buySearch)
{ buySearch.value = ""; }
if (title)
{ title.textContent = payload.displayName || "Central Exchange"; }
if (hintEl)
{
hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month.";
hintEl.textContent = "Placing an order costs a 3% listing fee (non-refundable). Matches are private; unfilled orders expire after one month.";
}
if (backdrop)
{ backdrop.hidden = false; }
if (panel)
{ panel.hidden = false; }
setTab("orders");
renderOrders();
renderCatalog();
refreshChrome();
@@ -4,6 +4,8 @@ import { itemAssetPathForStack, itemAssetPathForStack, formatQuantity formatQuantity} from "/shared/definitions/items.js";} from "/shared/definitions/items.js";import { marketOrderListingFee } from "/shared/market/exchange.js";import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";import { applyItemIcon } from "../render/potionIcon.js";import { applyItemIcon } from "../render/potionIcon.js";export function initMarket ({export function initMarket ({@@ -20,25 +22,54 @@ export function initMarket ({ const ordersEl = document.getElementById("market-orders"); const ordersEl = document.getElementById("market-orders"); const catalogEl = document.getElementById("market-catalog"); const catalogEl = document.getElementById("market-catalog"); const sellList = document.getElementById("market-sell-list"); const sellList = document.getElementById("market-sell-list"); const sellSelected = document.getElementById("market-sell-selected"); const buyItem = document.getElementById("market-buy-item"); const buyItem = document.getElementById("market-buy-item"); const buySearch = document.getElementById("market-buy-search"); const buyQty = document.getElementById("market-buy-qty"); const buyQty = document.getElementById("market-buy-qty"); const buyMax = document.getElementById("market-buy-max"); const buyMax = document.getElementById("market-buy-max"); const buyFee = document.getElementById("market-buy-fee"); const sellQty = document.getElementById("market-sell-qty"); const sellQty = document.getElementById("market-sell-qty"); const sellMin = document.getElementById("market-sell-min"); const sellMin = document.getElementById("market-sell-min"); const sellFee = document.getElementById("market-sell-fee"); const coinsEl = document.getElementById("market-coins"); const coinsEl = document.getElementById("market-coins"); const hintEl = document.getElementById("market-hint"); const hintEl = document.getElementById("market-hint"); const tabs = [...document.querySelectorAll(".market-tab")]; const panes = [...document.querySelectorAll(".market-pane")]; let open = false; let open = false; let catalog = []; let catalog = []; let orders = []; let orders = []; let searchHits = []; let selectedSellSlot = null; let selectedSellSlot = null; let selectedBuyItemId = null; let selectedBuyItemId = null; let activeTab = "orders"; let sellQtyLocked = false; function suppressWorldClick () function suppressWorldClick () { { onSuppressWorldClick?.(); 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; } if (tab === "sell") { renderSellables(); } if (tab === "buy") { updateBuyFee(); } if (tab === "orders") { renderOrders(); } } for (const button of tabs) { button.addEventListener("click", () => setTab(button.dataset.tab)); } document.getElementById("market-close")?.addEventListener("click", () => close()); document.getElementById("market-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("mousedown", (event) => backdrop?.addEventListener("mousedown", (event) => { {@@ -52,6 +83,19 @@ export function initMarket ({ suppressWorldClick(); suppressWorldClick(); }); }); buySearch?.addEventListener("keydown", (event) => { if (event.key !== "Enter") { return; } event.preventDefault(); runBuySearch(buySearch.value ?? ""); }); buyQty?.addEventListener("input", () => updateBuyFee()); buyMax?.addEventListener("input", () => updateBuyFee()); sellQty?.addEventListener("input", () => updateSellFee()); sellMin?.addEventListener("input", () => updateSellFee()); document.getElementById("market-buy-confirm")?.addEventListener("click", () => document.getElementById("market-buy-confirm")?.addEventListener("click", () => { { if (selectedBuyItemId == null) if (selectedBuyItemId == null)@@ -88,6 +132,53 @@ export function initMarket ({ socket.send({ type: MessageType.closeMarket }); socket.send({ type: MessageType.closeMarket }); } } function runBuySearch (query) { const needle = String(query ?? "").trim().toLowerCase(); selectedBuyItemId = null; if (buyItem) { buyItem.textContent = needle ? "Select an item" : "Search and select an item"; } if (!needle) { searchHits = []; renderCatalog(); updateBuyFee(); return; } searchHits = catalog .filter((entry) => entry.displayName.toLowerCase().includes(needle)) .slice(0, 10); renderCatalog(); updateBuyFee(); } function updateBuyFee () { const qty = Math.max(1, buyQty?.valueAsNumber || 1); const max = Math.max(1, buyMax?.valueAsNumber || 1); const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty); const escrow = selectedBuyItemId == null ? 0 : max * qty; if (buyFee) { buyFee.textContent = selectedBuyItemId == null ? "" : `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)} (3%, non-refundable)`; } } function updateSellFee () { const qty = Math.max(1, sellQty?.valueAsNumber || 1); const min = Math.max(1, sellMin?.valueAsNumber || 1); const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty); if (sellFee) { sellFee.textContent = selectedSellSlot == null ? "" : `Listing fee ${formatQuantity(fee)} (3% of min value, non-refundable)`; } } function renderOrders () function renderOrders () { { ordersEl.replaceChildren(); ordersEl.replaceChildren();@@ -104,7 +195,10 @@ export function initMarket ({ const row = document.createElement("div"); const row = document.createElement("div"); row.className = "market-order-row"; row.className = "market-order-row"; const label = document.createElement("span"); const label = document.createElement("span"); label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`; const priceLabel = order.side === "buy" ? `max ${order.limitUnitPrice}` : `min ${order.limitUnitPrice}`; label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`; const cancel = document.createElement("button"); const cancel = document.createElement("button"); cancel.type = "button"; cancel.type = "button"; cancel.textContent = "Cancel"; cancel.textContent = "Cancel";@@ -123,7 +217,17 @@ export function initMarket ({ function renderCatalog () function renderCatalog () { { catalogEl.replaceChildren(); catalogEl.replaceChildren(); for (const entry of catalog) if (!searchHits.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = (buySearch?.value ?? "").trim() ? "No matching items." : "Press Enter to search."; catalogEl.append(empty); return; } for (const entry of searchHits) { { const row = document.createElement("button"); const row = document.createElement("button"); row.type = "button"; row.type = "button";@@ -139,6 +243,7 @@ export function initMarket ({ if (buyMax && !(buyMax.valueAsNumber > 0)) if (buyMax && !(buyMax.valueAsNumber > 0)) { buyMax.value = String(entry.hintPrice); } { buyMax.value = String(entry.hintPrice); } renderCatalog(); renderCatalog(); updateBuyFee(); }); }); catalogEl.append(row); catalogEl.append(row); } }@@ -152,6 +257,9 @@ export function initMarket ({ { { if (!slot || slot.itemId == null) if (!slot || slot.itemId == null) { return; } { return; } const listing = resolveMarketSellListing(slot); if (!listing) { return; } const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); if (!def || def.marketplaceSellable === false) if (!def || def.marketplaceSellable === false) { return; } { return; }@@ -164,14 +272,33 @@ export function initMarket ({ icon.alt = ""; icon.alt = ""; applyItemIcon(icon, itemAssetPathForStack(slot)); applyItemIcon(icon, itemAssetPathForStack(slot)); const label = document.createElement("span"); const label = document.createElement("span"); label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`; if (listing.isCheque) { label.textContent = `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}`; } else { label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`; } row.append(icon, label); row.append(icon, label); row.addEventListener("click", () => row.addEventListener("click", () => { { selectedSellSlot = slotIndex; selectedSellSlot = slotIndex; sellQtyLocked = !!listing.quantityLocked; if (sellQty) if (sellQty) { sellQty.value = "1"; } { sellQty.value = String(listing.quantity); sellQty.readOnly = sellQtyLocked; sellQty.disabled = sellQtyLocked; } if (sellSelected) { sellSelected.textContent = listing.isCheque ? `Selling cheque for ${listing.quantity}× ${listing.displayName} (quantity locked)` : `Selling ${itemDisplayName(slot)}`; } renderSellables(); renderSellables(); updateSellFee(); }); }); sellList.append(row); sellList.append(row); }); });@@ -179,9 +306,19 @@ export function initMarket ({ function refreshChrome () function refreshChrome () { { const slots = getInventorySlots?.() ?? []; const funds = countMarketFunds(slots); const loose = getCoinCount?.() ?? 0; if (coinsEl) if (coinsEl) { coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; } { renderSellables(); coinsEl.textContent = funds === loose ? `Funds: ${formatQuantity(funds)}` : `Funds: ${formatQuantity(funds)} (coins + coin cheques)`; } if (activeTab === "sell") { renderSellables(); } updateBuyFee(); updateSellFee(); } } return { return {@@ -190,16 +327,29 @@ export function initMarket ({ open = true; open = true; orders = payload.orders ?? []; orders = payload.orders ?? []; catalog = payload.catalog ?? []; catalog = payload.catalog ?? []; searchHits = []; selectedSellSlot = null; selectedBuyItemId = null; sellQtyLocked = false; if (sellQty) { sellQty.readOnly = false; sellQty.disabled = false; sellQty.value = "1"; } if (buySearch) { buySearch.value = ""; } if (title) if (title) { title.textContent = payload.displayName || "Central Exchange"; } { title.textContent = payload.displayName || "Central Exchange"; } if (hintEl) if (hintEl) { { hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month."; hintEl.textContent = "Placing an order costs a 3% listing fee (non-refundable). Matches are private; unfilled orders expire after one month."; } } if (backdrop) if (backdrop) { backdrop.hidden = false; } { backdrop.hidden = false; } if (panel) if (panel) { panel.hidden = false; } { panel.hidden = false; } setTab("orders"); renderOrders(); renderOrders(); renderCatalog(); renderCatalog(); refreshChrome(); refreshChrome();@@ -295,6 +295,16 @@ export class WorldView
if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
{ this.despawnGroundItem(id); }
}
// Server only sends unsubscribeChunk (not per-entity despawns) when a chunk
// leaves the 3×3 interest set — drop mobs/players that still sit on that chunk.
for (const [id, entity] of [...this.entities.entries()])
{
if (id === this.localEntityId)
{ continue; }
if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
&& Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
{ this.despawnEntity(id); }
}
this.#rebuildAllEdges();
}
@@ -295,6 +295,16 @@ export class WorldView if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } { this.despawnGroundItem(id); } } } // Server only sends unsubscribeChunk (not per-entity despawns) when a chunk // leaves the 3×3 interest set — drop mobs/players that still sit on that chunk. for (const [id, entity] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) { this.despawnEntity(id); } } this.#rebuildAllEdges(); this.#rebuildAllEdges(); } }@@ -1105,7 +1105,7 @@ a { color: #d4c48a; }
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(720px, 94vw);
width: min(480px, 94vw);
max-height: min(85vh, 720px);
overflow: auto;
background: #1a1e26;
@@ -1126,14 +1126,28 @@ a { color: #d4c48a; }
margin-bottom: 0.5rem;
}
.market-section {
margin-top: 0.75rem;
.market-tabs {
display: flex;
gap: 0.25rem;
margin: 0.5rem 0 0.75rem;
}
.market-columns {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
.market-tab {
flex: 1;
font-size: 0.85rem;
padding: 0.35rem 0.4rem;
background: #12151b;
border: 1px solid #2c3340;
color: inherit;
}
.market-tab.active {
outline: 1px solid #6a8caf;
border-color: #6a8caf;
}
.market-pane {
margin-top: 0.25rem;
}
.market-catalog,
@@ -1141,7 +1155,7 @@ a { color: #d4c48a; }
display: flex;
flex-direction: column;
gap: 0.25rem;
max-height: 180px;
max-height: 220px;
overflow: auto;
margin-bottom: 0.5rem;
}
@@ -1171,10 +1185,9 @@ a { color: #d4c48a; }
image-rendering: pixelated;
}
@media (max-width: 700px) {
.market-columns {
grid-template-columns: 1fr;
}
#market-sell-qty:disabled,
#market-sell-qty[readonly] {
opacity: 0.7;
}
@@ -1105,7 +1105,7 @@ a { color: #d4c48a; } top: 50%; top: 50%; left: 50%; left: 50%; transform: translate(-50%, -50%); transform: translate(-50%, -50%); width: min(720px, 94vw); width: min(480px, 94vw); max-height: min(85vh, 720px); max-height: min(85vh, 720px); overflow: auto; overflow: auto; background: #1a1e26; background: #1a1e26;@@ -1126,14 +1126,28 @@ a { color: #d4c48a; } margin-bottom: 0.5rem; margin-bottom: 0.5rem;}}.market-section {.market-tabs { margin-top: 0.75rem; display: flex; gap: 0.25rem; margin: 0.5rem 0 0.75rem;}}.market-columns {.market-tab { display: grid; flex: 1; grid-template-columns: 1fr 1fr; font-size: 0.85rem; gap: 1rem; padding: 0.35rem 0.4rem; background: #12151b; border: 1px solid #2c3340; color: inherit;}.market-tab.active { outline: 1px solid #6a8caf; border-color: #6a8caf;}.market-pane { margin-top: 0.25rem;}}.market-catalog,.market-catalog,@@ -1141,7 +1155,7 @@ a { color: #d4c48a; } display: flex; display: flex; flex-direction: column; flex-direction: column; gap: 0.25rem; gap: 0.25rem; max-height: 180px; max-height: 220px; overflow: auto; overflow: auto; margin-bottom: 0.5rem; margin-bottom: 0.5rem;}}@@ -1171,10 +1185,9 @@ a { color: #d4c48a; } image-rendering: pixelated; image-rendering: pixelated;}}@media (max-width: 700px) {#market-sell-qty:disabled, .market-columns {#market-sell-qty[readonly] { grid-template-columns: 1fr; opacity: 0.7; }}}@@ -58,13 +58,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Baked lighting
**Status:** full
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4.
**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on a block def (e.g. table, marketplace counter) to let light through while remaining impassable. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4.
**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
## World editor (server)
**Status:** full
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`) are placeable blocks.
**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
**Code:** `server/src/editor/service.js`
## World editor (client)
@@ -229,7 +229,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
**Status:** partial
**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting.
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
@@ -294,8 +294,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Banking, cheques, shops, player-driven marketplace
**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** `BlockType.marketplace` counters require adjacency. Hidden order book (no browsable asks): place buy/sell with escrow from bag; match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter (`Bobby Pennies` etc., Central Exchange). Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter. Matches update durable `item_last_sales` for shop/tooltip lerp.
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
## Player scripting hooks
@@ -58,13 +58,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Baked lighting## Baked lighting**Status:** full **Status:** full **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through passable tiles, including across chunk borders. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4. **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on a block def (e.g. table, marketplace counter) to let light through while remaining impassable. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4. **Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`## World editor (server)## World editor (server)**Status:** full **Status:** full **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`) are placeable blocks. **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable. **Code:** `server/src/editor/service.js`**Code:** `server/src/editor/service.js`## World editor (client)## World editor (client)@@ -229,7 +229,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi**Status:** partial **Status:** partial **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), and boulder-ore; tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type). **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type). **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`@@ -294,8 +294,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Banking, cheques, shops, player-driven marketplace## Banking, cheques, shops, player-driven marketplace**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live) **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live) **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** `BlockType.marketplace` counters require adjacency. Hidden order book (no browsable asks): place buy/sell with escrow from bag; match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter (`Bobby Pennies` etc., Central Exchange). Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter. Matches update durable `item_last_sales` for shop/tooltip lerp. **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp. **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`## Player scripting hooks## Player scripting hooks@@ -6,7 +6,8 @@ import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
import {
ORE_BEARING_MATERIALS,
oreBoulderState,
materialTintColor
materialTintColor,
WOOD_TIER_ORDER
} from "../../../shared/definitions/materialTiers.js";
import {
bloomImageName,
@@ -17,6 +18,7 @@ import {
spriteImageName
} from "../../../shared/definitions/tileSprites.js";
import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";
const CHARACTER_DEFINITIONS = Object.freeze({
"player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -187,6 +189,30 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
}
}
if (layer === "block" && def.key === "table")
{
// Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
states = [];
for (const material of WOOD_TIER_ORDER)
{
for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
{
const state = composeNeighborConnectState(def, material, mask);
states.push(state);
const tint = materialTintColor(material);
imagesForType.push({
name: spriteImageName(layer, def.key, state),
url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
subImgTotal: frames,
perRow: framesPerRow,
loop: animationSpeed > 0,
animationSpeed,
tint: { r: tint.r, g: tint.g, b: tint.b }
});
}
}
}
types[def.key] = {
key: def.key,
typeId: def.id,
@@ -6,7 +6,8 @@ import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";import {import { ORE_BEARING_MATERIALS, ORE_BEARING_MATERIALS, oreBoulderState, oreBoulderState, materialTintColor materialTintColor, WOOD_TIER_ORDER} from "../../../shared/definitions/materialTiers.js";} from "../../../shared/definitions/materialTiers.js";import {import { bloomImageName, bloomImageName,@@ -17,6 +18,7 @@ import { spriteImageName spriteImageName} from "../../../shared/definitions/tileSprites.js";} from "../../../shared/definitions/tileSprites.js";import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";const CHARACTER_DEFINITIONS = Object.freeze({const CHARACTER_DEFINITIONS = Object.freeze({ "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }), "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),@@ -187,6 +189,30 @@ function scanLayer (layerDir, definitions, layer, urlFolder) } } } } if (layer === "block" && def.key === "table") { // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier. states = []; for (const material of WOOD_TIER_ORDER) { for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++) { const state = composeNeighborConnectState(def, material, mask); states.push(state); const tint = materialTintColor(material); imagesForType.push({ name: spriteImageName(layer, def.key, state), url: `/assets/${urlFolder}/${def.key}/${mask}.png`, subImgTotal: frames, perRow: framesPerRow, loop: animationSpeed > 0, animationSpeed, tint: { r: tint.r, g: tint.g, b: tint.b } }); } } } types[def.key] = { types[def.key] = { key: def.key, key: def.key, typeId: def.id, typeId: def.id,@@ -1,7 +1,7 @@
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";
export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
}
function isPassable (tileX, tileY)
function isClearForLight (tileX, tileY)
{
const data = getData(tileToChunk(tileX), tileToChunk(tileY));
return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY));
}
for (const coord of affected)
@@ -56,7 +56,7 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
if (dist > source.range)
{ continue; }
if (rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight))
{
best = Math.max(best, encodeLight(dist, source.range));
}
@@ -1,7 +1,7 @@import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange) sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data)); sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data)); } } function isPassable (tileX, tileY) function isClearForLight (tileX, tileY) { { const data = getData(tileToChunk(tileX), tileToChunk(tileY)); const data = getData(tileToChunk(tileX), tileToChunk(tileY)); return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY)); return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY)); } } for (const coord of affected) for (const coord of affected)@@ -56,7 +56,7 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange) const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY); const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY); if (dist > source.range) if (dist > source.range) { continue; } { continue; } if (rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable)) if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight)) { { best = Math.max(best, encodeLight(dist, source.range)); best = Math.max(best, encodeLight(dist, source.range)); } }@@ -7,7 +7,6 @@ import {
insertStack,
insertStackGrowable,
normalizeVault,
takeCoinsFromSlots,
takeFromSlot,
cloneStack
} from "../../../shared/items/inventory.js";
@@ -17,12 +16,14 @@ import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
import {
MARKET_ORDER_MAX_AGE_MS,
buyFilledLetterBody,
marketOrderListingFee,
midpointTradePrice,
orderExpiredLetterBody,
orderCancelledLetterBody,
pickExchangeClerk,
soldLetterBody
} from "../../../shared/market/exchange.js";
import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";
import { decodeChunkBlob } from "../world/chunkData.js";
import { withTransaction } from "../persistence/database.js";
@@ -165,6 +166,7 @@ export class MarketService
openMarket (sessionId, characterId, now = Date.now())
{
const { position } = this.#requireAtMarket(characterId);
this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
return {
events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
};
@@ -174,7 +176,6 @@ export class MarketService
{
const { position } = this.#requireAtMarket(characterId);
const minPrice = Math.max(1, minUnitPrice | 0);
const qty = Math.max(1, quantity | 0 || 1);
const bag = this.#loadBag(characterId);
const slot = bag.inventory?.[slotIndex];
if (!slot)
@@ -182,19 +183,58 @@ export class MarketService
assertMarketplaceSellable(slot);
if ((slot.itemId | 0) === ItemId.coins)
{ throw userError("Coins cannot be listed on the marketplace."); }
const taken = takeFromSlot(bag.inventory, slotIndex, qty);
if (!taken.ok || !taken.taken)
{ throw userError("That item is not available."); }
bag.inventory = taken.slots;
const stack = attachOrigins(taken.taken);
const listing = resolveMarketSellListing(slot);
if (!listing)
{ throw userError("That item cannot be sold on the marketplace."); }
let escrowStack;
let orderQty;
if (listing.isCheque)
{
orderQty = listing.quantity;
const taken = takeFromSlot(bag.inventory, slotIndex, 1);
if (!taken.ok || !taken.taken)
{ throw userError("That cheque is not available."); }
bag.inventory = taken.slots;
escrowStack = attachOrigins(taken.taken);
}
else
{
const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
orderQty = qty;
const taken = takeFromSlot(bag.inventory, slotIndex, qty);
if (!taken.ok || !taken.taken)
{ throw userError("That item is not available."); }
bag.inventory = taken.slots;
escrowStack = attachOrigins(taken.taken);
}
const fee = marketOrderListingFee(minPrice, orderQty);
const paid = this.#payMarketFunds(bag, characterId, fee);
if (!paid.ok)
{
const restored = insertStack(
bag.inventory,
escrowStack,
itemDefinition(escrowStack.itemId)
);
bag.inventory = restored.slots;
throw userError(
fee > 0
? `You need ${fee} coins for the listing fee.`
: "You cannot afford the listing fee."
);
}
const order = this.stateDb.insertMarketOrder({
characterId,
side: "sell",
itemId: stack.itemId,
quantity: stack.quantity,
itemId: listing.itemId,
quantity: orderQty,
limitUnitPrice: minPrice,
escrowCoins: 0,
escrowStack: stack,
escrowStack,
createdAt: now,
status: "open"
});
@@ -219,11 +259,15 @@ export class MarketService
if ((itemId | 0) === ItemId.coins)
{ throw userError("Coins cannot be ordered on the marketplace."); }
const escrow = maxPrice * qty;
const fee = marketOrderListingFee(maxPrice, qty);
const bag = this.#loadBag(characterId);
const paid = takeCoinsFromSlots(bag.inventory, escrow);
const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
if (!paid.ok)
{ throw userError("You cannot afford that buy order."); }
bag.inventory = paid.slots;
{
throw userError(
`You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
);
}
const order = this.stateDb.insertMarketOrder({
characterId,
side: "buy",
@@ -258,7 +302,11 @@ export class MarketService
side: order.side,
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
quantity: order.quantity,
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
escrowLabel: order.side === "buy"
? "coins"
: (isFilledChequeEscrow(order.escrowStack)
? "written cheque"
: (itemDefinition(order.itemId)?.displayName ?? "item")),
clerkName: pickExchangeClerk()
}),
now
@@ -283,7 +331,11 @@ export class MarketService
side: order.side,
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
quantity: order.quantity,
escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
escrowLabel: order.side === "buy"
? "coins"
: (isFilledChequeEscrow(order.escrowStack)
? "written cheque"
: (itemDefinition(order.itemId)?.displayName ?? "item")),
clerkName: pickExchangeClerk()
}),
now
@@ -330,7 +382,14 @@ export class MarketService
if (buy.limitUnitPrice < sell.limitUnitPrice)
{ continue; }
const fillQty = Math.min(buy.quantity, sell.quantity);
let fillQty = Math.min(buy.quantity, sell.quantity);
if (isFilledChequeEscrow(sell.escrowStack))
{
// Written cheques list as one indivisible lot.
if (fillQty < sell.quantity)
{ continue; }
fillQty = sell.quantity;
}
if (fillQty <= 0)
{ continue; }
const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
@@ -353,18 +412,31 @@ export class MarketService
const total = unitPrice * fillQty;
const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
const clerk = pickExchangeClerk();
const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
const goods = attachOrigins({
itemId: sell.itemId,
quantity: fillQty,
origins: sellSplit.taken,
instance: sell.escrowStack?.instance ?? null
});
let goods;
let sellRemainOrigins = null;
if (chequeEscrow)
{
goods = this.#redeemSellChequeEscrow(sell.escrowStack);
if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
{ throw userError("That cheque listing could not be settled."); }
}
else
{
const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
goods = attachOrigins({
itemId: sell.itemId,
quantity: fillQty,
origins: sellSplit.taken,
instance: sell.escrowStack?.instance ?? null
});
sellRemainOrigins = sellSplit.remain;
}
const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
const buyRemainingQty = buy.quantity - fillQty;
const sellRemainingQty = sell.quantity - fillQty;
const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
withTransaction(this.stateDb.db, () =>
{
@@ -392,7 +464,7 @@ export class MarketService
? attachOrigins({
...sell.escrowStack,
quantity: sellRemainingQty,
origins: sellSplit.remain
origins: sellRemainOrigins
})
: null,
status: sellRemainingQty > 0 ? "open" : "filled"
@@ -442,6 +514,67 @@ export class MarketService
return events;
}
/** Redeem a written-cheque sell escrow into the reserved goods stack. */
#redeemSellChequeEscrow (chequeStack)
{
const instance = chequeStack?.instance;
if (!instance || instance.kind !== "filled-cheque")
{ throw userError("That cheque listing is invalid."); }
const issuerId = instance.issuerCharacterId | 0;
const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
if (!release?.ok || !release.stack)
{ throw userError(release?.error ?? "That cheque cannot be redeemed."); }
return attachOrigins(release.stack);
}
/**
* Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
* Releases reservations for redeemed coin cheques.
*/
#payMarketFunds (bag, payerCharacterId, amount)
{
const need = Math.max(0, amount | 0);
if (!need)
{ return { ok: true }; }
const paid = takeMarketFunds(bag.inventory, need);
if (!paid.ok)
{ return { ok: false }; }
bag.inventory = paid.slots;
for (const cheque of paid.redeemedCheques ?? [])
{
const instance = cheque.instance;
const issuerId = instance?.issuerCharacterId | 0;
const release = this.simulation.releaseChequeReservation?.(
issuerId,
instance.chequeId,
instance
);
if (!release?.ok)
{
// Restore cheque paper; leave other payments as-is (best-effort).
const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
bag.inventory = restored.slots;
return { ok: false };
}
}
if ((paid.change | 0) > 0)
{
const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
if (!refunded.ok)
{
const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
bag.inventory = refunded.slots;
bag.vault = vaultPaid.slots;
bag.vaultReserved = vault.reserved;
}
else
{ bag.inventory = refunded.slots; }
}
void payerCharacterId;
return { ok: true };
}
#returnEscrowByPigeon (order, { letterBody, now })
{
const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
@@ -7,7 +7,6 @@ import { insertStack, insertStack, insertStackGrowable, insertStackGrowable, normalizeVault, normalizeVault, takeCoinsFromSlots, takeFromSlot, takeFromSlot, cloneStack cloneStack} from "../../../shared/items/inventory.js";} from "../../../shared/items/inventory.js";@@ -17,12 +16,14 @@ import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";import {import { MARKET_ORDER_MAX_AGE_MS, MARKET_ORDER_MAX_AGE_MS, buyFilledLetterBody, buyFilledLetterBody, marketOrderListingFee, midpointTradePrice, midpointTradePrice, orderExpiredLetterBody, orderExpiredLetterBody, orderCancelledLetterBody, orderCancelledLetterBody, pickExchangeClerk, pickExchangeClerk, soldLetterBody soldLetterBody} from "../../../shared/market/exchange.js";} from "../../../shared/market/exchange.js";import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";import { decodeChunkBlob } from "../world/chunkData.js";import { decodeChunkBlob } from "../world/chunkData.js";import { withTransaction } from "../persistence/database.js";import { withTransaction } from "../persistence/database.js";@@ -165,6 +166,7 @@ export class MarketService openMarket (sessionId, characterId, now = Date.now()) openMarket (sessionId, characterId, now = Date.now()) { { const { position } = this.#requireAtMarket(characterId); const { position } = this.#requireAtMarket(characterId); this.simulation.stationExchangeClerks?.(position.tileX, position.tileY); return { return { events: [this.#marketOpenEvent(sessionId, characterId, position, now)] events: [this.#marketOpenEvent(sessionId, characterId, position, now)] }; };@@ -174,7 +176,6 @@ export class MarketService { { const { position } = this.#requireAtMarket(characterId); const { position } = this.#requireAtMarket(characterId); const minPrice = Math.max(1, minUnitPrice | 0); const minPrice = Math.max(1, minUnitPrice | 0); const qty = Math.max(1, quantity | 0 || 1); const bag = this.#loadBag(characterId); const bag = this.#loadBag(characterId); const slot = bag.inventory?.[slotIndex]; const slot = bag.inventory?.[slotIndex]; if (!slot) if (!slot)@@ -182,19 +183,58 @@ export class MarketService assertMarketplaceSellable(slot); assertMarketplaceSellable(slot); if ((slot.itemId | 0) === ItemId.coins) if ((slot.itemId | 0) === ItemId.coins) { throw userError("Coins cannot be listed on the marketplace."); } { throw userError("Coins cannot be listed on the marketplace."); } const taken = takeFromSlot(bag.inventory, slotIndex, qty); if (!taken.ok || !taken.taken) const listing = resolveMarketSellListing(slot); { throw userError("That item is not available."); } if (!listing) bag.inventory = taken.slots; { throw userError("That item cannot be sold on the marketplace."); } const stack = attachOrigins(taken.taken); let escrowStack; let orderQty; if (listing.isCheque) { orderQty = listing.quantity; const taken = takeFromSlot(bag.inventory, slotIndex, 1); if (!taken.ok || !taken.taken) { throw userError("That cheque is not available."); } bag.inventory = taken.slots; escrowStack = attachOrigins(taken.taken); } else { const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity)); orderQty = qty; const taken = takeFromSlot(bag.inventory, slotIndex, qty); if (!taken.ok || !taken.taken) { throw userError("That item is not available."); } bag.inventory = taken.slots; escrowStack = attachOrigins(taken.taken); } const fee = marketOrderListingFee(minPrice, orderQty); const paid = this.#payMarketFunds(bag, characterId, fee); if (!paid.ok) { const restored = insertStack( bag.inventory, escrowStack, itemDefinition(escrowStack.itemId) ); bag.inventory = restored.slots; throw userError( fee > 0 ? `You need ${fee} coins for the listing fee.` : "You cannot afford the listing fee." ); } const order = this.stateDb.insertMarketOrder({ const order = this.stateDb.insertMarketOrder({ characterId, characterId, side: "sell", side: "sell", itemId: stack.itemId, itemId: listing.itemId, quantity: stack.quantity, quantity: orderQty, limitUnitPrice: minPrice, limitUnitPrice: minPrice, escrowCoins: 0, escrowCoins: 0, escrowStack: stack, escrowStack, createdAt: now, createdAt: now, status: "open" status: "open" }); });@@ -219,11 +259,15 @@ export class MarketService if ((itemId | 0) === ItemId.coins) if ((itemId | 0) === ItemId.coins) { throw userError("Coins cannot be ordered on the marketplace."); } { throw userError("Coins cannot be ordered on the marketplace."); } const escrow = maxPrice * qty; const escrow = maxPrice * qty; const fee = marketOrderListingFee(maxPrice, qty); const bag = this.#loadBag(characterId); const bag = this.#loadBag(characterId); const paid = takeCoinsFromSlots(bag.inventory, escrow); const paid = this.#payMarketFunds(bag, characterId, escrow + fee); if (!paid.ok) if (!paid.ok) { throw userError("You cannot afford that buy order."); } { bag.inventory = paid.slots; throw userError( `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).` ); } const order = this.stateDb.insertMarketOrder({ const order = this.stateDb.insertMarketOrder({ characterId, characterId, side: "buy", side: "buy",@@ -258,7 +302,11 @@ export class MarketService side: order.side, side: order.side, itemName: itemDefinition(order.itemId)?.displayName ?? "item", itemName: itemDefinition(order.itemId)?.displayName ?? "item", quantity: order.quantity, quantity: order.quantity, escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"), escrowLabel: order.side === "buy" ? "coins" : (isFilledChequeEscrow(order.escrowStack) ? "written cheque" : (itemDefinition(order.itemId)?.displayName ?? "item")), clerkName: pickExchangeClerk() clerkName: pickExchangeClerk() }), }), now now@@ -283,7 +331,11 @@ export class MarketService side: order.side, side: order.side, itemName: itemDefinition(order.itemId)?.displayName ?? "item", itemName: itemDefinition(order.itemId)?.displayName ?? "item", quantity: order.quantity, quantity: order.quantity, escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"), escrowLabel: order.side === "buy" ? "coins" : (isFilledChequeEscrow(order.escrowStack) ? "written cheque" : (itemDefinition(order.itemId)?.displayName ?? "item")), clerkName: pickExchangeClerk() clerkName: pickExchangeClerk() }), }), now now@@ -330,7 +382,14 @@ export class MarketService if (buy.limitUnitPrice < sell.limitUnitPrice) if (buy.limitUnitPrice < sell.limitUnitPrice) { continue; } { continue; } const fillQty = Math.min(buy.quantity, sell.quantity); let fillQty = Math.min(buy.quantity, sell.quantity); if (isFilledChequeEscrow(sell.escrowStack)) { // Written cheques list as one indivisible lot. if (fillQty < sell.quantity) { continue; } fillQty = sell.quantity; } if (fillQty <= 0) if (fillQty <= 0) { continue; } { continue; } const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice); const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);@@ -353,18 +412,31 @@ export class MarketService const total = unitPrice * fillQty; const total = unitPrice * fillQty; const itemName = itemDefinition(sell.itemId)?.displayName ?? "item"; const itemName = itemDefinition(sell.itemId)?.displayName ?? "item"; const clerk = pickExchangeClerk(); const clerk = pickExchangeClerk(); const chequeEscrow = isFilledChequeEscrow(sell.escrowStack); const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty); let goods; const goods = attachOrigins({ let sellRemainOrigins = null; itemId: sell.itemId, if (chequeEscrow) quantity: fillQty, { origins: sellSplit.taken, goods = this.#redeemSellChequeEscrow(sell.escrowStack); instance: sell.escrowStack?.instance ?? null if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0)) }); { throw userError("That cheque listing could not be settled."); } } else { const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty); goods = attachOrigins({ itemId: sell.itemId, quantity: fillQty, origins: sellSplit.taken, instance: sell.escrowStack?.instance ?? null }); sellRemainOrigins = sellSplit.remain; } const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty; const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty; const buyRemainingQty = buy.quantity - fillQty; const buyRemainingQty = buy.quantity - fillQty; const sellRemainingQty = sell.quantity - fillQty; const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty; withTransaction(this.stateDb.db, () => withTransaction(this.stateDb.db, () => { {@@ -392,7 +464,7 @@ export class MarketService ? attachOrigins({ ? attachOrigins({ ...sell.escrowStack, ...sell.escrowStack, quantity: sellRemainingQty, quantity: sellRemainingQty, origins: sellSplit.remain origins: sellRemainOrigins }) }) : null, : null, status: sellRemainingQty > 0 ? "open" : "filled" status: sellRemainingQty > 0 ? "open" : "filled"@@ -442,6 +514,67 @@ export class MarketService return events; return events; } } /** Redeem a written-cheque sell escrow into the reserved goods stack. */ #redeemSellChequeEscrow (chequeStack) { const instance = chequeStack?.instance; if (!instance || instance.kind !== "filled-cheque") { throw userError("That cheque listing is invalid."); } const issuerId = instance.issuerCharacterId | 0; const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance); if (!release?.ok || !release.stack) { throw userError(release?.error ?? "That cheque cannot be redeemed."); } return attachOrigins(release.stack); } /** * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory. * Releases reservations for redeemed coin cheques. */ #payMarketFunds (bag, payerCharacterId, amount) { const need = Math.max(0, amount | 0); if (!need) { return { ok: true }; } const paid = takeMarketFunds(bag.inventory, need); if (!paid.ok) { return { ok: false }; } bag.inventory = paid.slots; for (const cheque of paid.redeemedCheques ?? []) { const instance = cheque.instance; const issuerId = instance?.issuerCharacterId | 0; const release = this.simulation.releaseChequeReservation?.( issuerId, instance.chequeId, instance ); if (!release?.ok) { // Restore cheque paper; leave other payments as-is (best-effort). const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque)); bag.inventory = restored.slots; return { ok: false }; } } if ((paid.change | 0) > 0) { const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false }); if (!refunded.ok) { const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true }); bag.inventory = refunded.slots; bag.vault = vaultPaid.slots; bag.vaultReserved = vault.reserved; } else { bag.inventory = refunded.slots; } } void payerCharacterId; return { ok: true }; } #returnEscrowByPigeon (order, { letterBody, now }) #returnEscrowByPigeon (order, { letterBody, now }) { { const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 }; const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };@@ -34,5 +34,6 @@ export const WorkerMessage = Object.freeze({
spawnCorpseDrops: "spawnCorpseDrops",
applyRespawn: "applyRespawn",
clearCombat: "clearCombat",
setItemLastSales: "setItemLastSales"
setItemLastSales: "setItemLastSales",
stationExchangeClerk: "stationExchangeClerk"
});
@@ -34,5 +34,6 @@ export const WorkerMessage = Object.freeze({ spawnCorpseDrops: "spawnCorpseDrops", spawnCorpseDrops: "spawnCorpseDrops", applyRespawn: "applyRespawn", applyRespawn: "applyRespawn", clearCombat: "clearCombat", clearCombat: "clearCombat", setItemLastSales: "setItemLastSales" setItemLastSales: "setItemLastSales", stationExchangeClerk: "stationExchangeClerk"});});@@ -554,6 +554,36 @@ export class Simulation
});
}
/**
* When a player uses a marketplace counter, path an idle CE clerk to the
* opposite side of that counter (staff side).
*/
stationExchangeClerks (playerTileX, playerTileY)
{
const results = [];
for (const tile of this.market?.marketTiles ?? [])
{
if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
{ continue; }
if (tile.tileX === playerTileX && tile.tileY === playerTileY)
{ continue; }
const stationTileX = tile.tileX + (tile.tileX - playerTileX);
const stationTileY = tile.tileY + (tile.tileY - playerTileY);
if (stationTileX === playerTileX && stationTileY === playerTileY)
{ continue; }
const owner = this.#ownerOfTile(stationTileX, stationTileY);
if (owner == null)
{ continue; }
const result = this.workers[owner].call({
type: WorkerMessage.stationExchangeClerk,
stationTileX,
stationTileY
});
results.push(result);
}
return results;
}
despawnCharacter (characterId)
{
const entityId = this.characterEntities.get(characterId);
@@ -554,6 +554,36 @@ export class Simulation }); }); } } /** * When a player uses a marketplace counter, path an idle CE clerk to the * opposite side of that counter (staff side). */ stationExchangeClerks (playerTileX, playerTileY) { const results = []; for (const tile of this.market?.marketTiles ?? []) { if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1) { continue; } if (tile.tileX === playerTileX && tile.tileY === playerTileY) { continue; } const stationTileX = tile.tileX + (tile.tileX - playerTileX); const stationTileY = tile.tileY + (tile.tileY - playerTileY); if (stationTileX === playerTileX && stationTileY === playerTileY) { continue; } const owner = this.#ownerOfTile(stationTileX, stationTileY); if (owner == null) { continue; } const result = this.workers[owner].call({ type: WorkerMessage.stationExchangeClerk, stationTileX, stationTileY }); results.push(result); } return results; } despawnCharacter (characterId) despawnCharacter (characterId) { { const entityId = this.characterEntities.get(characterId); const entityId = this.characterEntities.get(characterId);@@ -4,8 +4,10 @@ import {
normalizeSpawnerConfig,
listAmbientMobTypes,
mobDefinition,
mobSpriteName
mobSpriteName,
MobId
} from "../../../shared/definitions/mobs.js";
import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
import { emptyEquipment } from "../../../shared/items/inventory.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { Component } from "../ecs/components.js";
@@ -15,6 +17,7 @@ export function collectSpawnRequests (world)
{
const requests = [];
const counts = countBySpawner(world);
const staffAlive = staffNamesBySpawner(world);
const reserved = new Set();
for (const [key, chunk] of world.chunks)
{
@@ -34,6 +37,43 @@ export function collectSpawnRequests (world)
const originX = chunkX * CHUNK_SIZE + localX;
const originY = chunkY * CHUNK_SIZE + localY;
const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
if (config.centralExchange)
{
const alive = staffAlive.get(config.spawnerId) ?? new Set();
for (const staff of CENTRAL_EXCHANGE_STAFF)
{
if (alive.has(staff.name))
{ continue; }
if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
{ break; }
const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
if (!tile)
{ break; }
reserved.add(`${tile.tileX},${tile.tileY}`);
alive.add(staff.name);
staffAlive.set(config.spawnerId, alive);
requests.push({
...tile,
mobTypeId: MobId.centralExchange,
spawnerId: config.spawnerId,
originTileX: originX,
originTileY: originY,
wanderRangeTiles: config.maxWanderRangeTiles,
persistent,
sex: staff.sex,
displayName: staff.name,
equipment: config.equipment,
sells: [],
buysItems: false,
hiddenDiscount: config.hiddenDiscount,
centralExchange: true
});
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
}
continue;
}
while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
{
const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
@@ -53,7 +93,8 @@ export function collectSpawnRequests (world)
equipment: config.equipment,
sells: config.sells,
buysItems: config.buysItems,
hiddenDiscount: config.hiddenDiscount
hiddenDiscount: config.hiddenDiscount,
centralExchange: false
});
counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
}
@@ -96,7 +137,10 @@ export function mobComponents (request)
spawnerId: request.spawnerId,
originTileX: request.originTileX ?? request.tileX,
originTileY: request.originTileY ?? request.tileY,
wanderRangeTiles: request.wanderRangeTiles ?? 4
wanderRangeTiles: request.wanderRangeTiles ?? 4,
centralExchange: !!request.centralExchange,
stationTileX: null,
stationTileY: null
};
}
if (def.persistent)
@@ -148,7 +192,8 @@ export function mobComponents (request)
}).filter((line) => line.itemId > 0)
: [];
const buysItems = !!request.buysItems;
if (catalog.length || buysItems || def.talkable)
const isExchange = !!request.centralExchange || def.centralExchange;
if (!isExchange && (catalog.length || buysItems || def.talkable))
{
components.shop = {
catalog,
@@ -219,6 +264,24 @@ function countBySpawner (world)
return counts;
}
function staffNamesBySpawner (world)
{
const map = new Map();
for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
const id = entity.spawnOrigin.spawnerId;
const name = entity.appearance?.firstName;
if (!id || !name)
{ continue; }
const set = map.get(id) ?? new Set();
set.add(name);
map.set(id, set);
}
return map;
}
function countCreatures (world, mobTypeId)
{
let count = 0;
@@ -4,8 +4,10 @@ import { normalizeSpawnerConfig, normalizeSpawnerConfig, listAmbientMobTypes, listAmbientMobTypes, mobDefinition, mobDefinition, mobSpriteName mobSpriteName, MobId} from "../../../shared/definitions/mobs.js";} from "../../../shared/definitions/mobs.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 { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";@@ -15,6 +17,7 @@ export function collectSpawnRequests (world){{ const requests = []; const requests = []; const counts = countBySpawner(world); const counts = countBySpawner(world); const staffAlive = staffNamesBySpawner(world); const reserved = new Set(); const reserved = new Set(); for (const [key, chunk] of world.chunks) for (const [key, chunk] of world.chunks) { {@@ -34,6 +37,43 @@ export function collectSpawnRequests (world) const originX = chunkX * CHUNK_SIZE + localX; const originX = chunkX * CHUNK_SIZE + localX; const originY = chunkY * CHUNK_SIZE + localY; const originY = chunkY * CHUNK_SIZE + localY; const persistent = !!mobDefinition(config.mobTypeId)?.persistent; const persistent = !!mobDefinition(config.mobTypeId)?.persistent; if (config.centralExchange) { const alive = staffAlive.get(config.spawnerId) ?? new Set(); for (const staff of CENTRAL_EXCHANGE_STAFF) { if (alive.has(staff.name)) { continue; } if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive) { break; } const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved); if (!tile) { break; } reserved.add(`${tile.tileX},${tile.tileY}`); alive.add(staff.name); staffAlive.set(config.spawnerId, alive); requests.push({ ...tile, mobTypeId: MobId.centralExchange, spawnerId: config.spawnerId, originTileX: originX, originTileY: originY, wanderRangeTiles: config.maxWanderRangeTiles, persistent, sex: staff.sex, displayName: staff.name, equipment: config.equipment, sells: [], buysItems: false, hiddenDiscount: config.hiddenDiscount, centralExchange: true }); counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); } continue; } while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive) while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive) { { const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved); const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);@@ -53,7 +93,8 @@ export function collectSpawnRequests (world) equipment: config.equipment, equipment: config.equipment, sells: config.sells, sells: config.sells, buysItems: config.buysItems, buysItems: config.buysItems, hiddenDiscount: config.hiddenDiscount hiddenDiscount: config.hiddenDiscount, centralExchange: false }); }); counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1); } }@@ -96,7 +137,10 @@ export function mobComponents (request) spawnerId: request.spawnerId, spawnerId: request.spawnerId, originTileX: request.originTileX ?? request.tileX, originTileX: request.originTileX ?? request.tileX, originTileY: request.originTileY ?? request.tileY, originTileY: request.originTileY ?? request.tileY, wanderRangeTiles: request.wanderRangeTiles ?? 4 wanderRangeTiles: request.wanderRangeTiles ?? 4, centralExchange: !!request.centralExchange, stationTileX: null, stationTileY: null }; }; } } if (def.persistent) if (def.persistent)@@ -148,7 +192,8 @@ export function mobComponents (request) }).filter((line) => line.itemId > 0) }).filter((line) => line.itemId > 0) : []; : []; const buysItems = !!request.buysItems; const buysItems = !!request.buysItems; if (catalog.length || buysItems || def.talkable) const isExchange = !!request.centralExchange || def.centralExchange; if (!isExchange && (catalog.length || buysItems || def.talkable)) { { components.shop = { components.shop = { catalog, catalog,@@ -219,6 +264,24 @@ function countBySpawner (world) return counts; return counts;}}function staffNamesBySpawner (world){ const map = new Map(); for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance)) { if (!entity.spawnOrigin?.centralExchange) { continue; } const id = entity.spawnOrigin.spawnerId; const name = entity.appearance?.firstName; if (!id || !name) { continue; } const set = map.get(id) ?? new Set(); set.add(name); map.set(id, set); } return map;}function countCreatures (world, mobTypeId)function countCreatures (world, mobTypeId){{ let count = 0; let count = 0;@@ -171,6 +171,8 @@ export class WorkerWorld
{ this.itemLastSales.set(Number(key), sale); }
return { ok: true };
}
case WorkerMessage.stationExchangeClerk:
return this.#stationExchangeClerk(message);
default:
throw new Error(`Unknown worker message ${message.type}`);
}
@@ -981,6 +983,7 @@ export class WorkerWorld
events.push(...pruneShopBrowsers(this));
this.#queueAmbientWander();
this.#queueSpawnerWander();
this.#queueExchangeStations();
for (const entity of this.ecs.query(Component.position, Component.movement))
{
const { handle, entityId, position, movement } = entity;
@@ -1169,6 +1172,9 @@ export class WorkerWorld
const shop = this.ecs.get(entity.handle, Component.shop);
if (shopHasActiveBrowsers(shop))
{ continue; }
const origin = entity.spawnOrigin;
if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
{ continue; }
const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
if (def?.freeFlight)
{ continue; }
@@ -1180,7 +1186,6 @@ export class WorkerWorld
if (Math.random() > 0.4)
{ continue; }
const origin = entity.spawnOrigin;
const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
const range = Math.max(0, origin.wanderRangeTiles | 0);
@@ -1207,6 +1212,108 @@ export class WorkerWorld
}
}
/**
* Send an idle Central Exchange clerk to the staff-side tile of a counter.
* message: { stationTileX, stationTileY }
*/
#stationExchangeClerk (message)
{
const stationTileX = message.stationTileX | 0;
const stationTileY = message.stationTileY | 0;
if (!this.isEnterable(stationTileX, stationTileY))
{ return { ok: false, reason: "blocked" }; }
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
if (
Number.isInteger(entity.spawnOrigin.stationTileX)
&& entity.spawnOrigin.stationTileX === stationTileX
&& entity.spawnOrigin.stationTileY === stationTileY
)
{ return { ok: true, entityId: entity.entityId, already: true }; }
}
let best = null;
let bestDist = Infinity;
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
if (Number.isInteger(entity.spawnOrigin.stationTileX))
{ continue; }
const dist = Math.max(
Math.abs(entity.position.tileX - stationTileX),
Math.abs(entity.position.tileY - stationTileY)
);
if (dist < bestDist)
{
bestDist = dist;
best = entity;
}
}
if (!best)
{ return { ok: false, reason: "none-available" }; }
const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
const tiles = findPath(
best.position.tileX,
best.position.tileY,
stationTileX,
stationTileY,
(x, y) => this.walkableFor(best.entityId, x, y),
bounds.minX,
bounds.minY,
bounds.maxX,
bounds.maxY
);
best.spawnOrigin.stationTileX = stationTileX;
best.spawnOrigin.stationTileY = stationTileY;
if (tiles?.length)
{ best.path.tiles = tiles; }
else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
{ best.path.tiles = []; }
else
{ return { ok: false, reason: "no-path" }; }
return { ok: true, entityId: best.entityId };
}
/** Keep stationed CE clerks at their counter tile. */
#queueExchangeStations ()
{
for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
const sx = entity.spawnOrigin.stationTileX;
const sy = entity.spawnOrigin.stationTileY;
if (!Number.isInteger(sx) || !Number.isInteger(sy))
{ continue; }
if (entity.position.tileX === sx && entity.position.tileY === sy)
{
entity.path.tiles = [];
continue;
}
if (entity.path.tiles?.length)
{ continue; }
const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
const tiles = findPath(
entity.position.tileX,
entity.position.tileY,
sx,
sy,
(x, y) => this.walkableFor(entity.entityId, x, y),
bounds.minX,
bounds.minY,
bounds.maxX,
bounds.maxY
);
if (tiles?.length)
{ entity.path.tiles = tiles; }
}
}
#applyTransfer (message)
{
const payload = message.payload;
@@ -171,6 +171,8 @@ export class WorkerWorld { this.itemLastSales.set(Number(key), sale); } { this.itemLastSales.set(Number(key), sale); } return { ok: true }; return { ok: true }; } } case WorkerMessage.stationExchangeClerk: return this.#stationExchangeClerk(message); default: default: throw new Error(`Unknown worker message ${message.type}`); throw new Error(`Unknown worker message ${message.type}`); } }@@ -981,6 +983,7 @@ export class WorkerWorld events.push(...pruneShopBrowsers(this)); events.push(...pruneShopBrowsers(this)); this.#queueAmbientWander(); this.#queueAmbientWander(); this.#queueSpawnerWander(); this.#queueSpawnerWander(); this.#queueExchangeStations(); for (const entity of this.ecs.query(Component.position, Component.movement)) for (const entity of this.ecs.query(Component.position, Component.movement)) { { const { handle, entityId, position, movement } = entity; const { handle, entityId, position, movement } = entity;@@ -1169,6 +1172,9 @@ export class WorkerWorld const shop = this.ecs.get(entity.handle, Component.shop); const shop = this.ecs.get(entity.handle, Component.shop); if (shopHasActiveBrowsers(shop)) if (shopHasActiveBrowsers(shop)) { continue; } { continue; } const origin = entity.spawnOrigin; if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY)) { continue; } const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId); const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId); if (def?.freeFlight) if (def?.freeFlight) { continue; } { continue; }@@ -1180,7 +1186,6 @@ export class WorkerWorld if (Math.random() > 0.4) if (Math.random() > 0.4) { continue; } { continue; } const origin = entity.spawnOrigin; const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX; const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX; const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY; const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY; const range = Math.max(0, origin.wanderRangeTiles | 0); const range = Math.max(0, origin.wanderRangeTiles | 0);@@ -1207,6 +1212,108 @@ export class WorkerWorld } } } } /** * Send an idle Central Exchange clerk to the staff-side tile of a counter. * message: { stationTileX, stationTileY } */ #stationExchangeClerk (message) { const stationTileX = message.stationTileX | 0; const stationTileY = message.stationTileY | 0; if (!this.isEnterable(stationTileX, stationTileY)) { return { ok: false, reason: "blocked" }; } for (const entity of this.ecs.query(Component.spawnOrigin, Component.position)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if ( Number.isInteger(entity.spawnOrigin.stationTileX) && entity.spawnOrigin.stationTileX === stationTileX && entity.spawnOrigin.stationTileY === stationTileY ) { return { ok: true, entityId: entity.entityId, already: true }; } } let best = null; let bestDist = Infinity; for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if (Number.isInteger(entity.spawnOrigin.stationTileX)) { continue; } const dist = Math.max( Math.abs(entity.position.tileX - stationTileX), Math.abs(entity.position.tileY - stationTileY) ); if (dist < bestDist) { bestDist = dist; best = entity; } } if (!best) { return { ok: false, reason: "none-available" }; } const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS); const tiles = findPath( best.position.tileX, best.position.tileY, stationTileX, stationTileY, (x, y) => this.walkableFor(best.entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); best.spawnOrigin.stationTileX = stationTileX; best.spawnOrigin.stationTileY = stationTileY; if (tiles?.length) { best.path.tiles = tiles; } else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY) { best.path.tiles = []; } else { return { ok: false, reason: "no-path" }; } return { ok: true, entityId: best.entityId }; } /** Keep stationed CE clerks at their counter tile. */ #queueExchangeStations () { for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path)) { if (!entity.spawnOrigin?.centralExchange) { continue; } const sx = entity.spawnOrigin.stationTileX; const sy = entity.spawnOrigin.stationTileY; if (!Number.isInteger(sx) || !Number.isInteger(sy)) { continue; } if (entity.position.tileX === sx && entity.position.tileY === sy) { entity.path.tiles = []; continue; } if (entity.path.tiles?.length) { continue; } const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS); const tiles = findPath( entity.position.tileX, entity.position.tileY, sx, sy, (x, y) => this.walkableFor(entity.entityId, x, y), bounds.minX, bounds.minY, bounds.maxX, bounds.maxY ); if (tiles?.length) { entity.path.tiles = tiles; } } } #applyTransfer (message) #applyTransfer (message) { { const payload = message.payload; const payload = message.payload;@@ -3,6 +3,7 @@ import {
GroundType,
BlockType,
isBlockPassable,
isBlockOccludingLight,
isGroundPassable,
blockLightRange,
normalizeGround,
@@ -156,6 +157,17 @@ export function isChunkTilePassable (data, localX, localY)
return isBlockPassable(block?.typeId ?? null);
}
/** Ground + block clear for light rays (furniture may be impassable but not occluding). */
export function isChunkTileClearForLight (data, localX, localY)
{
const index = tileIndex(localX, localY);
const ground = normalizeGround(data.grounds[index]);
if (!isGroundPassable(ground.typeId))
{ return false; }
const block = data.blocks[index];
return !isBlockOccludingLight(block?.typeId ?? null);
}
export function collectLightSources (chunkX, chunkY, data)
{
const sources = [];
@@ -3,6 +3,7 @@ import { GroundType, GroundType, BlockType, BlockType, isBlockPassable, isBlockPassable, isBlockOccludingLight, isGroundPassable, isGroundPassable, blockLightRange, blockLightRange, normalizeGround, normalizeGround,@@ -156,6 +157,17 @@ export function isChunkTilePassable (data, localX, localY) return isBlockPassable(block?.typeId ?? null); return isBlockPassable(block?.typeId ?? null);}}/** Ground + block clear for light rays (furniture may be impassable but not occluding). */export function isChunkTileClearForLight (data, localX, localY){ const index = tileIndex(localX, localY); const ground = normalizeGround(data.grounds[index]); if (!isGroundPassable(ground.typeId)) { return false; } const block = data.blocks[index]; return !isBlockOccludingLight(block?.typeId ?? null);}export function collectLightSources (chunkX, chunkY, data)export function collectLightSources (chunkX, chunkY, data){{ const sources = []; const sources = [];@@ -0,0 +1,172 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
NeighborBit,
computeNeighborConnectMask,
neighborConnectStateName,
parseNeighborConnectMask,
composeNeighborConnectState,
neighborConnectBlocksMatch,
parseMaterialNeighborConnectState
} from "../../shared/world/neighborConnect.js";
import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";
import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";
import { BlockType, BLOCK_DEFINITIONS } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
import { Component } from "../src/ecs/components.js";
test("neighbor connect masks cover all NESW combinations", () =>
{
assert.equal(neighborConnectStateName(0), "0");
assert.equal(neighborConnectStateName(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w), "15");
assert.equal(parseNeighborConnectMask("6"), NeighborBit.e | NeighborBit.s);
const mask = computeNeighborConnectMask((dx, dy) => dx === 1 || dy === -1);
assert.equal(mask, NeighborBit.n | NeighborBit.e);
});
test("material neighbor-connect states keep wood id and only match same material", () =>
{
const def = BLOCK_DEFINITIONS[BlockType.table];
assert.equal(composeNeighborConnectState(def, "oak", 3), "oak-3");
assert.deepEqual(parseMaterialNeighborConnectState("birch-10", def), { material: "birch", mask: 10 });
const pine = { typeId: BlockType.table, state: "pine-0" };
const pineNeighbor = { typeId: BlockType.table, state: "pine-2" };
const oakNeighbor = { typeId: BlockType.table, state: "oak-2" };
assert.equal(neighborConnectBlocksMatch(pine, pineNeighbor, def), true);
assert.equal(neighborConnectBlocksMatch(pine, oakNeighbor, def), false);
});
test("CE staff entries include sex labels and pickExchangeClerk returns a name", () =>
{
assert.ok(CENTRAL_EXCHANGE_STAFF.length >= 2);
for (const staff of CENTRAL_EXCHANGE_STAFF)
{
assert.ok(staff.name);
assert.ok(staff.sex === "male" || staff.sex === "female");
}
const name = pickExchangeClerk(() => 0);
assert.equal(name, CENTRAL_EXCHANGE_STAFF[0].name);
});
test("central exchange spawner config locks staff count and strips shop options", () =>
{
const config = normalizeSpawnerConfig({
mobTypeId: MobId.centralExchange,
maxAlive: 2,
sells: [{ itemId: ItemId.apple, quantity: 1 }],
buysItems: true,
displayName: "ignored"
}, "ce:0");
assert.equal(config.centralExchange, true);
assert.equal(config.maxAlive, CENTRAL_EXCHANGE_STAFF.length);
assert.equal(config.sells.length, 0);
assert.equal(config.buysItems, false);
assert.equal(isCentralExchangeSpawner(config), true);
});
test("central exchange spawner places every clerk with matching names", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const data = createEmptyChunkData();
data.open = true;
data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
data.spawners = [{
localX: 8,
localY: 8,
config: normalizeSpawnerConfig({
mobTypeId: MobId.centralExchange,
spawnRangeTiles: 6,
maxWanderRangeTiles: 6,
equipment: { chest: ItemId.clothShirt }
}, "ce-test")
}];
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
harness.simulation.reloadWorld();
harness.advance(50);
for (let i = 0; i < 30; i++)
{ harness.simulation.step(); }
const record = harness.simulation.entityRecord(
harness.simulation.spawnCharacter(1, makeCharacter(harness.stateDb, { tileX: 7, tileY: 7 }))
);
const worker = harness.simulation.workers[record.workerId];
for (let i = 0; i < 40; i++)
{ harness.simulation.step(); }
const clerks = [];
for (const entity of worker.world.ecs.query(Component.spawnOrigin, Component.appearance))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
clerks.push(entity.appearance.firstName);
}
assert.equal(clerks.length, CENTRAL_EXCHANGE_STAFF.length);
for (const staff of CENTRAL_EXCHANGE_STAFF)
{ assert.ok(clerks.includes(staff.name), staff.name); }
}
finally
{ harness.close(); }
});
test("opening the market stations a CE clerk on the opposite side of the counter", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const data = createEmptyChunkData();
data.open = true;
// Counter at (9,8); player will stand at (8,8); staff station = (10,8).
data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
data.spawners = [{
localX: 12,
localY: 8,
config: normalizeSpawnerConfig({
mobTypeId: MobId.centralExchange,
spawnRangeTiles: 8,
maxWanderRangeTiles: 8
}, "ce-station")
}];
harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const funded = addCoinsToSlots(emptySlots(), 10);
harness.stateDb.saveBag(character.character_id, {
inventory: funded.slots,
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
const playerId = harness.simulation.spawnCharacter(1, character);
for (let i = 0; i < 40; i++)
{ harness.simulation.step(); }
harness.simulation.enqueue(1, {
type: "open-market",
characterId: character.character_id
});
harness.simulation.step();
const record = harness.simulation.entityRecord(playerId);
const worker = harness.simulation.workers[record.workerId];
let stationed = false;
for (const entity of worker.world.ecs.query(Component.spawnOrigin))
{
if (!entity.spawnOrigin?.centralExchange)
{ continue; }
if (entity.spawnOrigin.stationTileX === 10 && entity.spawnOrigin.stationTileY === 8)
{ stationed = true; }
}
assert.equal(stationed, true);
}
finally
{ harness.close(); }
});
@@ -0,0 +1,172 @@import test from "node:test";import assert from "node:assert/strict";import { NeighborBit, computeNeighborConnectMask, neighborConnectStateName, parseNeighborConnectMask, composeNeighborConnectState, neighborConnectBlocksMatch, parseMaterialNeighborConnectState} from "../../shared/world/neighborConnect.js";import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";import { BlockType, BLOCK_DEFINITIONS } from "../../shared/definitions/tiles.js";import { ItemId } from "../../shared/definitions/items.js";import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { CHUNK_SIZE } from "../../shared/protocol/constants.js";import { Component } from "../src/ecs/components.js";test("neighbor connect masks cover all NESW combinations", () =>{ assert.equal(neighborConnectStateName(0), "0"); assert.equal(neighborConnectStateName(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w), "15"); assert.equal(parseNeighborConnectMask("6"), NeighborBit.e | NeighborBit.s); const mask = computeNeighborConnectMask((dx, dy) => dx === 1 || dy === -1); assert.equal(mask, NeighborBit.n | NeighborBit.e);});test("material neighbor-connect states keep wood id and only match same material", () =>{ const def = BLOCK_DEFINITIONS[BlockType.table]; assert.equal(composeNeighborConnectState(def, "oak", 3), "oak-3"); assert.deepEqual(parseMaterialNeighborConnectState("birch-10", def), { material: "birch", mask: 10 }); const pine = { typeId: BlockType.table, state: "pine-0" }; const pineNeighbor = { typeId: BlockType.table, state: "pine-2" }; const oakNeighbor = { typeId: BlockType.table, state: "oak-2" }; assert.equal(neighborConnectBlocksMatch(pine, pineNeighbor, def), true); assert.equal(neighborConnectBlocksMatch(pine, oakNeighbor, def), false);});test("CE staff entries include sex labels and pickExchangeClerk returns a name", () =>{ assert.ok(CENTRAL_EXCHANGE_STAFF.length >= 2); for (const staff of CENTRAL_EXCHANGE_STAFF) { assert.ok(staff.name); assert.ok(staff.sex === "male" || staff.sex === "female"); } const name = pickExchangeClerk(() => 0); assert.equal(name, CENTRAL_EXCHANGE_STAFF[0].name);});test("central exchange spawner config locks staff count and strips shop options", () =>{ const config = normalizeSpawnerConfig({ mobTypeId: MobId.centralExchange, maxAlive: 2, sells: [{ itemId: ItemId.apple, quantity: 1 }], buysItems: true, displayName: "ignored" }, "ce:0"); assert.equal(config.centralExchange, true); assert.equal(config.maxAlive, CENTRAL_EXCHANGE_STAFF.length); assert.equal(config.sells.length, 0); assert.equal(config.buysItems, false); assert.equal(isCentralExchangeSpawner(config), true);});test("central exchange spawner places every clerk with matching names", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const data = createEmptyChunkData(); data.open = true; data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" }; data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null }; data.spawners = [{ localX: 8, localY: 8, config: normalizeSpawnerConfig({ mobTypeId: MobId.centralExchange, spawnRangeTiles: 6, maxWanderRangeTiles: 6, equipment: { chest: ItemId.clothShirt } }, "ce-test") }]; harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data)); harness.simulation.reloadWorld(); harness.advance(50); for (let i = 0; i < 30; i++) { harness.simulation.step(); } const record = harness.simulation.entityRecord( harness.simulation.spawnCharacter(1, makeCharacter(harness.stateDb, { tileX: 7, tileY: 7 })) ); const worker = harness.simulation.workers[record.workerId]; for (let i = 0; i < 40; i++) { harness.simulation.step(); } const clerks = []; for (const entity of worker.world.ecs.query(Component.spawnOrigin, Component.appearance)) { if (!entity.spawnOrigin?.centralExchange) { continue; } clerks.push(entity.appearance.firstName); } assert.equal(clerks.length, CENTRAL_EXCHANGE_STAFF.length); for (const staff of CENTRAL_EXCHANGE_STAFF) { assert.ok(clerks.includes(staff.name), staff.name); } } finally { harness.close(); }});test("opening the market stations a CE clerk on the opposite side of the counter", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const data = createEmptyChunkData(); data.open = true; // Counter at (9,8); player will stand at (8,8); staff station = (10,8). data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" }; data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null }; data.spawners = [{ localX: 12, localY: 8, config: normalizeSpawnerConfig({ mobTypeId: MobId.centralExchange, spawnRangeTiles: 8, maxWanderRangeTiles: 8 }, "ce-station") }]; harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data)); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const funded = addCoinsToSlots(emptySlots(), 10); harness.stateDb.saveBag(character.character_id, { inventory: funded.slots, equipment: emptyEquipment(), vault: [], vaultReserved: [] }); const playerId = harness.simulation.spawnCharacter(1, character); for (let i = 0; i < 40; i++) { harness.simulation.step(); } harness.simulation.enqueue(1, { type: "open-market", characterId: character.character_id }); harness.simulation.step(); const record = harness.simulation.entityRecord(playerId); const worker = harness.simulation.workers[record.workerId]; let stationed = false; for (const entity of worker.world.ecs.query(Component.spawnOrigin)) { if (!entity.spawnOrigin?.centralExchange) { continue; } if (entity.spawnOrigin.stationTileX === 10 && entity.spawnOrigin.stationTileY === 8) { stationed = true; } } assert.equal(stationed, true); } finally { harness.close(); }});@@ -55,3 +55,40 @@ test("dynamic lights use the same wall occlusion as baked light", () =>
assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
});
test("tables and marketplace counters do not occlude light rays", () =>
{
const origin = createEmptyChunkData();
origin.open = true;
origin.blocks[0] = { typeId: BlockType.torch, config: null };
origin.blocks[1] = { typeId: BlockType.table, state: "pine-0", config: null };
origin.blocks[2] = { typeId: BlockType.marketplace, state: "0", config: null };
const baked = bakeLightMaps(0, 0, (x, y) =>
{
if (x === 0 && y === 0)
{ return origin; }
return createEmptyChunkData();
}, 8);
const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
assert.ok(self.light[3] > 0, "light passes through table and counter");
});
test("anvil occludes light by default (omit blocksLight)", () =>
{
const origin = createEmptyChunkData();
origin.open = true;
origin.blocks[0] = { typeId: BlockType.torch, config: null };
origin.blocks[1] = { typeId: BlockType.anvil, config: null };
const baked = bakeLightMaps(0, 0, (x, y) =>
{
if (x === 0 && y === 0)
{ return origin; }
return createEmptyChunkData();
}, 8);
const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
assert.equal(self.light[2], 0, "tile behind anvil stays unlit");
});
@@ -55,3 +55,40 @@ test("dynamic lights use the same wall occlusion as baked light", () => assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0); assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0); assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0); assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);});});test("tables and marketplace counters do not occlude light rays", () =>{ const origin = createEmptyChunkData(); origin.open = true; origin.blocks[0] = { typeId: BlockType.torch, config: null }; origin.blocks[1] = { typeId: BlockType.table, state: "pine-0", config: null }; origin.blocks[2] = { typeId: BlockType.marketplace, state: "0", config: null }; const baked = bakeLightMaps(0, 0, (x, y) => { if (x === 0 && y === 0) { return origin; } return createEmptyChunkData(); }, 8); const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data; assert.ok(self.light[3] > 0, "light passes through table and counter");});test("anvil occludes light by default (omit blocksLight)", () =>{ const origin = createEmptyChunkData(); origin.open = true; origin.blocks[0] = { typeId: BlockType.torch, config: null }; origin.blocks[1] = { typeId: BlockType.anvil, config: null }; const baked = bakeLightMaps(0, 0, (x, y) => { if (x === 0 && y === 0) { return origin; } return createEmptyChunkData(); }, 8); const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data; assert.equal(self.light[2], 0, "tile behind anvil stays unlit");});@@ -3,7 +3,8 @@ import assert from "node:assert/strict";
import { ItemId } from "../../shared/definitions/items.js";
import { BlockType } from "../../shared/definitions/tiles.js";
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";
import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js";
import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
@@ -42,6 +43,42 @@ test("midpoint trade price rounds half units deterministically", () =>
assert.equal(midpointTradePrice(80, 100), 90);
});
test("listing fee is 3% of notional rounded up", () =>
{
assert.equal(marketOrderListingFee(100, 1), 3);
assert.equal(marketOrderListingFee(10, 1), 1);
assert.equal(marketOrderListingFee(8, 2), 1);
assert.equal(marketOrderListingFee(0, 5), 0);
});
test("market funds spend whole coin cheques and return change", () =>
{
const slots = emptySlots();
slots[0] = {
itemId: ItemId.filledCheque,
quantity: 1,
instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
};
const paid = takeMarketFunds(slots, 25);
assert.equal(paid.ok, true);
assert.equal(paid.change, 15);
assert.equal(paid.redeemedCheques.length, 1);
assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
});
test("written cheque sell listing locks quantity to reserved goods", () =>
{
const listing = resolveMarketSellListing({
itemId: ItemId.filledCheque,
quantity: 1,
instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
});
assert.equal(listing.isCheque, true);
assert.equal(listing.itemId, ItemId.apple);
assert.equal(listing.quantity, 7);
assert.equal(listing.quantityLocked, true);
});
function placePlaza (worldDb)
{
const data = createEmptyChunkData();
@@ -61,8 +98,9 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
const sellerBag = addCoinsToSlots(emptySlots(), 0);
sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 };
const sellerBag = addCoinsToSlots(emptySlots(), 5);
assert.equal(sellerBag.ok, true);
sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
harness.stateDb.saveBag(seller.character_id, {
inventory: sellerBag.slots,
equipment: emptyEquipment(),
@@ -85,7 +123,7 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
harness.simulation.enqueue(1, {
type: "place-market-sell",
characterId: seller.character_id,
slotIndex: 0,
slotIndex: 1,
quantity: 2,
minUnitPrice: 8
});
@@ -3,7 +3,8 @@ import assert from "node:assert/strict";import { ItemId } from "../../shared/definitions/items.js";import { ItemId } from "../../shared/definitions/items.js";import { BlockType } from "../../shared/definitions/tiles.js";import { BlockType } from "../../shared/definitions/tiles.js";import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js";import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";@@ -42,6 +43,42 @@ test("midpoint trade price rounds half units deterministically", () => assert.equal(midpointTradePrice(80, 100), 90); assert.equal(midpointTradePrice(80, 100), 90);});});test("listing fee is 3% of notional rounded up", () =>{ assert.equal(marketOrderListingFee(100, 1), 3); assert.equal(marketOrderListingFee(10, 1), 1); assert.equal(marketOrderListingFee(8, 2), 1); assert.equal(marketOrderListingFee(0, 5), 0);});test("market funds spend whole coin cheques and return change", () =>{ const slots = emptySlots(); slots[0] = { itemId: ItemId.filledCheque, quantity: 1, instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 } }; const paid = takeMarketFunds(slots, 25); assert.equal(paid.ok, true); assert.equal(paid.change, 15); assert.equal(paid.redeemedCheques.length, 1); assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);});test("written cheque sell listing locks quantity to reserved goods", () =>{ const listing = resolveMarketSellListing({ itemId: ItemId.filledCheque, quantity: 1, instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 } }); assert.equal(listing.isCheque, true); assert.equal(listing.itemId, ItemId.apple); assert.equal(listing.quantity, 7); assert.equal(listing.quantityLocked, true);});function placePlaza (worldDb)function placePlaza (worldDb){{ const data = createEmptyChunkData(); const data = createEmptyChunkData();@@ -61,8 +98,9 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" }); const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" }); const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" }); const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" }); const sellerBag = addCoinsToSlots(emptySlots(), 0); const sellerBag = addCoinsToSlots(emptySlots(), 5); sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 }; assert.equal(sellerBag.ok, true); sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 }; harness.stateDb.saveBag(seller.character_id, { harness.stateDb.saveBag(seller.character_id, { inventory: sellerBag.slots, inventory: sellerBag.slots, equipment: emptyEquipment(), equipment: emptyEquipment(),@@ -85,7 +123,7 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p harness.simulation.enqueue(1, { harness.simulation.enqueue(1, { type: "place-market-sell", type: "place-market-sell", characterId: seller.character_id, characterId: seller.character_id, slotIndex: 0, slotIndex: 1, quantity: 2, quantity: 2, minUnitPrice: 8 minUnitPrice: 8 }); });