BlueGit

timfa questward

rweaks

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
2b34e2dd88be028525ce825a1ab688bf5c9277bd
Parent
3682f91c
61 files changed +2005 −165
client/assets/blocks/marketplace/0.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/10.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/11.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/12.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/13.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/14.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/15.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/4.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/5.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/6.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/7.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/8.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/9.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/marketplace/marketplace.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/0.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/10.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/11.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/12.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/13.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/14.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/15.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/3.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/4.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/5.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/6.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/7.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/8.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/9.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/table/wood.png added Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +33 −27
@@ -227,35 +227,41 @@
227 227 <button id="market-close" type="button">Close</button>
228 228 </header>
229 229 <p id="market-hint" class="hint"></p>
230 <p id="market-coins" class="shop-coins">Coins: 0</p>
231 <section class="market-section">
232 <h3>Your orders</h3>
230 <p id="market-coins" class="shop-coins">Funds: 0</p>
231 <div class="market-tabs" role="tablist">
232 <button id="market-tab-orders" type="button" class="market-tab active" data-tab="orders">Your Orders</button>
233 <button id="market-tab-sell" type="button" class="market-tab" data-tab="sell">Sell</button>
234 <button id="market-tab-buy" type="button" class="market-tab" data-tab="buy">Buy</button>
235 </div>
236 <section id="market-pane-orders" class="market-pane" data-pane="orders">
233 237 <div id="market-orders"></div>
234 238 </section>
235 <section class="market-section market-columns">
236 <div>
237 <h3>Buy order</h3>
238 <div id="market-catalog" class="market-catalog"></div>
239 <p id="market-buy-item" class="hint">Select an item</p>
240 <label class="send-row">Quantity
241 <input id="market-buy-qty" type="number" min="1" step="1" value="1">
242 </label>
243 <label class="send-row">Max unit price
244 <input id="market-buy-max" type="number" min="1" step="1" value="1">
245 </label>
246 <button id="market-buy-confirm" type="button">Place buy order</button>
247 </div>
248 <div>
249 <h3>Sell order</h3>
250 <div id="market-sell-list" class="market-sell-list"></div>
251 <label class="send-row">Quantity
252 <input id="market-sell-qty" type="number" min="1" step="1" value="1">
253 </label>
254 <label class="send-row">Min unit price
255 <input id="market-sell-min" type="number" min="1" step="1" value="1">
256 </label>
257 <button id="market-sell-confirm" type="button">Place sell order</button>
258 </div>
239 <section id="market-pane-sell" class="market-pane" data-pane="sell" hidden>
240 <div id="market-sell-list" class="market-sell-list"></div>
241 <p id="market-sell-selected" class="hint">Select an item from your bag</p>
242 <label class="send-row">Quantity
243 <input id="market-sell-qty" type="number" min="1" step="1" value="1">
244 </label>
245 <label class="send-row">Min unit price
246 <input id="market-sell-min" type="number" min="1" step="1" value="1">
247 </label>
248 <p id="market-sell-fee" class="hint"></p>
249 <button id="market-sell-confirm" type="button">Place sell order</button>
250 </section>
251 <section id="market-pane-buy" class="market-pane" data-pane="buy" hidden>
252 <label class="send-row">Search items
253 <input id="market-buy-search" type="search" placeholder="Type a name and press Enter" autocomplete="off">
254 </label>
255 <div id="market-catalog" class="market-catalog"></div>
256 <p id="market-buy-item" class="hint">Search and select an item</p>
257 <label class="send-row">Quantity
258 <input id="market-buy-qty" type="number" min="1" step="1" value="1">
259 </label>
260 <label class="send-row">Max unit price
261 <input id="market-buy-max" type="number" min="1" step="1" value="1">
262 </label>
263 <p id="market-buy-fee" class="hint"></p>
264 <button id="market-buy-confirm" type="button">Place buy order</button>
259 265 </section>
260 266 </aside>
261 267
@@ -227,35 +227,41 @@
227 <button id="market-close" type="button">Close</button>
227 <button id="market-close" type="button">Close</button>
228 </header>
228 </header>
229 <p id="market-hint" class="hint"></p>
229 <p id="market-hint" class="hint"></p>
230 <p id="market-coins" class="shop-coins">Coins: 0</p>
230 <p id="market-coins" class="shop-coins">Funds: 0</p>
231 <section class="market-section">
231 <div class="market-tabs" role="tablist">
232 <h3>Your orders</h3>
232 <button id="market-tab-orders" type="button" class="market-tab active" data-tab="orders">Your Orders</button>
233 <button id="market-tab-sell" type="button" class="market-tab" data-tab="sell">Sell</button>
234 <button id="market-tab-buy" type="button" class="market-tab" data-tab="buy">Buy</button>
235 </div>
236 <section id="market-pane-orders" class="market-pane" data-pane="orders">
233 <div id="market-orders"></div>
237 <div id="market-orders"></div>
234 </section>
238 </section>
235 <section class="market-section market-columns">
239 <section id="market-pane-sell" class="market-pane" data-pane="sell" hidden>
236 <div>
240 <div id="market-sell-list" class="market-sell-list"></div>
237 <h3>Buy order</h3>
241 <p id="market-sell-selected" class="hint">Select an item from your bag</p>
238 <div id="market-catalog" class="market-catalog"></div>
242 <label class="send-row">Quantity
239 <p id="market-buy-item" class="hint">Select an item</p>
243 <input id="market-sell-qty" type="number" min="1" step="1" value="1">
240 <label class="send-row">Quantity
244 </label>
241 <input id="market-buy-qty" type="number" min="1" step="1" value="1">
245 <label class="send-row">Min unit price
242 </label>
246 <input id="market-sell-min" type="number" min="1" step="1" value="1">
243 <label class="send-row">Max unit price
247 </label>
244 <input id="market-buy-max" type="number" min="1" step="1" value="1">
248 <p id="market-sell-fee" class="hint"></p>
245 </label>
249 <button id="market-sell-confirm" type="button">Place sell order</button>
246 <button id="market-buy-confirm" type="button">Place buy order</button>
250 </section>
247 </div>
251 <section id="market-pane-buy" class="market-pane" data-pane="buy" hidden>
248 <div>
252 <label class="send-row">Search items
249 <h3>Sell order</h3>
253 <input id="market-buy-search" type="search" placeholder="Type a name and press Enter" autocomplete="off">
250 <div id="market-sell-list" class="market-sell-list"></div>
254 </label>
251 <label class="send-row">Quantity
255 <div id="market-catalog" class="market-catalog"></div>
252 <input id="market-sell-qty" type="number" min="1" step="1" value="1">
256 <p id="market-buy-item" class="hint">Search and select an item</p>
253 </label>
257 <label class="send-row">Quantity
254 <label class="send-row">Min unit price
258 <input id="market-buy-qty" type="number" min="1" step="1" value="1">
255 <input id="market-sell-min" type="number" min="1" step="1" value="1">
259 </label>
256 </label>
260 <label class="send-row">Max unit price
257 <button id="market-sell-confirm" type="button">Place sell order</button>
261 <input id="market-buy-max" type="number" min="1" step="1" value="1">
258 </div>
262 </label>
263 <p id="market-buy-fee" class="hint"></p>
264 <button id="market-buy-confirm" type="button">Place buy order</button>
259 </section>
265 </section>
260 </aside>
266 </aside>
261
267
client/scripts/generate-counter-sprites.mjs added +199 −0
@@ -0,0 +1,199 @@
1 /**
2 * Generate 16×16 top-down wooden counter PNGs for neighbor-connect masks 0–15.
3 * Perspective: orthographic top-down (grid-aligned, not diamond isometric).
4 * Connections remove the shared edge rim so adjacent tiles read as one counter.
5 */
6 import { mkdirSync, writeFileSync } from "node:fs";
7 import { deflateSync } from "node:zlib";
8 import { fileURLToPath } from "node:url";
9 import { dirname, join } from "node:path";
10 import { NeighborBit } from "../../shared/world/neighborConnect.js";
11
12 const SIZE = 16;
13 const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/marketplace");
14
15 /** Wood palette (RGBA). */
16 const RIM = [92, 58, 32, 255];
17 const RIM_DARK = [62, 38, 20, 255];
18 const TOP = [196, 148, 78, 255];
19 const TOP_LIGHT = [214, 170, 98, 255];
20 const TOP_SHADE = [168, 120, 58, 255];
21 const GRAIN = [180, 132, 64, 255];
22
23 function crcTable ()
24 {
25 const table = new Uint32Array(256);
26 for (let n = 0; n < 256; n++)
27 {
28 let c = n;
29 for (let k = 0; k < 8; k++)
30 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
31 table[n] = c >>> 0;
32 }
33 return table;
34 }
35
36 const CRC_TABLE = crcTable();
37
38 function crc32 (buf)
39 {
40 let c = 0xffffffff;
41 for (let i = 0; i < buf.length; i++)
42 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
43 return (c ^ 0xffffffff) >>> 0;
44 }
45
46 function chunk (type, data)
47 {
48 const len = Buffer.alloc(4);
49 len.writeUInt32BE(data.length);
50 const typeBuf = Buffer.from(type, "ascii");
51 const crcBuf = Buffer.alloc(4);
52 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
53 return Buffer.concat([len, typeBuf, data, crcBuf]);
54 }
55
56 function encodePng (rgba)
57 {
58 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
59 for (let y = 0; y < SIZE; y++)
60 {
61 const row = y * (SIZE * 4 + 1);
62 raw[row] = 0;
63 for (let x = 0; x < SIZE; x++)
64 {
65 const i = (y * SIZE + x) * 4;
66 const o = row + 1 + x * 4;
67 raw[o] = rgba[i];
68 raw[o + 1] = rgba[i + 1];
69 raw[o + 2] = rgba[i + 2];
70 raw[o + 3] = rgba[i + 3];
71 }
72 }
73 const ihdr = Buffer.alloc(13);
74 ihdr.writeUInt32BE(SIZE, 0);
75 ihdr.writeUInt32BE(SIZE, 4);
76 ihdr[8] = 8;
77 ihdr[9] = 6;
78 ihdr[10] = 0;
79 ihdr[11] = 0;
80 ihdr[12] = 0;
81 return Buffer.concat([
82 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
83 chunk("IHDR", ihdr),
84 chunk("IDAT", deflateSync(raw, { level: 9 })),
85 chunk("IEND", Buffer.alloc(0))
86 ]);
87 }
88
89 function setPx (rgba, x, y, color)
90 {
91 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
92 { return; }
93 const i = (y * SIZE + x) * 4;
94 rgba[i] = color[0];
95 rgba[i + 1] = color[1];
96 rgba[i + 2] = color[2];
97 rgba[i + 3] = color[3];
98 }
99
100 function fillRect (rgba, x0, y0, x1, y1, color)
101 {
102 for (let y = y0; y <= y1; y++)
103 {
104 for (let x = x0; x <= x1; x++)
105 { setPx(rgba, x, y, color); }
106 }
107 }
108
109 function paintCounter (mask)
110 {
111 const rgba = new Uint8Array(SIZE * SIZE * 4);
112 const connectN = (mask & NeighborBit.n) !== 0;
113 const connectE = (mask & NeighborBit.e) !== 0;
114 const connectS = (mask & NeighborBit.s) !== 0;
115 const connectW = (mask & NeighborBit.w) !== 0;
116
117 const topY0 = connectN ? 0 : 2;
118 const topY1 = connectS ? SIZE - 1 : SIZE - 3;
119 const topX0 = connectW ? 0 : 2;
120 const topX1 = connectE ? SIZE - 1 : SIZE - 3;
121
122 // Base fill transparent then rim body where not connected.
123 for (let i = 0; i < rgba.length; i += 4)
124 { rgba[i + 3] = 0; }
125
126 // Outer rim (only on non-connected sides).
127 if (!connectN)
128 { fillRect(rgba, 0, 0, SIZE - 1, 1, RIM_DARK); }
129 if (!connectS)
130 { fillRect(rgba, 0, SIZE - 2, SIZE - 1, SIZE - 1, RIM_DARK); }
131 if (!connectW)
132 { fillRect(rgba, 0, 0, 1, SIZE - 1, RIM_DARK); }
133 if (!connectE)
134 { fillRect(rgba, SIZE - 2, 0, SIZE - 1, SIZE - 1, RIM_DARK); }
135
136 // Inner rim bevel
137 if (!connectN)
138 { fillRect(rgba, topX0, 1, topX1, 1, RIM); }
139 if (!connectS)
140 { fillRect(rgba, topX0, SIZE - 2, topX1, SIZE - 2, RIM); }
141 if (!connectW)
142 { fillRect(rgba, 1, topY0, 1, topY1, RIM); }
143 if (!connectE)
144 { fillRect(rgba, SIZE - 2, topY0, SIZE - 2, topY1, RIM); }
145
146 // Countertop
147 fillRect(rgba, topX0, topY0, topX1, topY1, TOP);
148 // Subtle grain / highlight
149 for (let y = topY0; y <= topY1; y++)
150 {
151 for (let x = topX0; x <= topX1; x++)
152 {
153 if (((x + y * 3) % 7) === 0)
154 { setPx(rgba, x, y, GRAIN); }
155 if (y === topY0 && !connectN)
156 { setPx(rgba, x, y, TOP_LIGHT); }
157 if (y === topY1 && !connectS)
158 { setPx(rgba, x, y, TOP_SHADE); }
159 }
160 }
161
162 // Corner posts when both adjacent sides are free (standalone corners).
163 const corners = [
164 { x: 0, y: 0, n: connectN, w: connectW },
165 { x: SIZE - 1, y: 0, n: connectN, e: connectE },
166 { x: 0, y: SIZE - 1, s: connectS, w: connectW },
167 { x: SIZE - 1, y: SIZE - 1, s: connectS, e: connectE }
168 ];
169 for (const c of corners)
170 {
171 const openN = c.n === false || c.n == null;
172 const openS = c.s === false || c.s == null;
173 const openE = c.e === false || c.e == null;
174 const openW = c.w === false || c.w == null;
175 if ((c.n != null || c.s != null) && (c.e != null || c.w != null))
176 {
177 const vertOpen = (c.n != null ? !c.n : !c.s);
178 const horzOpen = (c.e != null ? !c.e : !c.w);
179 if (vertOpen && horzOpen)
180 { setPx(rgba, c.x, c.y, RIM_DARK); }
181 }
182 void openN;
183 void openS;
184 void openE;
185 void openW;
186 }
187
188 return rgba;
189 }
190
191 mkdirSync(OUT, { recursive: true });
192 for (let mask = 0; mask < 16; mask++)
193 {
194 const png = encodePng(paintCounter(mask));
195 writeFileSync(join(OUT, `${mask}.png`), png);
196 }
197 // Keep legacy fallback name pointing at isolated counter.
198 writeFileSync(join(OUT, "marketplace.png"), encodePng(paintCounter(0)));
199 console.log(`Wrote marketplace counter sprites 0–15 to ${OUT}`);
@@ -0,0 +1,199 @@
1/**
2 * Generate 16×16 top-down wooden counter PNGs for neighbor-connect masks 0–15.
3 * Perspective: orthographic top-down (grid-aligned, not diamond isometric).
4 * Connections remove the shared edge rim so adjacent tiles read as one counter.
5 */
6import { mkdirSync, writeFileSync } from "node:fs";
7import { deflateSync } from "node:zlib";
8import { fileURLToPath } from "node:url";
9import { dirname, join } from "node:path";
10import { NeighborBit } from "../../shared/world/neighborConnect.js";
11
12const SIZE = 16;
13const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/marketplace");
14
15/** Wood palette (RGBA). */
16const RIM = [92, 58, 32, 255];
17const RIM_DARK = [62, 38, 20, 255];
18const TOP = [196, 148, 78, 255];
19const TOP_LIGHT = [214, 170, 98, 255];
20const TOP_SHADE = [168, 120, 58, 255];
21const GRAIN = [180, 132, 64, 255];
22
23function crcTable ()
24{
25 const table = new Uint32Array(256);
26 for (let n = 0; n < 256; n++)
27 {
28 let c = n;
29 for (let k = 0; k < 8; k++)
30 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
31 table[n] = c >>> 0;
32 }
33 return table;
34}
35
36const CRC_TABLE = crcTable();
37
38function crc32 (buf)
39{
40 let c = 0xffffffff;
41 for (let i = 0; i < buf.length; i++)
42 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
43 return (c ^ 0xffffffff) >>> 0;
44}
45
46function chunk (type, data)
47{
48 const len = Buffer.alloc(4);
49 len.writeUInt32BE(data.length);
50 const typeBuf = Buffer.from(type, "ascii");
51 const crcBuf = Buffer.alloc(4);
52 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
53 return Buffer.concat([len, typeBuf, data, crcBuf]);
54}
55
56function encodePng (rgba)
57{
58 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
59 for (let y = 0; y < SIZE; y++)
60 {
61 const row = y * (SIZE * 4 + 1);
62 raw[row] = 0;
63 for (let x = 0; x < SIZE; x++)
64 {
65 const i = (y * SIZE + x) * 4;
66 const o = row + 1 + x * 4;
67 raw[o] = rgba[i];
68 raw[o + 1] = rgba[i + 1];
69 raw[o + 2] = rgba[i + 2];
70 raw[o + 3] = rgba[i + 3];
71 }
72 }
73 const ihdr = Buffer.alloc(13);
74 ihdr.writeUInt32BE(SIZE, 0);
75 ihdr.writeUInt32BE(SIZE, 4);
76 ihdr[8] = 8;
77 ihdr[9] = 6;
78 ihdr[10] = 0;
79 ihdr[11] = 0;
80 ihdr[12] = 0;
81 return Buffer.concat([
82 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
83 chunk("IHDR", ihdr),
84 chunk("IDAT", deflateSync(raw, { level: 9 })),
85 chunk("IEND", Buffer.alloc(0))
86 ]);
87}
88
89function setPx (rgba, x, y, color)
90{
91 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
92 { return; }
93 const i = (y * SIZE + x) * 4;
94 rgba[i] = color[0];
95 rgba[i + 1] = color[1];
96 rgba[i + 2] = color[2];
97 rgba[i + 3] = color[3];
98}
99
100function fillRect (rgba, x0, y0, x1, y1, color)
101{
102 for (let y = y0; y <= y1; y++)
103 {
104 for (let x = x0; x <= x1; x++)
105 { setPx(rgba, x, y, color); }
106 }
107}
108
109function paintCounter (mask)
110{
111 const rgba = new Uint8Array(SIZE * SIZE * 4);
112 const connectN = (mask & NeighborBit.n) !== 0;
113 const connectE = (mask & NeighborBit.e) !== 0;
114 const connectS = (mask & NeighborBit.s) !== 0;
115 const connectW = (mask & NeighborBit.w) !== 0;
116
117 const topY0 = connectN ? 0 : 2;
118 const topY1 = connectS ? SIZE - 1 : SIZE - 3;
119 const topX0 = connectW ? 0 : 2;
120 const topX1 = connectE ? SIZE - 1 : SIZE - 3;
121
122 // Base fill transparent then rim body where not connected.
123 for (let i = 0; i < rgba.length; i += 4)
124 { rgba[i + 3] = 0; }
125
126 // Outer rim (only on non-connected sides).
127 if (!connectN)
128 { fillRect(rgba, 0, 0, SIZE - 1, 1, RIM_DARK); }
129 if (!connectS)
130 { fillRect(rgba, 0, SIZE - 2, SIZE - 1, SIZE - 1, RIM_DARK); }
131 if (!connectW)
132 { fillRect(rgba, 0, 0, 1, SIZE - 1, RIM_DARK); }
133 if (!connectE)
134 { fillRect(rgba, SIZE - 2, 0, SIZE - 1, SIZE - 1, RIM_DARK); }
135
136 // Inner rim bevel
137 if (!connectN)
138 { fillRect(rgba, topX0, 1, topX1, 1, RIM); }
139 if (!connectS)
140 { fillRect(rgba, topX0, SIZE - 2, topX1, SIZE - 2, RIM); }
141 if (!connectW)
142 { fillRect(rgba, 1, topY0, 1, topY1, RIM); }
143 if (!connectE)
144 { fillRect(rgba, SIZE - 2, topY0, SIZE - 2, topY1, RIM); }
145
146 // Countertop
147 fillRect(rgba, topX0, topY0, topX1, topY1, TOP);
148 // Subtle grain / highlight
149 for (let y = topY0; y <= topY1; y++)
150 {
151 for (let x = topX0; x <= topX1; x++)
152 {
153 if (((x + y * 3) % 7) === 0)
154 { setPx(rgba, x, y, GRAIN); }
155 if (y === topY0 && !connectN)
156 { setPx(rgba, x, y, TOP_LIGHT); }
157 if (y === topY1 && !connectS)
158 { setPx(rgba, x, y, TOP_SHADE); }
159 }
160 }
161
162 // Corner posts when both adjacent sides are free (standalone corners).
163 const corners = [
164 { x: 0, y: 0, n: connectN, w: connectW },
165 { x: SIZE - 1, y: 0, n: connectN, e: connectE },
166 { x: 0, y: SIZE - 1, s: connectS, w: connectW },
167 { x: SIZE - 1, y: SIZE - 1, s: connectS, e: connectE }
168 ];
169 for (const c of corners)
170 {
171 const openN = c.n === false || c.n == null;
172 const openS = c.s === false || c.s == null;
173 const openE = c.e === false || c.e == null;
174 const openW = c.w === false || c.w == null;
175 if ((c.n != null || c.s != null) && (c.e != null || c.w != null))
176 {
177 const vertOpen = (c.n != null ? !c.n : !c.s);
178 const horzOpen = (c.e != null ? !c.e : !c.w);
179 if (vertOpen && horzOpen)
180 { setPx(rgba, c.x, c.y, RIM_DARK); }
181 }
182 void openN;
183 void openS;
184 void openE;
185 void openW;
186 }
187
188 return rgba;
189}
190
191mkdirSync(OUT, { recursive: true });
192for (let mask = 0; mask < 16; mask++)
193{
194 const png = encodePng(paintCounter(mask));
195 writeFileSync(join(OUT, `${mask}.png`), png);
196}
197// Keep legacy fallback name pointing at isolated counter.
198writeFileSync(join(OUT, "marketplace.png"), encodePng(paintCounter(0)));
199console.log(`Wrote marketplace counter sprites 0–15 to ${OUT}`);
client/scripts/generate-table-sprites.mjs added +289 −0
@@ -0,0 +1,289 @@
1 /**
2 * Generate 16×16 magenta table PNGs for neighbor-connect masks 0–15.
3 * Reads the artist `wood.png`, remaps browns → magenta (tintable), then
4 * extends the tabletop along connected cardinals (no diagonals).
5 * Legs stay on free south edges; extra legs appear on long spans.
6 */
7 import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
8 import { deflateSync, inflateSync } from "node:zlib";
9 import { fileURLToPath } from "node:url";
10 import { dirname, join } from "node:path";
11 import { NeighborBit } from "../../shared/world/neighborConnect.js";
12
13 const SIZE = 16;
14 const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/table");
15 const SOURCE = join(OUT, "wood.png");
16
17 /** Base tabletop AABB in the artist sprite (inclusive). */
18 const BASE = Object.freeze({
19 x0: 3,
20 x1: 12,
21 y0: 2,
22 y1: 11
23 });
24
25 function crcTable ()
26 {
27 const table = new Uint32Array(256);
28 for (let n = 0; n < 256; n++)
29 {
30 let c = n;
31 for (let k = 0; k < 8; k++)
32 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
33 table[n] = c >>> 0;
34 }
35 return table;
36 }
37
38 const CRC_TABLE = crcTable();
39
40 function crc32 (buf)
41 {
42 let c = 0xffffffff;
43 for (let i = 0; i < buf.length; i++)
44 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
45 return (c ^ 0xffffffff) >>> 0;
46 }
47
48 function chunk (type, data)
49 {
50 const len = Buffer.alloc(4);
51 len.writeUInt32BE(data.length);
52 const typeBuf = Buffer.from(type, "ascii");
53 const crcBuf = Buffer.alloc(4);
54 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
55 return Buffer.concat([len, typeBuf, data, crcBuf]);
56 }
57
58 function encodePng (rgba)
59 {
60 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
61 for (let y = 0; y < SIZE; y++)
62 {
63 const row = y * (SIZE * 4 + 1);
64 raw[row] = 0;
65 for (let x = 0; x < SIZE; x++)
66 {
67 const i = (y * SIZE + x) * 4;
68 const o = row + 1 + x * 4;
69 raw[o] = rgba[i];
70 raw[o + 1] = rgba[i + 1];
71 raw[o + 2] = rgba[i + 2];
72 raw[o + 3] = rgba[i + 3];
73 }
74 }
75 const ihdr = Buffer.alloc(13);
76 ihdr.writeUInt32BE(SIZE, 0);
77 ihdr.writeUInt32BE(SIZE, 4);
78 ihdr[8] = 8;
79 ihdr[9] = 6;
80 ihdr[10] = 0;
81 ihdr[11] = 0;
82 ihdr[12] = 0;
83 return Buffer.concat([
84 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
85 chunk("IHDR", ihdr),
86 chunk("IDAT", deflateSync(raw, { level: 9 })),
87 chunk("IEND", Buffer.alloc(0))
88 ]);
89 }
90
91 function decodePngRgba (buf)
92 {
93 let off = 8;
94 let w = 0;
95 let h = 0;
96 const idat = [];
97 while (off < buf.length)
98 {
99 const len = buf.readUInt32BE(off);
100 const type = buf.slice(off + 4, off + 8).toString("ascii");
101 const data = buf.slice(off + 8, off + 8 + len);
102 if (type === "IHDR")
103 {
104 w = data.readUInt32BE(0);
105 h = data.readUInt32BE(4);
106 }
107 else if (type === "IDAT")
108 { idat.push(data); }
109 else if (type === "IEND")
110 { break; }
111 off += 12 + len;
112 }
113 if (w !== SIZE || h !== SIZE)
114 { throw new Error(`Expected ${SIZE}×${SIZE} PNG, got ${w}×${h}`); }
115 const raw = inflateSync(Buffer.concat(idat));
116 const stride = 1 + SIZE * 4;
117 const rgba = new Uint8Array(SIZE * SIZE * 4);
118 for (let y = 0; y < SIZE; y++)
119 {
120 for (let x = 0; x < SIZE; x++)
121 {
122 const i = y * stride + 1 + x * 4;
123 const o = (y * SIZE + x) * 4;
124 rgba[o] = raw[i];
125 rgba[o + 1] = raw[i + 1];
126 rgba[o + 2] = raw[i + 2];
127 rgba[o + 3] = raw[i + 3];
128 }
129 }
130 return rgba;
131 }
132
133 function getPx (rgba, x, y)
134 {
135 const i = (y * SIZE + x) * 4;
136 return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
137 }
138
139 function setPx (rgba, x, y, color)
140 {
141 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
142 { return; }
143 const i = (y * SIZE + x) * 4;
144 rgba[i] = color[0];
145 rgba[i + 1] = color[1];
146 rgba[i + 2] = color[2];
147 rgba[i + 3] = color[3];
148 }
149
150 /** Remap any opaque pixel into the magenta tint family (R≈B, G<R). */
151 function toMagenta (r, g, b, a)
152 {
153 if (a < 8)
154 { return [0, 0, 0, 0]; }
155 const L = Math.max(1, Math.max(r, g, b));
156 const minC = Math.min(r, g, b);
157 const chroma = (L - minC) / 255;
158 // Slight G softens grain; keep rims more saturated (low G).
159 const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22)));
160 return [L, Math.max(0, gMag), L, 255];
161 }
162
163 function magentaize (src)
164 {
165 const out = new Uint8Array(src.length);
166 for (let i = 0; i < src.length; i += 4)
167 {
168 const [r, g, b, a] = toMagenta(src[i], src[i + 1], src[i + 2], src[i + 3]);
169 out[i] = r;
170 out[i + 1] = g;
171 out[i + 2] = b;
172 out[i + 3] = a;
173 }
174 return out;
175 }
176
177 function sampleTop (base, x, y)
178 {
179 const sx = Math.min(BASE.x1, Math.max(BASE.x0, x));
180 const sy = Math.min(BASE.y1, Math.max(BASE.y0, y));
181 return getPx(base, sx, sy);
182 }
183
184 function drawLeg (rgba, base, anchorX, topY)
185 {
186 // Artist legs: 3×2 under the top at (4,12) and (9,12).
187 const pattern = [
188 [getPx(base, 4, 12), getPx(base, 5, 12), getPx(base, 6, 12)],
189 [getPx(base, 4, 13), getPx(base, 5, 13), getPx(base, 6, 13)]
190 ];
191 for (let ly = 0; ly < 2; ly++)
192 {
193 const y = topY + 1 + ly;
194 if (y >= SIZE)
195 { break; }
196 for (let lx = 0; lx < 3; lx++)
197 { setPx(rgba, anchorX + lx, y, pattern[ly][lx]); }
198 }
199 }
200
201 function paintTable (mask, base)
202 {
203 const rgba = new Uint8Array(SIZE * SIZE * 4);
204 const connectN = (mask & NeighborBit.n) !== 0;
205 const connectE = (mask & NeighborBit.e) !== 0;
206 const connectS = (mask & NeighborBit.s) !== 0;
207 const connectW = (mask & NeighborBit.w) !== 0;
208
209 if (mask === 0)
210 {
211 rgba.set(base);
212 return rgba;
213 }
214
215 const topX0 = connectW ? 0 : BASE.x0;
216 const topX1 = connectE ? SIZE - 1 : BASE.x1;
217 const topY0 = connectN ? 0 : BASE.y0;
218 const topY1 = connectS ? SIZE - 1 : BASE.y1;
219
220 for (let y = topY0; y <= topY1; y++)
221 {
222 for (let x = topX0; x <= topX1; x++)
223 {
224 const onN = y === topY0 && !connectN;
225 const onS = y === topY1 && !connectS;
226 const onW = x === topX0 && !connectW;
227 const onE = x === topX1 && !connectE;
228 let color;
229 if (onN)
230 { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y0); }
231 else if (onS)
232 { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y1); }
233 else if (onW)
234 { color = sampleTop(base, BASE.x0, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
235 else if (onE)
236 { color = sampleTop(base, BASE.x1, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
237 else
238 {
239 // Interior: wrap the artist's fill so long spans keep grain.
240 const ix = BASE.x0 + 1 + ((x - topX0) % (BASE.x1 - BASE.x0 - 1));
241 const iy = BASE.y0 + 1 + ((y - topY0) % (BASE.y1 - BASE.y0 - 1));
242 color = sampleTop(base, ix, iy);
243 }
244 setPx(rgba, x, y, color);
245 }
246 }
247
248 // Front legs only when this tile is a south terminus (perspective).
249 if (!connectS && topY1 + 2 < SIZE)
250 {
251 const span = topX1 - topX0 + 1;
252 const anchors = [];
253 if (span <= 10)
254 {
255 anchors.push(topX0 + 1);
256 anchors.push(Math.max(topX0 + 1, topX1 - 3));
257 }
258 else
259 {
260 for (let x = topX0 + 1; x <= topX1 - 3; x += 5)
261 { anchors.push(x); }
262 const last = topX1 - 3;
263 if (anchors[anchors.length - 1] !== last)
264 { anchors.push(last); }
265 }
266 const seen = new Set();
267 for (const ax of anchors)
268 {
269 if (seen.has(ax))
270 { continue; }
271 seen.add(ax);
272 drawLeg(rgba, base, ax, topY1);
273 }
274 }
275
276 return rgba;
277 }
278
279 const source = decodePngRgba(readFileSync(SOURCE));
280 const base = magentaize(source);
281
282 mkdirSync(OUT, { recursive: true });
283 // Replace artist wood.png with magenta base (same silhouette).
284 writeFileSync(SOURCE, encodePng(base));
285 for (let mask = 0; mask < 16; mask++)
286 {
287 writeFileSync(join(OUT, `${mask}.png`), encodePng(paintTable(mask, base)));
288 }
289 console.log(`Wrote magenta table sprites wood.png + 0–15 to ${OUT}`);
@@ -0,0 +1,289 @@
1/**
2 * Generate 16×16 magenta table PNGs for neighbor-connect masks 0–15.
3 * Reads the artist `wood.png`, remaps browns → magenta (tintable), then
4 * extends the tabletop along connected cardinals (no diagonals).
5 * Legs stay on free south edges; extra legs appear on long spans.
6 */
7import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
8import { deflateSync, inflateSync } from "node:zlib";
9import { fileURLToPath } from "node:url";
10import { dirname, join } from "node:path";
11import { NeighborBit } from "../../shared/world/neighborConnect.js";
12
13const SIZE = 16;
14const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/table");
15const SOURCE = join(OUT, "wood.png");
16
17/** Base tabletop AABB in the artist sprite (inclusive). */
18const BASE = Object.freeze({
19 x0: 3,
20 x1: 12,
21 y0: 2,
22 y1: 11
23});
24
25function crcTable ()
26{
27 const table = new Uint32Array(256);
28 for (let n = 0; n < 256; n++)
29 {
30 let c = n;
31 for (let k = 0; k < 8; k++)
32 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
33 table[n] = c >>> 0;
34 }
35 return table;
36}
37
38const CRC_TABLE = crcTable();
39
40function crc32 (buf)
41{
42 let c = 0xffffffff;
43 for (let i = 0; i < buf.length; i++)
44 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
45 return (c ^ 0xffffffff) >>> 0;
46}
47
48function chunk (type, data)
49{
50 const len = Buffer.alloc(4);
51 len.writeUInt32BE(data.length);
52 const typeBuf = Buffer.from(type, "ascii");
53 const crcBuf = Buffer.alloc(4);
54 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
55 return Buffer.concat([len, typeBuf, data, crcBuf]);
56}
57
58function encodePng (rgba)
59{
60 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
61 for (let y = 0; y < SIZE; y++)
62 {
63 const row = y * (SIZE * 4 + 1);
64 raw[row] = 0;
65 for (let x = 0; x < SIZE; x++)
66 {
67 const i = (y * SIZE + x) * 4;
68 const o = row + 1 + x * 4;
69 raw[o] = rgba[i];
70 raw[o + 1] = rgba[i + 1];
71 raw[o + 2] = rgba[i + 2];
72 raw[o + 3] = rgba[i + 3];
73 }
74 }
75 const ihdr = Buffer.alloc(13);
76 ihdr.writeUInt32BE(SIZE, 0);
77 ihdr.writeUInt32BE(SIZE, 4);
78 ihdr[8] = 8;
79 ihdr[9] = 6;
80 ihdr[10] = 0;
81 ihdr[11] = 0;
82 ihdr[12] = 0;
83 return Buffer.concat([
84 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
85 chunk("IHDR", ihdr),
86 chunk("IDAT", deflateSync(raw, { level: 9 })),
87 chunk("IEND", Buffer.alloc(0))
88 ]);
89}
90
91function decodePngRgba (buf)
92{
93 let off = 8;
94 let w = 0;
95 let h = 0;
96 const idat = [];
97 while (off < buf.length)
98 {
99 const len = buf.readUInt32BE(off);
100 const type = buf.slice(off + 4, off + 8).toString("ascii");
101 const data = buf.slice(off + 8, off + 8 + len);
102 if (type === "IHDR")
103 {
104 w = data.readUInt32BE(0);
105 h = data.readUInt32BE(4);
106 }
107 else if (type === "IDAT")
108 { idat.push(data); }
109 else if (type === "IEND")
110 { break; }
111 off += 12 + len;
112 }
113 if (w !== SIZE || h !== SIZE)
114 { throw new Error(`Expected ${SIZE}×${SIZE} PNG, got ${w}×${h}`); }
115 const raw = inflateSync(Buffer.concat(idat));
116 const stride = 1 + SIZE * 4;
117 const rgba = new Uint8Array(SIZE * SIZE * 4);
118 for (let y = 0; y < SIZE; y++)
119 {
120 for (let x = 0; x < SIZE; x++)
121 {
122 const i = y * stride + 1 + x * 4;
123 const o = (y * SIZE + x) * 4;
124 rgba[o] = raw[i];
125 rgba[o + 1] = raw[i + 1];
126 rgba[o + 2] = raw[i + 2];
127 rgba[o + 3] = raw[i + 3];
128 }
129 }
130 return rgba;
131}
132
133function getPx (rgba, x, y)
134{
135 const i = (y * SIZE + x) * 4;
136 return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
137}
138
139function setPx (rgba, x, y, color)
140{
141 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
142 { return; }
143 const i = (y * SIZE + x) * 4;
144 rgba[i] = color[0];
145 rgba[i + 1] = color[1];
146 rgba[i + 2] = color[2];
147 rgba[i + 3] = color[3];
148}
149
150/** Remap any opaque pixel into the magenta tint family (R≈B, G<R). */
151function toMagenta (r, g, b, a)
152{
153 if (a < 8)
154 { return [0, 0, 0, 0]; }
155 const L = Math.max(1, Math.max(r, g, b));
156 const minC = Math.min(r, g, b);
157 const chroma = (L - minC) / 255;
158 // Slight G softens grain; keep rims more saturated (low G).
159 const gMag = Math.min(L - 1, Math.round(L * (0.08 + (1 - chroma) * 0.22)));
160 return [L, Math.max(0, gMag), L, 255];
161}
162
163function magentaize (src)
164{
165 const out = new Uint8Array(src.length);
166 for (let i = 0; i < src.length; i += 4)
167 {
168 const [r, g, b, a] = toMagenta(src[i], src[i + 1], src[i + 2], src[i + 3]);
169 out[i] = r;
170 out[i + 1] = g;
171 out[i + 2] = b;
172 out[i + 3] = a;
173 }
174 return out;
175}
176
177function sampleTop (base, x, y)
178{
179 const sx = Math.min(BASE.x1, Math.max(BASE.x0, x));
180 const sy = Math.min(BASE.y1, Math.max(BASE.y0, y));
181 return getPx(base, sx, sy);
182}
183
184function drawLeg (rgba, base, anchorX, topY)
185{
186 // Artist legs: 3×2 under the top at (4,12) and (9,12).
187 const pattern = [
188 [getPx(base, 4, 12), getPx(base, 5, 12), getPx(base, 6, 12)],
189 [getPx(base, 4, 13), getPx(base, 5, 13), getPx(base, 6, 13)]
190 ];
191 for (let ly = 0; ly < 2; ly++)
192 {
193 const y = topY + 1 + ly;
194 if (y >= SIZE)
195 { break; }
196 for (let lx = 0; lx < 3; lx++)
197 { setPx(rgba, anchorX + lx, y, pattern[ly][lx]); }
198 }
199}
200
201function paintTable (mask, base)
202{
203 const rgba = new Uint8Array(SIZE * SIZE * 4);
204 const connectN = (mask & NeighborBit.n) !== 0;
205 const connectE = (mask & NeighborBit.e) !== 0;
206 const connectS = (mask & NeighborBit.s) !== 0;
207 const connectW = (mask & NeighborBit.w) !== 0;
208
209 if (mask === 0)
210 {
211 rgba.set(base);
212 return rgba;
213 }
214
215 const topX0 = connectW ? 0 : BASE.x0;
216 const topX1 = connectE ? SIZE - 1 : BASE.x1;
217 const topY0 = connectN ? 0 : BASE.y0;
218 const topY1 = connectS ? SIZE - 1 : BASE.y1;
219
220 for (let y = topY0; y <= topY1; y++)
221 {
222 for (let x = topX0; x <= topX1; x++)
223 {
224 const onN = y === topY0 && !connectN;
225 const onS = y === topY1 && !connectS;
226 const onW = x === topX0 && !connectW;
227 const onE = x === topX1 && !connectE;
228 let color;
229 if (onN)
230 { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y0); }
231 else if (onS)
232 { color = sampleTop(base, Math.min(BASE.x1, Math.max(BASE.x0, x)), BASE.y1); }
233 else if (onW)
234 { color = sampleTop(base, BASE.x0, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
235 else if (onE)
236 { color = sampleTop(base, BASE.x1, Math.min(BASE.y1, Math.max(BASE.y0, y))); }
237 else
238 {
239 // Interior: wrap the artist's fill so long spans keep grain.
240 const ix = BASE.x0 + 1 + ((x - topX0) % (BASE.x1 - BASE.x0 - 1));
241 const iy = BASE.y0 + 1 + ((y - topY0) % (BASE.y1 - BASE.y0 - 1));
242 color = sampleTop(base, ix, iy);
243 }
244 setPx(rgba, x, y, color);
245 }
246 }
247
248 // Front legs only when this tile is a south terminus (perspective).
249 if (!connectS && topY1 + 2 < SIZE)
250 {
251 const span = topX1 - topX0 + 1;
252 const anchors = [];
253 if (span <= 10)
254 {
255 anchors.push(topX0 + 1);
256 anchors.push(Math.max(topX0 + 1, topX1 - 3));
257 }
258 else
259 {
260 for (let x = topX0 + 1; x <= topX1 - 3; x += 5)
261 { anchors.push(x); }
262 const last = topX1 - 3;
263 if (anchors[anchors.length - 1] !== last)
264 { anchors.push(last); }
265 }
266 const seen = new Set();
267 for (const ax of anchors)
268 {
269 if (seen.has(ax))
270 { continue; }
271 seen.add(ax);
272 drawLeg(rgba, base, ax, topY1);
273 }
274 }
275
276 return rgba;
277}
278
279const source = decodePngRgba(readFileSync(SOURCE));
280const base = magentaize(source);
281
282mkdirSync(OUT, { recursive: true });
283// Replace artist wood.png with magenta base (same silhouette).
284writeFileSync(SOURCE, encodePng(base));
285for (let mask = 0; mask < 16; mask++)
286{
287 writeFileSync(join(OUT, `${mask}.png`), encodePng(paintTable(mask, base)));
288}
289console.log(`Wrote magenta table sprites wood.png + 0–15 to ${OUT}`);
client/src/editor/main.js +70 −2
@@ -17,6 +17,12 @@ import {
17 17 placeableStatesForType
18 18 } from "/shared/world/season.js";
19 19 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
20 import {
21 computeNeighborConnectMask,
22 composeNeighborConnectState,
23 definitionUsesNeighborConnect,
24 neighborConnectBlocksMatch
25 } from "/shared/world/neighborConnect.js";
20 26 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
21 27 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
22 28 import { WorldView } from "../render/worldView.js";
@@ -167,7 +173,18 @@ function paintAt (localX, localY)
167 173 if (tool.kind === "ground")
168 174 { draft.grounds[index] = { typeId: tool.typeId, state }; }
169 175 else if (tool.kind === "erase")
170 { draft.blocks[index] = null; }
176 {
177 const removed = draft.blocks[index];
178 draft.blocks[index] = null;
179 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
180 ground: draft.grounds[index],
181 block: draft.blocks[index],
182 light: draft.light[index]
183 });
184 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
185 { refreshNeighborConnect(localX, localY, removed.typeId); }
186 return;
187 }
171 188 else if (tool.kind === "spawner")
172 189 {
173 190 const existing = spawnerAt(localX, localY);
@@ -188,7 +205,21 @@ function paintAt (localX, localY)
188 205 return;
189 206 }
190 207 else
191 { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; }
208 {
209 const def = BLOCK_DEFINITIONS[tool.typeId];
210 const nextState = definitionUsesNeighborConnect(def)
211 ? composeNeighborConnectState(def, state, 0)
212 : state;
213 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
214 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
215 ground: draft.grounds[index],
216 block: draft.blocks[index],
217 light: draft.light[index]
218 });
219 if (definitionUsesNeighborConnect(def))
220 { refreshNeighborConnect(localX, localY, tool.typeId); }
221 return;
222 }
192 223 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
193 224 ground: draft.grounds[index],
194 225 block: draft.blocks[index],
@@ -196,6 +227,41 @@ function paintAt (localX, localY)
196 227 });
197 228 }
198 229
230 /** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
231 function refreshNeighborConnect (localX, localY, typeId)
232 {
233 const def = BLOCK_DEFINITIONS[typeId];
234 if (!draft || !definitionUsesNeighborConnect(def))
235 { return; }
236 const cells = [[localX, localY]];
237 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
238 { cells.push([localX + dx, localY + dy]); }
239 for (const [lx, ly] of cells)
240 {
241 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
242 { continue; }
243 const index = ly * CHUNK_SIZE + lx;
244 const block = draft.blocks[index];
245 if (!block || block.typeId !== typeId)
246 { continue; }
247 const mask = computeNeighborConnectMask((dx, dy) =>
248 {
249 const nx = lx + dx;
250 const ny = ly + dy;
251 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
252 { return false; }
253 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
254 return neighborConnectBlocksMatch(block, neighbor, def);
255 });
256 block.state = composeNeighborConnectState(def, block.state, mask);
257 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
258 ground: draft.grounds[index],
259 block: draft.blocks[index],
260 light: draft.light[index]
261 });
262 }
263 }
264
199 265 function updateRevisionUI ()
200 266 {
201 267 const applyBtn = $("apply");
@@ -659,6 +725,8 @@ function cycleToolState (direction)
659 725 { return; }
660 726 const layer = tool.kind === "ground" ? "ground" : "block";
661 727 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
728 if (definitionUsesNeighborConnect(def))
729 { return; }
662 730 const allStates = statesForType(catalog, layer, def.key);
663 731 const seasonal = seasonalCycleStates(allStates);
664 732 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
@@ -17,6 +17,12 @@ import {
17 placeableStatesForType
17 placeableStatesForType
18} from "/shared/world/season.js";
18} from "/shared/world/season.js";
19import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
19import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
20import {
21 computeNeighborConnectMask,
22 composeNeighborConnectState,
23 definitionUsesNeighborConnect,
24 neighborConnectBlocksMatch
25} from "/shared/world/neighborConnect.js";
20import { GameSocket, defaultSocketUrl } from "../net/socket.js";
26import { GameSocket, defaultSocketUrl } from "../net/socket.js";
21import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
27import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
22import { WorldView } from "../render/worldView.js";
28import { WorldView } from "../render/worldView.js";
@@ -167,7 +173,18 @@ function paintAt (localX, localY)
167 if (tool.kind === "ground")
173 if (tool.kind === "ground")
168 { draft.grounds[index] = { typeId: tool.typeId, state }; }
174 { draft.grounds[index] = { typeId: tool.typeId, state }; }
169 else if (tool.kind === "erase")
175 else if (tool.kind === "erase")
170 { draft.blocks[index] = null; }
176 {
177 const removed = draft.blocks[index];
178 draft.blocks[index] = null;
179 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
180 ground: draft.grounds[index],
181 block: draft.blocks[index],
182 light: draft.light[index]
183 });
184 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
185 { refreshNeighborConnect(localX, localY, removed.typeId); }
186 return;
187 }
171 else if (tool.kind === "spawner")
188 else if (tool.kind === "spawner")
172 {
189 {
173 const existing = spawnerAt(localX, localY);
190 const existing = spawnerAt(localX, localY);
@@ -188,7 +205,21 @@ function paintAt (localX, localY)
188 return;
205 return;
189 }
206 }
190 else
207 else
191 { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; }
208 {
209 const def = BLOCK_DEFINITIONS[tool.typeId];
210 const nextState = definitionUsesNeighborConnect(def)
211 ? composeNeighborConnectState(def, state, 0)
212 : state;
213 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
214 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
215 ground: draft.grounds[index],
216 block: draft.blocks[index],
217 light: draft.light[index]
218 });
219 if (definitionUsesNeighborConnect(def))
220 { refreshNeighborConnect(localX, localY, tool.typeId); }
221 return;
222 }
192 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
223 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
193 ground: draft.grounds[index],
224 ground: draft.grounds[index],
194 block: draft.blocks[index],
225 block: draft.blocks[index],
@@ -196,6 +227,41 @@ function paintAt (localX, localY)
196 });
227 });
197}
228}
198
229
230/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
231function refreshNeighborConnect (localX, localY, typeId)
232{
233 const def = BLOCK_DEFINITIONS[typeId];
234 if (!draft || !definitionUsesNeighborConnect(def))
235 { return; }
236 const cells = [[localX, localY]];
237 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
238 { cells.push([localX + dx, localY + dy]); }
239 for (const [lx, ly] of cells)
240 {
241 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
242 { continue; }
243 const index = ly * CHUNK_SIZE + lx;
244 const block = draft.blocks[index];
245 if (!block || block.typeId !== typeId)
246 { continue; }
247 const mask = computeNeighborConnectMask((dx, dy) =>
248 {
249 const nx = lx + dx;
250 const ny = ly + dy;
251 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
252 { return false; }
253 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
254 return neighborConnectBlocksMatch(block, neighbor, def);
255 });
256 block.state = composeNeighborConnectState(def, block.state, mask);
257 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
258 ground: draft.grounds[index],
259 block: draft.blocks[index],
260 light: draft.light[index]
261 });
262 }
263}
264
199function updateRevisionUI ()
265function updateRevisionUI ()
200{
266{
201 const applyBtn = $("apply");
267 const applyBtn = $("apply");
@@ -659,6 +725,8 @@ function cycleToolState (direction)
659 { return; }
725 { return; }
660 const layer = tool.kind === "ground" ? "ground" : "block";
726 const layer = tool.kind === "ground" ? "ground" : "block";
661 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
727 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
728 if (definitionUsesNeighborConnect(def))
729 { return; }
662 const allStates = statesForType(catalog, layer, def.key);
730 const allStates = statesForType(catalog, layer, def.key);
663 const seasonal = seasonalCycleStates(allStates);
731 const seasonal = seasonalCycleStates(allStates);
664 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
732 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
client/src/editor/tileConfigModal.js +69 −42
@@ -5,8 +5,10 @@ import {
5 5 listSpawnableMobTypes,
6 6 normalizeSpawnerConfig,
7 7 MobId,
8 isHumanoidMob
8 isHumanoidMob,
9 isCentralExchangeSpawner
9 10 } from "/shared/definitions/mobs.js";
11 import { centralExchangeStaffCount } from "/shared/market/exchange.js";
10 12 import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11 13 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12 14 import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
@@ -152,10 +154,21 @@ export function initTileConfigModal ({ onSave, onRemove })
152 154 const wrap = document.createElement("div");
153 155 wrap.className = "spawner-humanoid-fields";
154 156 wrap.dataset.humanoid = "1";
155 wrap.append(
156 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
157 field("Sex", sexSelect("sex", config.sex))
158 );
157 const exchange = isCentralExchangeSpawner(config);
158 if (exchange)
159 {
160 const note = document.createElement("p");
161 note.className = "hint";
162 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
163 wrap.append(note);
164 }
165 else
166 {
167 wrap.append(
168 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
169 field("Sex", sexSelect("sex", config.sex))
170 );
171 }
159 172 for (const slot of EQUIPMENT_SLOTS)
160 173 {
161 174 wrap.append(field(
@@ -163,47 +176,52 @@ export function initTileConfigModal ({ onSave, onRemove })
163 176 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
164 177 ));
165 178 }
166 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
179 if (!exchange)
180 {
181 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
167 182
168 const sellsHeader = document.createElement("div");
169 sellsHeader.className = "spawner-sells-header";
170 const sellsTitle = document.createElement("strong");
171 sellsTitle.textContent = "Sells";
172 const addBtn = document.createElement("button");
173 addBtn.type = "button";
174 addBtn.textContent = "+";
175 addBtn.title = "Add item";
176 addBtn.addEventListener("click", () => openItemSearch());
177 sellsHeader.append(sellsTitle, addBtn);
178 wrap.append(sellsHeader);
183 const sellsHeader = document.createElement("div");
184 sellsHeader.className = "spawner-sells-header";
185 const sellsTitle = document.createElement("strong");
186 sellsTitle.textContent = "Sells";
187 const addBtn = document.createElement("button");
188 addBtn.type = "button";
189 addBtn.textContent = "+";
190 addBtn.title = "Add item";
191 addBtn.addEventListener("click", () => openItemSearch());
192 sellsHeader.append(sellsTitle, addBtn);
193 wrap.append(sellsHeader);
179 194
180 const list = document.createElement("div");
181 list.className = "spawner-sells-list";
182 list.dataset.sellsList = "1";
183 wrap.append(list);
195 const list = document.createElement("div");
196 list.className = "spawner-sells-list";
197 list.dataset.sellsList = "1";
198 wrap.append(list);
184 199
185 const buysLabel = document.createElement("label");
186 buysLabel.className = "spawner-buys-row";
187 const buys = document.createElement("input");
188 buys.type = "checkbox";
189 buys.name = "buysItems";
190 buys.checked = !!config.buysItems;
191 buysLabel.append(buys, document.createTextNode(" Buys items"));
192 wrap.append(buysLabel);
200 const buysLabel = document.createElement("label");
201 buysLabel.className = "spawner-buys-row";
202 const buys = document.createElement("input");
203 buys.type = "checkbox";
204 buys.name = "buysItems";
205 buys.checked = !!config.buysItems;
206 buysLabel.append(buys, document.createTextNode(" Buys items"));
207 wrap.append(buysLabel);
193 208
194 const hint = document.createElement("p");
195 hint.className = "hint";
196 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.";
197 wrap.append(hint);
209 const hint = document.createElement("p");
210 hint.className = "hint";
211 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.";
212 wrap.append(hint);
198 213
199 sellsDraft = (config.sells ?? []).map((line) =>
200 {
201 if (line && typeof line === "object")
202 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
203 return { itemId: line | 0, quantity: 0 };
204 }).filter((line) => line.itemId > 0);
214 sellsDraft = (config.sells ?? []).map((line) =>
215 {
216 if (line && typeof line === "object")
217 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
218 return { itemId: line | 0, quantity: 0 };
219 }).filter((line) => line.itemId > 0);
205 220
206 queueMicrotask(() => renderSellsList());
221 queueMicrotask(() => renderSellsList());
222 }
223 else
224 { sellsDraft = []; }
207 225 return wrap;
208 226 }
209 227
@@ -217,8 +235,16 @@ export function initTileConfigModal ({ onSave, onRemove })
217 235 return;
218 236 }
219 237 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
220 mobTypeId: MobId.humanoid
238 mobTypeId: mobTypeId || MobId.humanoid
221 239 }, "spawner")));
240 const maxAlive = form.querySelector('[name="maxAlive"]');
241 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
242 {
243 maxAlive.value = String(centralExchangeStaffCount());
244 maxAlive.disabled = true;
245 }
246 else if (maxAlive)
247 { maxAlive.disabled = false; }
222 248 }
223 249
224 250 function openSpawner (ctx)
@@ -289,7 +315,8 @@ export function initTileConfigModal ({ onSave, onRemove })
289 315 equipment,
290 316 sells: sellsDraft,
291 317 buysItems: data.get("buysItems") === "on",
292 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
318 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
319 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
293 320 }, context.config.spawnerId));
294 321 show(false);
295 322 });
@@ -5,8 +5,10 @@ import {
5 listSpawnableMobTypes,
5 listSpawnableMobTypes,
6 normalizeSpawnerConfig,
6 normalizeSpawnerConfig,
7 MobId,
7 MobId,
8 isHumanoidMob
8 isHumanoidMob,
9 isCentralExchangeSpawner
9} from "/shared/definitions/mobs.js";
10} from "/shared/definitions/mobs.js";
11import { centralExchangeStaffCount } from "/shared/market/exchange.js";
10import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
12import { ItemId, itemDefinition, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
11import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
13import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
12import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
14import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
@@ -152,10 +154,21 @@ export function initTileConfigModal ({ onSave, onRemove })
152 const wrap = document.createElement("div");
154 const wrap = document.createElement("div");
153 wrap.className = "spawner-humanoid-fields";
155 wrap.className = "spawner-humanoid-fields";
154 wrap.dataset.humanoid = "1";
156 wrap.dataset.humanoid = "1";
155 wrap.append(
157 const exchange = isCentralExchangeSpawner(config);
156 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
158 if (exchange)
157 field("Sex", sexSelect("sex", config.sex))
159 {
158 );
160 const note = document.createElement("p");
161 note.className = "hint";
162 note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`;
163 wrap.append(note);
164 }
165 else
166 {
167 wrap.append(
168 field("Display name", textInput("displayName", config.displayName || "Shopkeeper")),
169 field("Sex", sexSelect("sex", config.sex))
170 );
171 }
159 for (const slot of EQUIPMENT_SLOTS)
172 for (const slot of EQUIPMENT_SLOTS)
160 {
173 {
161 wrap.append(field(
174 wrap.append(field(
@@ -163,47 +176,52 @@ export function initTileConfigModal ({ onSave, onRemove })
163 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
176 equipSelect(`equipment.${slot}`, slot, config.equipment?.[slot] ?? null)
164 ));
177 ));
165 }
178 }
166 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
179 if (!exchange)
180 {
181 wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01)));
167
182
168 const sellsHeader = document.createElement("div");
183 const sellsHeader = document.createElement("div");
169 sellsHeader.className = "spawner-sells-header";
184 sellsHeader.className = "spawner-sells-header";
170 const sellsTitle = document.createElement("strong");
185 const sellsTitle = document.createElement("strong");
171 sellsTitle.textContent = "Sells";
186 sellsTitle.textContent = "Sells";
172 const addBtn = document.createElement("button");
187 const addBtn = document.createElement("button");
173 addBtn.type = "button";
188 addBtn.type = "button";
174 addBtn.textContent = "+";
189 addBtn.textContent = "+";
175 addBtn.title = "Add item";
190 addBtn.title = "Add item";
176 addBtn.addEventListener("click", () => openItemSearch());
191 addBtn.addEventListener("click", () => openItemSearch());
177 sellsHeader.append(sellsTitle, addBtn);
192 sellsHeader.append(sellsTitle, addBtn);
178 wrap.append(sellsHeader);
193 wrap.append(sellsHeader);
179
194
180 const list = document.createElement("div");
195 const list = document.createElement("div");
181 list.className = "spawner-sells-list";
196 list.className = "spawner-sells-list";
182 list.dataset.sellsList = "1";
197 list.dataset.sellsList = "1";
183 wrap.append(list);
198 wrap.append(list);
184
199
185 const buysLabel = document.createElement("label");
200 const buysLabel = document.createElement("label");
186 buysLabel.className = "spawner-buys-row";
201 buysLabel.className = "spawner-buys-row";
187 const buys = document.createElement("input");
202 const buys = document.createElement("input");
188 buys.type = "checkbox";
203 buys.type = "checkbox";
189 buys.name = "buysItems";
204 buys.name = "buysItems";
190 buys.checked = !!config.buysItems;
205 buys.checked = !!config.buysItems;
191 buysLabel.append(buys, document.createTextNode(" Buys items"));
206 buysLabel.append(buys, document.createTextNode(" Buys items"));
192 wrap.append(buysLabel);
207 wrap.append(buysLabel);
193
208
194 const hint = document.createElement("p");
209 const hint = document.createElement("p");
195 hint.className = "hint";
210 hint.className = "hint";
196 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.";
211 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.";
197 wrap.append(hint);
212 wrap.append(hint);
198
213
199 sellsDraft = (config.sells ?? []).map((line) =>
214 sellsDraft = (config.sells ?? []).map((line) =>
200 {
215 {
201 if (line && typeof line === "object")
216 if (line && typeof line === "object")
202 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
217 { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; }
203 return { itemId: line | 0, quantity: 0 };
218 return { itemId: line | 0, quantity: 0 };
204 }).filter((line) => line.itemId > 0);
219 }).filter((line) => line.itemId > 0);
205
220
206 queueMicrotask(() => renderSellsList());
221 queueMicrotask(() => renderSellsList());
222 }
223 else
224 { sellsDraft = []; }
207 return wrap;
225 return wrap;
208 }
226 }
209
227
@@ -217,8 +235,16 @@ export function initTileConfigModal ({ onSave, onRemove })
217 return;
235 return;
218 }
236 }
219 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
237 form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({
220 mobTypeId: MobId.humanoid
238 mobTypeId: mobTypeId || MobId.humanoid
221 }, "spawner")));
239 }, "spawner")));
240 const maxAlive = form.querySelector('[name="maxAlive"]');
241 if (maxAlive && isCentralExchangeSpawner({ mobTypeId }))
242 {
243 maxAlive.value = String(centralExchangeStaffCount());
244 maxAlive.disabled = true;
245 }
246 else if (maxAlive)
247 { maxAlive.disabled = false; }
222 }
248 }
223
249
224 function openSpawner (ctx)
250 function openSpawner (ctx)
@@ -289,7 +315,8 @@ export function initTileConfigModal ({ onSave, onRemove })
289 equipment,
315 equipment,
290 sells: sellsDraft,
316 sells: sellsDraft,
291 buysItems: data.get("buysItems") === "on",
317 buysItems: data.get("buysItems") === "on",
292 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9)
318 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
319 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
293 }, context.config.spawnerId));
320 }, context.config.spawnerId));
294 show(false);
321 show(false);
295 });
322 });
client/src/play/market.js +157 −7
@@ -4,6 +4,8 @@ import {
4 4 itemAssetPathForStack,
5 5 formatQuantity
6 6 } from "/shared/definitions/items.js";
7 import { marketOrderListingFee } from "/shared/market/exchange.js";
8 import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
7 9 import { applyItemIcon } from "../render/potionIcon.js";
8 10
9 11 export function initMarket ({
@@ -20,25 +22,54 @@ export function initMarket ({
20 22 const ordersEl = document.getElementById("market-orders");
21 23 const catalogEl = document.getElementById("market-catalog");
22 24 const sellList = document.getElementById("market-sell-list");
25 const sellSelected = document.getElementById("market-sell-selected");
23 26 const buyItem = document.getElementById("market-buy-item");
27 const buySearch = document.getElementById("market-buy-search");
24 28 const buyQty = document.getElementById("market-buy-qty");
25 29 const buyMax = document.getElementById("market-buy-max");
30 const buyFee = document.getElementById("market-buy-fee");
26 31 const sellQty = document.getElementById("market-sell-qty");
27 32 const sellMin = document.getElementById("market-sell-min");
33 const sellFee = document.getElementById("market-sell-fee");
28 34 const coinsEl = document.getElementById("market-coins");
29 35 const hintEl = document.getElementById("market-hint");
36 const tabs = [...document.querySelectorAll(".market-tab")];
37 const panes = [...document.querySelectorAll(".market-pane")];
30 38
31 39 let open = false;
32 40 let catalog = [];
33 41 let orders = [];
42 let searchHits = [];
34 43 let selectedSellSlot = null;
35 44 let selectedBuyItemId = null;
45 let activeTab = "orders";
46 let sellQtyLocked = false;
36 47
37 48 function suppressWorldClick ()
38 49 {
39 50 onSuppressWorldClick?.();
40 51 }
41 52
53 function setTab (tab)
54 {
55 activeTab = tab;
56 for (const button of tabs)
57 { button.classList.toggle("active", button.dataset.tab === tab); }
58 for (const pane of panes)
59 { pane.hidden = pane.dataset.pane !== tab; }
60 if (tab === "sell")
61 { renderSellables(); }
62 if (tab === "buy")
63 { updateBuyFee(); }
64 if (tab === "orders")
65 { renderOrders(); }
66 }
67
68 for (const button of tabs)
69 {
70 button.addEventListener("click", () => setTab(button.dataset.tab));
71 }
72
42 73 document.getElementById("market-close")?.addEventListener("click", () => close());
43 74 backdrop?.addEventListener("mousedown", (event) =>
44 75 {
@@ -52,6 +83,19 @@ export function initMarket ({
52 83 suppressWorldClick();
53 84 });
54 85
86 buySearch?.addEventListener("keydown", (event) =>
87 {
88 if (event.key !== "Enter")
89 { return; }
90 event.preventDefault();
91 runBuySearch(buySearch.value ?? "");
92 });
93
94 buyQty?.addEventListener("input", () => updateBuyFee());
95 buyMax?.addEventListener("input", () => updateBuyFee());
96 sellQty?.addEventListener("input", () => updateSellFee());
97 sellMin?.addEventListener("input", () => updateSellFee());
98
55 99 document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
56 100 {
57 101 if (selectedBuyItemId == null)
@@ -88,6 +132,53 @@ export function initMarket ({
88 132 socket.send({ type: MessageType.closeMarket });
89 133 }
90 134
135 function runBuySearch (query)
136 {
137 const needle = String(query ?? "").trim().toLowerCase();
138 selectedBuyItemId = null;
139 if (buyItem)
140 { buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }
141 if (!needle)
142 {
143 searchHits = [];
144 renderCatalog();
145 updateBuyFee();
146 return;
147 }
148 searchHits = catalog
149 .filter((entry) => entry.displayName.toLowerCase().includes(needle))
150 .slice(0, 10);
151 renderCatalog();
152 updateBuyFee();
153 }
154
155 function updateBuyFee ()
156 {
157 const qty = Math.max(1, buyQty?.valueAsNumber || 1);
158 const max = Math.max(1, buyMax?.valueAsNumber || 1);
159 const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty);
160 const escrow = selectedBuyItemId == null ? 0 : max * qty;
161 if (buyFee)
162 {
163 buyFee.textContent = selectedBuyItemId == null
164 ? ""
165 : `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)} (3%, non-refundable)`;
166 }
167 }
168
169 function updateSellFee ()
170 {
171 const qty = Math.max(1, sellQty?.valueAsNumber || 1);
172 const min = Math.max(1, sellMin?.valueAsNumber || 1);
173 const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty);
174 if (sellFee)
175 {
176 sellFee.textContent = selectedSellSlot == null
177 ? ""
178 : `Listing fee ${formatQuantity(fee)} (3% of min value, non-refundable)`;
179 }
180 }
181
91 182 function renderOrders ()
92 183 {
93 184 ordersEl.replaceChildren();
@@ -104,7 +195,10 @@ export function initMarket ({
104 195 const row = document.createElement("div");
105 196 row.className = "market-order-row";
106 197 const label = document.createElement("span");
107 label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`;
198 const priceLabel = order.side === "buy"
199 ? `max ${order.limitUnitPrice}`
200 : `min ${order.limitUnitPrice}`;
201 label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`;
108 202 const cancel = document.createElement("button");
109 203 cancel.type = "button";
110 204 cancel.textContent = "Cancel";
@@ -123,7 +217,17 @@ export function initMarket ({
123 217 function renderCatalog ()
124 218 {
125 219 catalogEl.replaceChildren();
126 for (const entry of catalog)
220 if (!searchHits.length)
221 {
222 const empty = document.createElement("p");
223 empty.className = "hint";
224 empty.textContent = (buySearch?.value ?? "").trim()
225 ? "No matching items."
226 : "Press Enter to search.";
227 catalogEl.append(empty);
228 return;
229 }
230 for (const entry of searchHits)
127 231 {
128 232 const row = document.createElement("button");
129 233 row.type = "button";
@@ -139,6 +243,7 @@ export function initMarket ({
139 243 if (buyMax && !(buyMax.valueAsNumber > 0))
140 244 { buyMax.value = String(entry.hintPrice); }
141 245 renderCatalog();
246 updateBuyFee();
142 247 });
143 248 catalogEl.append(row);
144 249 }
@@ -152,6 +257,9 @@ export function initMarket ({
152 257 {
153 258 if (!slot || slot.itemId == null)
154 259 { return; }
260 const listing = resolveMarketSellListing(slot);
261 if (!listing)
262 { return; }
155 263 const def = itemDefinition(slot.itemId);
156 264 if (!def || def.marketplaceSellable === false)
157 265 { return; }
@@ -164,14 +272,33 @@ export function initMarket ({
164 272 icon.alt = "";
165 273 applyItemIcon(icon, itemAssetPathForStack(slot));
166 274 const label = document.createElement("span");
167 label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
275 if (listing.isCheque)
276 {
277 label.textContent = `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}`;
278 }
279 else
280 {
281 label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
282 }
168 283 row.append(icon, label);
169 284 row.addEventListener("click", () =>
170 285 {
171 286 selectedSellSlot = slotIndex;
287 sellQtyLocked = !!listing.quantityLocked;
172 288 if (sellQty)
173 { sellQty.value = "1"; }
289 {
290 sellQty.value = String(listing.quantity);
291 sellQty.readOnly = sellQtyLocked;
292 sellQty.disabled = sellQtyLocked;
293 }
294 if (sellSelected)
295 {
296 sellSelected.textContent = listing.isCheque
297 ? `Selling cheque for ${listing.quantity}× ${listing.displayName} (quantity locked)`
298 : `Selling ${itemDisplayName(slot)}`;
299 }
174 300 renderSellables();
301 updateSellFee();
175 302 });
176 303 sellList.append(row);
177 304 });
@@ -179,9 +306,19 @@ export function initMarket ({
179 306
180 307 function refreshChrome ()
181 308 {
309 const slots = getInventorySlots?.() ?? [];
310 const funds = countMarketFunds(slots);
311 const loose = getCoinCount?.() ?? 0;
182 312 if (coinsEl)
183 { coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; }
184 renderSellables();
313 {
314 coinsEl.textContent = funds === loose
315 ? `Funds: ${formatQuantity(funds)}`
316 : `Funds: ${formatQuantity(funds)} (coins + coin cheques)`;
317 }
318 if (activeTab === "sell")
319 { renderSellables(); }
320 updateBuyFee();
321 updateSellFee();
185 322 }
186 323
187 324 return {
@@ -190,16 +327,29 @@ export function initMarket ({
190 327 open = true;
191 328 orders = payload.orders ?? [];
192 329 catalog = payload.catalog ?? [];
330 searchHits = [];
331 selectedSellSlot = null;
332 selectedBuyItemId = null;
333 sellQtyLocked = false;
334 if (sellQty)
335 {
336 sellQty.readOnly = false;
337 sellQty.disabled = false;
338 sellQty.value = "1";
339 }
340 if (buySearch)
341 { buySearch.value = ""; }
193 342 if (title)
194 343 { title.textContent = payload.displayName || "Central Exchange"; }
195 344 if (hintEl)
196 345 {
197 hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month.";
346 hintEl.textContent = "Placing an order costs a 3% listing fee (non-refundable). Matches are private; unfilled orders expire after one month.";
198 347 }
199 348 if (backdrop)
200 349 { backdrop.hidden = false; }
201 350 if (panel)
202 351 { panel.hidden = false; }
352 setTab("orders");
203 353 renderOrders();
204 354 renderCatalog();
205 355 refreshChrome();
@@ -4,6 +4,8 @@ import {
4 itemAssetPathForStack,
4 itemAssetPathForStack,
5 formatQuantity
5 formatQuantity
6} from "/shared/definitions/items.js";
6} from "/shared/definitions/items.js";
7import { marketOrderListingFee } from "/shared/market/exchange.js";
8import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
7import { applyItemIcon } from "../render/potionIcon.js";
9import { applyItemIcon } from "../render/potionIcon.js";
8
10
9export function initMarket ({
11export function initMarket ({
@@ -20,25 +22,54 @@ export function initMarket ({
20 const ordersEl = document.getElementById("market-orders");
22 const ordersEl = document.getElementById("market-orders");
21 const catalogEl = document.getElementById("market-catalog");
23 const catalogEl = document.getElementById("market-catalog");
22 const sellList = document.getElementById("market-sell-list");
24 const sellList = document.getElementById("market-sell-list");
25 const sellSelected = document.getElementById("market-sell-selected");
23 const buyItem = document.getElementById("market-buy-item");
26 const buyItem = document.getElementById("market-buy-item");
27 const buySearch = document.getElementById("market-buy-search");
24 const buyQty = document.getElementById("market-buy-qty");
28 const buyQty = document.getElementById("market-buy-qty");
25 const buyMax = document.getElementById("market-buy-max");
29 const buyMax = document.getElementById("market-buy-max");
30 const buyFee = document.getElementById("market-buy-fee");
26 const sellQty = document.getElementById("market-sell-qty");
31 const sellQty = document.getElementById("market-sell-qty");
27 const sellMin = document.getElementById("market-sell-min");
32 const sellMin = document.getElementById("market-sell-min");
33 const sellFee = document.getElementById("market-sell-fee");
28 const coinsEl = document.getElementById("market-coins");
34 const coinsEl = document.getElementById("market-coins");
29 const hintEl = document.getElementById("market-hint");
35 const hintEl = document.getElementById("market-hint");
36 const tabs = [...document.querySelectorAll(".market-tab")];
37 const panes = [...document.querySelectorAll(".market-pane")];
30
38
31 let open = false;
39 let open = false;
32 let catalog = [];
40 let catalog = [];
33 let orders = [];
41 let orders = [];
42 let searchHits = [];
34 let selectedSellSlot = null;
43 let selectedSellSlot = null;
35 let selectedBuyItemId = null;
44 let selectedBuyItemId = null;
45 let activeTab = "orders";
46 let sellQtyLocked = false;
36
47
37 function suppressWorldClick ()
48 function suppressWorldClick ()
38 {
49 {
39 onSuppressWorldClick?.();
50 onSuppressWorldClick?.();
40 }
51 }
41
52
53 function setTab (tab)
54 {
55 activeTab = tab;
56 for (const button of tabs)
57 { button.classList.toggle("active", button.dataset.tab === tab); }
58 for (const pane of panes)
59 { pane.hidden = pane.dataset.pane !== tab; }
60 if (tab === "sell")
61 { renderSellables(); }
62 if (tab === "buy")
63 { updateBuyFee(); }
64 if (tab === "orders")
65 { renderOrders(); }
66 }
67
68 for (const button of tabs)
69 {
70 button.addEventListener("click", () => setTab(button.dataset.tab));
71 }
72
42 document.getElementById("market-close")?.addEventListener("click", () => close());
73 document.getElementById("market-close")?.addEventListener("click", () => close());
43 backdrop?.addEventListener("mousedown", (event) =>
74 backdrop?.addEventListener("mousedown", (event) =>
44 {
75 {
@@ -52,6 +83,19 @@ export function initMarket ({
52 suppressWorldClick();
83 suppressWorldClick();
53 });
84 });
54
85
86 buySearch?.addEventListener("keydown", (event) =>
87 {
88 if (event.key !== "Enter")
89 { return; }
90 event.preventDefault();
91 runBuySearch(buySearch.value ?? "");
92 });
93
94 buyQty?.addEventListener("input", () => updateBuyFee());
95 buyMax?.addEventListener("input", () => updateBuyFee());
96 sellQty?.addEventListener("input", () => updateSellFee());
97 sellMin?.addEventListener("input", () => updateSellFee());
98
55 document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
99 document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
56 {
100 {
57 if (selectedBuyItemId == null)
101 if (selectedBuyItemId == null)
@@ -88,6 +132,53 @@ export function initMarket ({
88 socket.send({ type: MessageType.closeMarket });
132 socket.send({ type: MessageType.closeMarket });
89 }
133 }
90
134
135 function runBuySearch (query)
136 {
137 const needle = String(query ?? "").trim().toLowerCase();
138 selectedBuyItemId = null;
139 if (buyItem)
140 { buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }
141 if (!needle)
142 {
143 searchHits = [];
144 renderCatalog();
145 updateBuyFee();
146 return;
147 }
148 searchHits = catalog
149 .filter((entry) => entry.displayName.toLowerCase().includes(needle))
150 .slice(0, 10);
151 renderCatalog();
152 updateBuyFee();
153 }
154
155 function updateBuyFee ()
156 {
157 const qty = Math.max(1, buyQty?.valueAsNumber || 1);
158 const max = Math.max(1, buyMax?.valueAsNumber || 1);
159 const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty);
160 const escrow = selectedBuyItemId == null ? 0 : max * qty;
161 if (buyFee)
162 {
163 buyFee.textContent = selectedBuyItemId == null
164 ? ""
165 : `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)} (3%, non-refundable)`;
166 }
167 }
168
169 function updateSellFee ()
170 {
171 const qty = Math.max(1, sellQty?.valueAsNumber || 1);
172 const min = Math.max(1, sellMin?.valueAsNumber || 1);
173 const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty);
174 if (sellFee)
175 {
176 sellFee.textContent = selectedSellSlot == null
177 ? ""
178 : `Listing fee ${formatQuantity(fee)} (3% of min value, non-refundable)`;
179 }
180 }
181
91 function renderOrders ()
182 function renderOrders ()
92 {
183 {
93 ordersEl.replaceChildren();
184 ordersEl.replaceChildren();
@@ -104,7 +195,10 @@ export function initMarket ({
104 const row = document.createElement("div");
195 const row = document.createElement("div");
105 row.className = "market-order-row";
196 row.className = "market-order-row";
106 const label = document.createElement("span");
197 const label = document.createElement("span");
107 label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${order.limitUnitPrice}`;
198 const priceLabel = order.side === "buy"
199 ? `max ${order.limitUnitPrice}`
200 : `min ${order.limitUnitPrice}`;
201 label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`;
108 const cancel = document.createElement("button");
202 const cancel = document.createElement("button");
109 cancel.type = "button";
203 cancel.type = "button";
110 cancel.textContent = "Cancel";
204 cancel.textContent = "Cancel";
@@ -123,7 +217,17 @@ export function initMarket ({
123 function renderCatalog ()
217 function renderCatalog ()
124 {
218 {
125 catalogEl.replaceChildren();
219 catalogEl.replaceChildren();
126 for (const entry of catalog)
220 if (!searchHits.length)
221 {
222 const empty = document.createElement("p");
223 empty.className = "hint";
224 empty.textContent = (buySearch?.value ?? "").trim()
225 ? "No matching items."
226 : "Press Enter to search.";
227 catalogEl.append(empty);
228 return;
229 }
230 for (const entry of searchHits)
127 {
231 {
128 const row = document.createElement("button");
232 const row = document.createElement("button");
129 row.type = "button";
233 row.type = "button";
@@ -139,6 +243,7 @@ export function initMarket ({
139 if (buyMax && !(buyMax.valueAsNumber > 0))
243 if (buyMax && !(buyMax.valueAsNumber > 0))
140 { buyMax.value = String(entry.hintPrice); }
244 { buyMax.value = String(entry.hintPrice); }
141 renderCatalog();
245 renderCatalog();
246 updateBuyFee();
142 });
247 });
143 catalogEl.append(row);
248 catalogEl.append(row);
144 }
249 }
@@ -152,6 +257,9 @@ export function initMarket ({
152 {
257 {
153 if (!slot || slot.itemId == null)
258 if (!slot || slot.itemId == null)
154 { return; }
259 { return; }
260 const listing = resolveMarketSellListing(slot);
261 if (!listing)
262 { return; }
155 const def = itemDefinition(slot.itemId);
263 const def = itemDefinition(slot.itemId);
156 if (!def || def.marketplaceSellable === false)
264 if (!def || def.marketplaceSellable === false)
157 { return; }
265 { return; }
@@ -164,14 +272,33 @@ export function initMarket ({
164 icon.alt = "";
272 icon.alt = "";
165 applyItemIcon(icon, itemAssetPathForStack(slot));
273 applyItemIcon(icon, itemAssetPathForStack(slot));
166 const label = document.createElement("span");
274 const label = document.createElement("span");
167 label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
275 if (listing.isCheque)
276 {
277 label.textContent = `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}`;
278 }
279 else
280 {
281 label.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
282 }
168 row.append(icon, label);
283 row.append(icon, label);
169 row.addEventListener("click", () =>
284 row.addEventListener("click", () =>
170 {
285 {
171 selectedSellSlot = slotIndex;
286 selectedSellSlot = slotIndex;
287 sellQtyLocked = !!listing.quantityLocked;
172 if (sellQty)
288 if (sellQty)
173 { sellQty.value = "1"; }
289 {
290 sellQty.value = String(listing.quantity);
291 sellQty.readOnly = sellQtyLocked;
292 sellQty.disabled = sellQtyLocked;
293 }
294 if (sellSelected)
295 {
296 sellSelected.textContent = listing.isCheque
297 ? `Selling cheque for ${listing.quantity}× ${listing.displayName} (quantity locked)`
298 : `Selling ${itemDisplayName(slot)}`;
299 }
174 renderSellables();
300 renderSellables();
301 updateSellFee();
175 });
302 });
176 sellList.append(row);
303 sellList.append(row);
177 });
304 });
@@ -179,9 +306,19 @@ export function initMarket ({
179
306
180 function refreshChrome ()
307 function refreshChrome ()
181 {
308 {
309 const slots = getInventorySlots?.() ?? [];
310 const funds = countMarketFunds(slots);
311 const loose = getCoinCount?.() ?? 0;
182 if (coinsEl)
312 if (coinsEl)
183 { coinsEl.textContent = `Coins: ${formatQuantity(getCoinCount?.() ?? 0)}`; }
313 {
184 renderSellables();
314 coinsEl.textContent = funds === loose
315 ? `Funds: ${formatQuantity(funds)}`
316 : `Funds: ${formatQuantity(funds)} (coins + coin cheques)`;
317 }
318 if (activeTab === "sell")
319 { renderSellables(); }
320 updateBuyFee();
321 updateSellFee();
185 }
322 }
186
323
187 return {
324 return {
@@ -190,16 +327,29 @@ export function initMarket ({
190 open = true;
327 open = true;
191 orders = payload.orders ?? [];
328 orders = payload.orders ?? [];
192 catalog = payload.catalog ?? [];
329 catalog = payload.catalog ?? [];
330 searchHits = [];
331 selectedSellSlot = null;
332 selectedBuyItemId = null;
333 sellQtyLocked = false;
334 if (sellQty)
335 {
336 sellQty.readOnly = false;
337 sellQty.disabled = false;
338 sellQty.value = "1";
339 }
340 if (buySearch)
341 { buySearch.value = ""; }
193 if (title)
342 if (title)
194 { title.textContent = payload.displayName || "Central Exchange"; }
343 { title.textContent = payload.displayName || "Central Exchange"; }
195 if (hintEl)
344 if (hintEl)
196 {
345 {
197 hintEl.textContent = "Orders are matched privately. Live asks are not listed. Unfilled orders expire after one month.";
346 hintEl.textContent = "Placing an order costs a 3% listing fee (non-refundable). Matches are private; unfilled orders expire after one month.";
198 }
347 }
199 if (backdrop)
348 if (backdrop)
200 { backdrop.hidden = false; }
349 { backdrop.hidden = false; }
201 if (panel)
350 if (panel)
202 { panel.hidden = false; }
351 { panel.hidden = false; }
352 setTab("orders");
203 renderOrders();
353 renderOrders();
204 renderCatalog();
354 renderCatalog();
205 refreshChrome();
355 refreshChrome();
client/src/render/worldView.js +10 −0
@@ -295,6 +295,16 @@ export class WorldView
295 295 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
296 296 { this.despawnGroundItem(id); }
297 297 }
298 // Server only sends unsubscribeChunk (not per-entity despawns) when a chunk
299 // leaves the 3×3 interest set — drop mobs/players that still sit on that chunk.
300 for (const [id, entity] of [...this.entities.entries()])
301 {
302 if (id === this.localEntityId)
303 { continue; }
304 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
305 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
306 { this.despawnEntity(id); }
307 }
298 308 this.#rebuildAllEdges();
299 309 }
300 310
@@ -295,6 +295,16 @@ export class WorldView
295 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
295 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
296 { this.despawnGroundItem(id); }
296 { this.despawnGroundItem(id); }
297 }
297 }
298 // Server only sends unsubscribeChunk (not per-entity despawns) when a chunk
299 // leaves the 3×3 interest set — drop mobs/players that still sit on that chunk.
300 for (const [id, entity] of [...this.entities.entries()])
301 {
302 if (id === this.localEntityId)
303 { continue; }
304 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
305 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
306 { this.despawnEntity(id); }
307 }
298 this.#rebuildAllEdges();
308 this.#rebuildAllEdges();
299 }
309 }
300
310
client/ui/play.css +25 −12
@@ -1105,7 +1105,7 @@ a { color: #d4c48a; }
1105 1105 top: 50%;
1106 1106 left: 50%;
1107 1107 transform: translate(-50%, -50%);
1108 width: min(720px, 94vw);
1108 width: min(480px, 94vw);
1109 1109 max-height: min(85vh, 720px);
1110 1110 overflow: auto;
1111 1111 background: #1a1e26;
@@ -1126,14 +1126,28 @@ a { color: #d4c48a; }
1126 1126 margin-bottom: 0.5rem;
1127 1127 }
1128 1128
1129 .market-section {
1130 margin-top: 0.75rem;
1129 .market-tabs {
1130 display: flex;
1131 gap: 0.25rem;
1132 margin: 0.5rem 0 0.75rem;
1131 1133 }
1132 1134
1133 .market-columns {
1134 display: grid;
1135 grid-template-columns: 1fr 1fr;
1136 gap: 1rem;
1135 .market-tab {
1136 flex: 1;
1137 font-size: 0.85rem;
1138 padding: 0.35rem 0.4rem;
1139 background: #12151b;
1140 border: 1px solid #2c3340;
1141 color: inherit;
1142 }
1143
1144 .market-tab.active {
1145 outline: 1px solid #6a8caf;
1146 border-color: #6a8caf;
1147 }
1148
1149 .market-pane {
1150 margin-top: 0.25rem;
1137 1151 }
1138 1152
1139 1153 .market-catalog,
@@ -1141,7 +1155,7 @@ a { color: #d4c48a; }
1141 1155 display: flex;
1142 1156 flex-direction: column;
1143 1157 gap: 0.25rem;
1144 max-height: 180px;
1158 max-height: 220px;
1145 1159 overflow: auto;
1146 1160 margin-bottom: 0.5rem;
1147 1161 }
@@ -1171,10 +1185,9 @@ a { color: #d4c48a; }
1171 1185 image-rendering: pixelated;
1172 1186 }
1173 1187
1174 @media (max-width: 700px) {
1175 .market-columns {
1176 grid-template-columns: 1fr;
1177 }
1188 #market-sell-qty:disabled,
1189 #market-sell-qty[readonly] {
1190 opacity: 0.7;
1178 1191 }
1179 1192
1180 1193
@@ -1105,7 +1105,7 @@ a { color: #d4c48a; }
1105 top: 50%;
1105 top: 50%;
1106 left: 50%;
1106 left: 50%;
1107 transform: translate(-50%, -50%);
1107 transform: translate(-50%, -50%);
1108 width: min(720px, 94vw);
1108 width: min(480px, 94vw);
1109 max-height: min(85vh, 720px);
1109 max-height: min(85vh, 720px);
1110 overflow: auto;
1110 overflow: auto;
1111 background: #1a1e26;
1111 background: #1a1e26;
@@ -1126,14 +1126,28 @@ a { color: #d4c48a; }
1126 margin-bottom: 0.5rem;
1126 margin-bottom: 0.5rem;
1127}
1127}
1128
1128
1129.market-section {
1129.market-tabs {
1130 margin-top: 0.75rem;
1130 display: flex;
1131 gap: 0.25rem;
1132 margin: 0.5rem 0 0.75rem;
1131}
1133}
1132
1134
1133.market-columns {
1135.market-tab {
1134 display: grid;
1136 flex: 1;
1135 grid-template-columns: 1fr 1fr;
1137 font-size: 0.85rem;
1136 gap: 1rem;
1138 padding: 0.35rem 0.4rem;
1139 background: #12151b;
1140 border: 1px solid #2c3340;
1141 color: inherit;
1142}
1143
1144.market-tab.active {
1145 outline: 1px solid #6a8caf;
1146 border-color: #6a8caf;
1147}
1148
1149.market-pane {
1150 margin-top: 0.25rem;
1137}
1151}
1138
1152
1139.market-catalog,
1153.market-catalog,
@@ -1141,7 +1155,7 @@ a { color: #d4c48a; }
1141 display: flex;
1155 display: flex;
1142 flex-direction: column;
1156 flex-direction: column;
1143 gap: 0.25rem;
1157 gap: 0.25rem;
1144 max-height: 180px;
1158 max-height: 220px;
1145 overflow: auto;
1159 overflow: auto;
1146 margin-bottom: 0.5rem;
1160 margin-bottom: 0.5rem;
1147}
1161}
@@ -1171,10 +1185,9 @@ a { color: #d4c48a; }
1171 image-rendering: pixelated;
1185 image-rendering: pixelated;
1172}
1186}
1173
1187
1174@media (max-width: 700px) {
1188#market-sell-qty:disabled,
1175 .market-columns {
1189#market-sell-qty[readonly] {
1176 grid-template-columns: 1fr;
1190 opacity: 0.7;
1177 }
1178}
1191}
1179
1192
1180
1193
docs/FEATURES.md +5 −5
@@ -58,13 +58,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58 58 ## Baked lighting
59 59
60 60 **Status:** full
61 **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.
61 **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.
62 62 **Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
63 63
64 64 ## World editor (server)
65 65
66 66 **Status:** full
67 **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.
67 **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.
68 68 **Code:** `server/src/editor/service.js`
69 69
70 70 ## World editor (client)
@@ -229,7 +229,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
229 229
230 230 **Status:** partial
231 231 **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.
232 **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).
232 **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).
233 233 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
234 234 **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`
235 235
@@ -294,8 +294,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
294 294 ## Banking, cheques, shops, player-driven marketplace
295 295
296 296 **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
297 **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.
298 **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`
297 **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.
298 **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`
299 299
300 300 ## Player scripting hooks
301 301
@@ -58,13 +58,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58## Baked lighting
58## Baked lighting
59
59
60**Status:** full
60**Status:** full
61**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.
61**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.
62**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
62**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
63
63
64## World editor (server)
64## World editor (server)
65
65
66**Status:** full
66**Status:** full
67**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.
67**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.
68**Code:** `server/src/editor/service.js`
68**Code:** `server/src/editor/service.js`
69
69
70## World editor (client)
70## World editor (client)
@@ -229,7 +229,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
229
229
230**Status:** partial
230**Status:** partial
231**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.
231**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.
232**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).
232**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).
233**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
233**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
234**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`
234**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`
235
235
@@ -294,8 +294,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
294## Banking, cheques, shops, player-driven marketplace
294## Banking, cheques, shops, player-driven marketplace
295
295
296**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
296**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
297**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.
297**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.
298**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`
298**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`
299
299
300## Player scripting hooks
300## Player scripting hooks
301
301
server/src/assets/spriteCatalog.js +27 −1
@@ -6,7 +6,8 @@ import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6 6 import {
7 7 ORE_BEARING_MATERIALS,
8 8 oreBoulderState,
9 materialTintColor
9 materialTintColor,
10 WOOD_TIER_ORDER
10 11 } from "../../../shared/definitions/materialTiers.js";
11 12 import {
12 13 bloomImageName,
@@ -17,6 +18,7 @@ import {
17 18 spriteImageName
18 19 } from "../../../shared/definitions/tileSprites.js";
19 20 import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
21 import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";
20 22
21 23 const CHARACTER_DEFINITIONS = Object.freeze({
22 24 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -187,6 +189,30 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
187 189 }
188 190 }
189 191
192 if (layer === "block" && def.key === "table")
193 {
194 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
195 states = [];
196 for (const material of WOOD_TIER_ORDER)
197 {
198 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
199 {
200 const state = composeNeighborConnectState(def, material, mask);
201 states.push(state);
202 const tint = materialTintColor(material);
203 imagesForType.push({
204 name: spriteImageName(layer, def.key, state),
205 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
206 subImgTotal: frames,
207 perRow: framesPerRow,
208 loop: animationSpeed > 0,
209 animationSpeed,
210 tint: { r: tint.r, g: tint.g, b: tint.b }
211 });
212 }
213 }
214 }
215
190 216 types[def.key] = {
191 217 key: def.key,
192 218 typeId: def.id,
@@ -6,7 +6,8 @@ import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import {
6import {
7 ORE_BEARING_MATERIALS,
7 ORE_BEARING_MATERIALS,
8 oreBoulderState,
8 oreBoulderState,
9 materialTintColor
9 materialTintColor,
10 WOOD_TIER_ORDER
10} from "../../../shared/definitions/materialTiers.js";
11} from "../../../shared/definitions/materialTiers.js";
11import {
12import {
12 bloomImageName,
13 bloomImageName,
@@ -17,6 +18,7 @@ import {
17 spriteImageName
18 spriteImageName
18} from "../../../shared/definitions/tileSprites.js";
19} from "../../../shared/definitions/tileSprites.js";
19import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
20import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
21import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";
20
22
21const CHARACTER_DEFINITIONS = Object.freeze({
23const CHARACTER_DEFINITIONS = Object.freeze({
22 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
24 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
@@ -187,6 +189,30 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
187 }
189 }
188 }
190 }
189
191
192 if (layer === "block" && def.key === "table")
193 {
194 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
195 states = [];
196 for (const material of WOOD_TIER_ORDER)
197 {
198 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
199 {
200 const state = composeNeighborConnectState(def, material, mask);
201 states.push(state);
202 const tint = materialTintColor(material);
203 imagesForType.push({
204 name: spriteImageName(layer, def.key, state),
205 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
206 subImgTotal: frames,
207 perRow: framesPerRow,
208 loop: animationSpeed > 0,
209 animationSpeed,
210 tint: { r: tint.r, g: tint.g, b: tint.b }
211 });
212 }
213 }
214 }
215
190 types[def.key] = {
216 types[def.key] = {
191 key: def.key,
217 key: def.key,
192 typeId: def.id,
218 typeId: def.id,
server/src/lighting/baker.js +4 −4
@@ -1,7 +1,7 @@
1 1 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 2 import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
3 3 import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4 import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
4 import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";
5 5
6 6 export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
7 7
@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
34 34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
35 35 }
36 36
37 function isPassable (tileX, tileY)
37 function isClearForLight (tileX, tileY)
38 38 {
39 39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
40 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
40 return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY));
41 41 }
42 42
43 43 for (const coord of affected)
@@ -56,7 +56,7 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
56 56 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 57 if (dist > source.range)
58 58 { continue; }
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight))
60 60 {
61 61 best = Math.max(best, encodeLight(dist, source.range));
62 62 }
@@ -1,7 +1,7 @@
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
2import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";
5
5
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
7
7
@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
35 }
35 }
36
36
37 function isPassable (tileX, tileY)
37 function isClearForLight (tileX, tileY)
38 {
38 {
39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
40 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
40 return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY));
41 }
41 }
42
42
43 for (const coord of affected)
43 for (const coord of affected)
@@ -56,7 +56,7 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
56 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
56 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 if (dist > source.range)
57 if (dist > source.range)
58 { continue; }
58 { continue; }
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight))
60 {
60 {
61 best = Math.max(best, encodeLight(dist, source.range));
61 best = Math.max(best, encodeLight(dist, source.range));
62 }
62 }
server/src/market/service.js +158 −25
@@ -7,7 +7,6 @@ import {
7 7 insertStack,
8 8 insertStackGrowable,
9 9 normalizeVault,
10 takeCoinsFromSlots,
11 10 takeFromSlot,
12 11 cloneStack
13 12 } from "../../../shared/items/inventory.js";
@@ -17,12 +16,14 @@ import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
17 16 import {
18 17 MARKET_ORDER_MAX_AGE_MS,
19 18 buyFilledLetterBody,
19 marketOrderListingFee,
20 20 midpointTradePrice,
21 21 orderExpiredLetterBody,
22 22 orderCancelledLetterBody,
23 23 pickExchangeClerk,
24 24 soldLetterBody
25 25 } from "../../../shared/market/exchange.js";
26 import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";
26 27 import { decodeChunkBlob } from "../world/chunkData.js";
27 28 import { withTransaction } from "../persistence/database.js";
28 29
@@ -165,6 +166,7 @@ export class MarketService
165 166 openMarket (sessionId, characterId, now = Date.now())
166 167 {
167 168 const { position } = this.#requireAtMarket(characterId);
169 this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
168 170 return {
169 171 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
170 172 };
@@ -174,7 +176,6 @@ export class MarketService
174 176 {
175 177 const { position } = this.#requireAtMarket(characterId);
176 178 const minPrice = Math.max(1, minUnitPrice | 0);
177 const qty = Math.max(1, quantity | 0 || 1);
178 179 const bag = this.#loadBag(characterId);
179 180 const slot = bag.inventory?.[slotIndex];
180 181 if (!slot)
@@ -182,19 +183,58 @@ export class MarketService
182 183 assertMarketplaceSellable(slot);
183 184 if ((slot.itemId | 0) === ItemId.coins)
184 185 { throw userError("Coins cannot be listed on the marketplace."); }
185 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
186 if (!taken.ok || !taken.taken)
187 { throw userError("That item is not available."); }
188 bag.inventory = taken.slots;
189 const stack = attachOrigins(taken.taken);
186
187 const listing = resolveMarketSellListing(slot);
188 if (!listing)
189 { throw userError("That item cannot be sold on the marketplace."); }
190
191 let escrowStack;
192 let orderQty;
193 if (listing.isCheque)
194 {
195 orderQty = listing.quantity;
196 const taken = takeFromSlot(bag.inventory, slotIndex, 1);
197 if (!taken.ok || !taken.taken)
198 { throw userError("That cheque is not available."); }
199 bag.inventory = taken.slots;
200 escrowStack = attachOrigins(taken.taken);
201 }
202 else
203 {
204 const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
205 orderQty = qty;
206 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
207 if (!taken.ok || !taken.taken)
208 { throw userError("That item is not available."); }
209 bag.inventory = taken.slots;
210 escrowStack = attachOrigins(taken.taken);
211 }
212
213 const fee = marketOrderListingFee(minPrice, orderQty);
214 const paid = this.#payMarketFunds(bag, characterId, fee);
215 if (!paid.ok)
216 {
217 const restored = insertStack(
218 bag.inventory,
219 escrowStack,
220 itemDefinition(escrowStack.itemId)
221 );
222 bag.inventory = restored.slots;
223 throw userError(
224 fee > 0
225 ? `You need ${fee} coins for the listing fee.`
226 : "You cannot afford the listing fee."
227 );
228 }
229
190 230 const order = this.stateDb.insertMarketOrder({
191 231 characterId,
192 232 side: "sell",
193 itemId: stack.itemId,
194 quantity: stack.quantity,
233 itemId: listing.itemId,
234 quantity: orderQty,
195 235 limitUnitPrice: minPrice,
196 236 escrowCoins: 0,
197 escrowStack: stack,
237 escrowStack,
198 238 createdAt: now,
199 239 status: "open"
200 240 });
@@ -219,11 +259,15 @@ export class MarketService
219 259 if ((itemId | 0) === ItemId.coins)
220 260 { throw userError("Coins cannot be ordered on the marketplace."); }
221 261 const escrow = maxPrice * qty;
262 const fee = marketOrderListingFee(maxPrice, qty);
222 263 const bag = this.#loadBag(characterId);
223 const paid = takeCoinsFromSlots(bag.inventory, escrow);
264 const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
224 265 if (!paid.ok)
225 { throw userError("You cannot afford that buy order."); }
226 bag.inventory = paid.slots;
266 {
267 throw userError(
268 `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
269 );
270 }
227 271 const order = this.stateDb.insertMarketOrder({
228 272 characterId,
229 273 side: "buy",
@@ -258,7 +302,11 @@ export class MarketService
258 302 side: order.side,
259 303 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
260 304 quantity: order.quantity,
261 escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
305 escrowLabel: order.side === "buy"
306 ? "coins"
307 : (isFilledChequeEscrow(order.escrowStack)
308 ? "written cheque"
309 : (itemDefinition(order.itemId)?.displayName ?? "item")),
262 310 clerkName: pickExchangeClerk()
263 311 }),
264 312 now
@@ -283,7 +331,11 @@ export class MarketService
283 331 side: order.side,
284 332 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
285 333 quantity: order.quantity,
286 escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
334 escrowLabel: order.side === "buy"
335 ? "coins"
336 : (isFilledChequeEscrow(order.escrowStack)
337 ? "written cheque"
338 : (itemDefinition(order.itemId)?.displayName ?? "item")),
287 339 clerkName: pickExchangeClerk()
288 340 }),
289 341 now
@@ -330,7 +382,14 @@ export class MarketService
330 382 if (buy.limitUnitPrice < sell.limitUnitPrice)
331 383 { continue; }
332 384
333 const fillQty = Math.min(buy.quantity, sell.quantity);
385 let fillQty = Math.min(buy.quantity, sell.quantity);
386 if (isFilledChequeEscrow(sell.escrowStack))
387 {
388 // Written cheques list as one indivisible lot.
389 if (fillQty < sell.quantity)
390 { continue; }
391 fillQty = sell.quantity;
392 }
334 393 if (fillQty <= 0)
335 394 { continue; }
336 395 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
@@ -353,18 +412,31 @@ export class MarketService
353 412 const total = unitPrice * fillQty;
354 413 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
355 414 const clerk = pickExchangeClerk();
415 const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
356 416
357 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
358 const goods = attachOrigins({
359 itemId: sell.itemId,
360 quantity: fillQty,
361 origins: sellSplit.taken,
362 instance: sell.escrowStack?.instance ?? null
363 });
417 let goods;
418 let sellRemainOrigins = null;
419 if (chequeEscrow)
420 {
421 goods = this.#redeemSellChequeEscrow(sell.escrowStack);
422 if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
423 { throw userError("That cheque listing could not be settled."); }
424 }
425 else
426 {
427 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
428 goods = attachOrigins({
429 itemId: sell.itemId,
430 quantity: fillQty,
431 origins: sellSplit.taken,
432 instance: sell.escrowStack?.instance ?? null
433 });
434 sellRemainOrigins = sellSplit.remain;
435 }
364 436
365 437 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
366 438 const buyRemainingQty = buy.quantity - fillQty;
367 const sellRemainingQty = sell.quantity - fillQty;
439 const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
368 440
369 441 withTransaction(this.stateDb.db, () =>
370 442 {
@@ -392,7 +464,7 @@ export class MarketService
392 464 ? attachOrigins({
393 465 ...sell.escrowStack,
394 466 quantity: sellRemainingQty,
395 origins: sellSplit.remain
467 origins: sellRemainOrigins
396 468 })
397 469 : null,
398 470 status: sellRemainingQty > 0 ? "open" : "filled"
@@ -442,6 +514,67 @@ export class MarketService
442 514 return events;
443 515 }
444 516
517 /** Redeem a written-cheque sell escrow into the reserved goods stack. */
518 #redeemSellChequeEscrow (chequeStack)
519 {
520 const instance = chequeStack?.instance;
521 if (!instance || instance.kind !== "filled-cheque")
522 { throw userError("That cheque listing is invalid."); }
523 const issuerId = instance.issuerCharacterId | 0;
524 const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
525 if (!release?.ok || !release.stack)
526 { throw userError(release?.error ?? "That cheque cannot be redeemed."); }
527 return attachOrigins(release.stack);
528 }
529
530 /**
531 * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
532 * Releases reservations for redeemed coin cheques.
533 */
534 #payMarketFunds (bag, payerCharacterId, amount)
535 {
536 const need = Math.max(0, amount | 0);
537 if (!need)
538 { return { ok: true }; }
539 const paid = takeMarketFunds(bag.inventory, need);
540 if (!paid.ok)
541 { return { ok: false }; }
542 bag.inventory = paid.slots;
543 for (const cheque of paid.redeemedCheques ?? [])
544 {
545 const instance = cheque.instance;
546 const issuerId = instance?.issuerCharacterId | 0;
547 const release = this.simulation.releaseChequeReservation?.(
548 issuerId,
549 instance.chequeId,
550 instance
551 );
552 if (!release?.ok)
553 {
554 // Restore cheque paper; leave other payments as-is (best-effort).
555 const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
556 bag.inventory = restored.slots;
557 return { ok: false };
558 }
559 }
560 if ((paid.change | 0) > 0)
561 {
562 const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
563 if (!refunded.ok)
564 {
565 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
566 const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
567 bag.inventory = refunded.slots;
568 bag.vault = vaultPaid.slots;
569 bag.vaultReserved = vault.reserved;
570 }
571 else
572 { bag.inventory = refunded.slots; }
573 }
574 void payerCharacterId;
575 return { ok: true };
576 }
577
445 578 #returnEscrowByPigeon (order, { letterBody, now })
446 579 {
447 580 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
@@ -7,7 +7,6 @@ import {
7 insertStack,
7 insertStack,
8 insertStackGrowable,
8 insertStackGrowable,
9 normalizeVault,
9 normalizeVault,
10 takeCoinsFromSlots,
11 takeFromSlot,
10 takeFromSlot,
12 cloneStack
11 cloneStack
13} from "../../../shared/items/inventory.js";
12} from "../../../shared/items/inventory.js";
@@ -17,12 +16,14 @@ import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
17import {
16import {
18 MARKET_ORDER_MAX_AGE_MS,
17 MARKET_ORDER_MAX_AGE_MS,
19 buyFilledLetterBody,
18 buyFilledLetterBody,
19 marketOrderListingFee,
20 midpointTradePrice,
20 midpointTradePrice,
21 orderExpiredLetterBody,
21 orderExpiredLetterBody,
22 orderCancelledLetterBody,
22 orderCancelledLetterBody,
23 pickExchangeClerk,
23 pickExchangeClerk,
24 soldLetterBody
24 soldLetterBody
25} from "../../../shared/market/exchange.js";
25} from "../../../shared/market/exchange.js";
26import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";
26import { decodeChunkBlob } from "../world/chunkData.js";
27import { decodeChunkBlob } from "../world/chunkData.js";
27import { withTransaction } from "../persistence/database.js";
28import { withTransaction } from "../persistence/database.js";
28
29
@@ -165,6 +166,7 @@ export class MarketService
165 openMarket (sessionId, characterId, now = Date.now())
166 openMarket (sessionId, characterId, now = Date.now())
166 {
167 {
167 const { position } = this.#requireAtMarket(characterId);
168 const { position } = this.#requireAtMarket(characterId);
169 this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
168 return {
170 return {
169 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
171 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
170 };
172 };
@@ -174,7 +176,6 @@ export class MarketService
174 {
176 {
175 const { position } = this.#requireAtMarket(characterId);
177 const { position } = this.#requireAtMarket(characterId);
176 const minPrice = Math.max(1, minUnitPrice | 0);
178 const minPrice = Math.max(1, minUnitPrice | 0);
177 const qty = Math.max(1, quantity | 0 || 1);
178 const bag = this.#loadBag(characterId);
179 const bag = this.#loadBag(characterId);
179 const slot = bag.inventory?.[slotIndex];
180 const slot = bag.inventory?.[slotIndex];
180 if (!slot)
181 if (!slot)
@@ -182,19 +183,58 @@ export class MarketService
182 assertMarketplaceSellable(slot);
183 assertMarketplaceSellable(slot);
183 if ((slot.itemId | 0) === ItemId.coins)
184 if ((slot.itemId | 0) === ItemId.coins)
184 { throw userError("Coins cannot be listed on the marketplace."); }
185 { throw userError("Coins cannot be listed on the marketplace."); }
185 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
186
186 if (!taken.ok || !taken.taken)
187 const listing = resolveMarketSellListing(slot);
187 { throw userError("That item is not available."); }
188 if (!listing)
188 bag.inventory = taken.slots;
189 { throw userError("That item cannot be sold on the marketplace."); }
189 const stack = attachOrigins(taken.taken);
190
191 let escrowStack;
192 let orderQty;
193 if (listing.isCheque)
194 {
195 orderQty = listing.quantity;
196 const taken = takeFromSlot(bag.inventory, slotIndex, 1);
197 if (!taken.ok || !taken.taken)
198 { throw userError("That cheque is not available."); }
199 bag.inventory = taken.slots;
200 escrowStack = attachOrigins(taken.taken);
201 }
202 else
203 {
204 const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
205 orderQty = qty;
206 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
207 if (!taken.ok || !taken.taken)
208 { throw userError("That item is not available."); }
209 bag.inventory = taken.slots;
210 escrowStack = attachOrigins(taken.taken);
211 }
212
213 const fee = marketOrderListingFee(minPrice, orderQty);
214 const paid = this.#payMarketFunds(bag, characterId, fee);
215 if (!paid.ok)
216 {
217 const restored = insertStack(
218 bag.inventory,
219 escrowStack,
220 itemDefinition(escrowStack.itemId)
221 );
222 bag.inventory = restored.slots;
223 throw userError(
224 fee > 0
225 ? `You need ${fee} coins for the listing fee.`
226 : "You cannot afford the listing fee."
227 );
228 }
229
190 const order = this.stateDb.insertMarketOrder({
230 const order = this.stateDb.insertMarketOrder({
191 characterId,
231 characterId,
192 side: "sell",
232 side: "sell",
193 itemId: stack.itemId,
233 itemId: listing.itemId,
194 quantity: stack.quantity,
234 quantity: orderQty,
195 limitUnitPrice: minPrice,
235 limitUnitPrice: minPrice,
196 escrowCoins: 0,
236 escrowCoins: 0,
197 escrowStack: stack,
237 escrowStack,
198 createdAt: now,
238 createdAt: now,
199 status: "open"
239 status: "open"
200 });
240 });
@@ -219,11 +259,15 @@ export class MarketService
219 if ((itemId | 0) === ItemId.coins)
259 if ((itemId | 0) === ItemId.coins)
220 { throw userError("Coins cannot be ordered on the marketplace."); }
260 { throw userError("Coins cannot be ordered on the marketplace."); }
221 const escrow = maxPrice * qty;
261 const escrow = maxPrice * qty;
262 const fee = marketOrderListingFee(maxPrice, qty);
222 const bag = this.#loadBag(characterId);
263 const bag = this.#loadBag(characterId);
223 const paid = takeCoinsFromSlots(bag.inventory, escrow);
264 const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
224 if (!paid.ok)
265 if (!paid.ok)
225 { throw userError("You cannot afford that buy order."); }
266 {
226 bag.inventory = paid.slots;
267 throw userError(
268 `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
269 );
270 }
227 const order = this.stateDb.insertMarketOrder({
271 const order = this.stateDb.insertMarketOrder({
228 characterId,
272 characterId,
229 side: "buy",
273 side: "buy",
@@ -258,7 +302,11 @@ export class MarketService
258 side: order.side,
302 side: order.side,
259 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
303 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
260 quantity: order.quantity,
304 quantity: order.quantity,
261 escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
305 escrowLabel: order.side === "buy"
306 ? "coins"
307 : (isFilledChequeEscrow(order.escrowStack)
308 ? "written cheque"
309 : (itemDefinition(order.itemId)?.displayName ?? "item")),
262 clerkName: pickExchangeClerk()
310 clerkName: pickExchangeClerk()
263 }),
311 }),
264 now
312 now
@@ -283,7 +331,11 @@ export class MarketService
283 side: order.side,
331 side: order.side,
284 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
332 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
285 quantity: order.quantity,
333 quantity: order.quantity,
286 escrowLabel: order.side === "buy" ? "coins" : (itemDefinition(order.itemId)?.displayName ?? "item"),
334 escrowLabel: order.side === "buy"
335 ? "coins"
336 : (isFilledChequeEscrow(order.escrowStack)
337 ? "written cheque"
338 : (itemDefinition(order.itemId)?.displayName ?? "item")),
287 clerkName: pickExchangeClerk()
339 clerkName: pickExchangeClerk()
288 }),
340 }),
289 now
341 now
@@ -330,7 +382,14 @@ export class MarketService
330 if (buy.limitUnitPrice < sell.limitUnitPrice)
382 if (buy.limitUnitPrice < sell.limitUnitPrice)
331 { continue; }
383 { continue; }
332
384
333 const fillQty = Math.min(buy.quantity, sell.quantity);
385 let fillQty = Math.min(buy.quantity, sell.quantity);
386 if (isFilledChequeEscrow(sell.escrowStack))
387 {
388 // Written cheques list as one indivisible lot.
389 if (fillQty < sell.quantity)
390 { continue; }
391 fillQty = sell.quantity;
392 }
334 if (fillQty <= 0)
393 if (fillQty <= 0)
335 { continue; }
394 { continue; }
336 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
395 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
@@ -353,18 +412,31 @@ export class MarketService
353 const total = unitPrice * fillQty;
412 const total = unitPrice * fillQty;
354 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
413 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
355 const clerk = pickExchangeClerk();
414 const clerk = pickExchangeClerk();
415 const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
356
416
357 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
417 let goods;
358 const goods = attachOrigins({
418 let sellRemainOrigins = null;
359 itemId: sell.itemId,
419 if (chequeEscrow)
360 quantity: fillQty,
420 {
361 origins: sellSplit.taken,
421 goods = this.#redeemSellChequeEscrow(sell.escrowStack);
362 instance: sell.escrowStack?.instance ?? null
422 if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
363 });
423 { throw userError("That cheque listing could not be settled."); }
424 }
425 else
426 {
427 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
428 goods = attachOrigins({
429 itemId: sell.itemId,
430 quantity: fillQty,
431 origins: sellSplit.taken,
432 instance: sell.escrowStack?.instance ?? null
433 });
434 sellRemainOrigins = sellSplit.remain;
435 }
364
436
365 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
437 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
366 const buyRemainingQty = buy.quantity - fillQty;
438 const buyRemainingQty = buy.quantity - fillQty;
367 const sellRemainingQty = sell.quantity - fillQty;
439 const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
368
440
369 withTransaction(this.stateDb.db, () =>
441 withTransaction(this.stateDb.db, () =>
370 {
442 {
@@ -392,7 +464,7 @@ export class MarketService
392 ? attachOrigins({
464 ? attachOrigins({
393 ...sell.escrowStack,
465 ...sell.escrowStack,
394 quantity: sellRemainingQty,
466 quantity: sellRemainingQty,
395 origins: sellSplit.remain
467 origins: sellRemainOrigins
396 })
468 })
397 : null,
469 : null,
398 status: sellRemainingQty > 0 ? "open" : "filled"
470 status: sellRemainingQty > 0 ? "open" : "filled"
@@ -442,6 +514,67 @@ export class MarketService
442 return events;
514 return events;
443 }
515 }
444
516
517 /** Redeem a written-cheque sell escrow into the reserved goods stack. */
518 #redeemSellChequeEscrow (chequeStack)
519 {
520 const instance = chequeStack?.instance;
521 if (!instance || instance.kind !== "filled-cheque")
522 { throw userError("That cheque listing is invalid."); }
523 const issuerId = instance.issuerCharacterId | 0;
524 const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
525 if (!release?.ok || !release.stack)
526 { throw userError(release?.error ?? "That cheque cannot be redeemed."); }
527 return attachOrigins(release.stack);
528 }
529
530 /**
531 * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
532 * Releases reservations for redeemed coin cheques.
533 */
534 #payMarketFunds (bag, payerCharacterId, amount)
535 {
536 const need = Math.max(0, amount | 0);
537 if (!need)
538 { return { ok: true }; }
539 const paid = takeMarketFunds(bag.inventory, need);
540 if (!paid.ok)
541 { return { ok: false }; }
542 bag.inventory = paid.slots;
543 for (const cheque of paid.redeemedCheques ?? [])
544 {
545 const instance = cheque.instance;
546 const issuerId = instance?.issuerCharacterId | 0;
547 const release = this.simulation.releaseChequeReservation?.(
548 issuerId,
549 instance.chequeId,
550 instance
551 );
552 if (!release?.ok)
553 {
554 // Restore cheque paper; leave other payments as-is (best-effort).
555 const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
556 bag.inventory = restored.slots;
557 return { ok: false };
558 }
559 }
560 if ((paid.change | 0) > 0)
561 {
562 const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
563 if (!refunded.ok)
564 {
565 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
566 const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
567 bag.inventory = refunded.slots;
568 bag.vault = vaultPaid.slots;
569 bag.vaultReserved = vault.reserved;
570 }
571 else
572 { bag.inventory = refunded.slots; }
573 }
574 void payerCharacterId;
575 return { ok: true };
576 }
577
445 #returnEscrowByPigeon (order, { letterBody, now })
578 #returnEscrowByPigeon (order, { letterBody, now })
446 {
579 {
447 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
580 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
server/src/simulation/protocol.js +2 −1
@@ -34,5 +34,6 @@ export const WorkerMessage = Object.freeze({
34 34 spawnCorpseDrops: "spawnCorpseDrops",
35 35 applyRespawn: "applyRespawn",
36 36 clearCombat: "clearCombat",
37 setItemLastSales: "setItemLastSales"
37 setItemLastSales: "setItemLastSales",
38 stationExchangeClerk: "stationExchangeClerk"
38 39 });
@@ -34,5 +34,6 @@ export const WorkerMessage = Object.freeze({
34 spawnCorpseDrops: "spawnCorpseDrops",
34 spawnCorpseDrops: "spawnCorpseDrops",
35 applyRespawn: "applyRespawn",
35 applyRespawn: "applyRespawn",
36 clearCombat: "clearCombat",
36 clearCombat: "clearCombat",
37 setItemLastSales: "setItemLastSales"
37 setItemLastSales: "setItemLastSales",
38 stationExchangeClerk: "stationExchangeClerk"
38});
39});
server/src/simulation/simulation.js +30 −0
@@ -554,6 +554,36 @@ export class Simulation
554 554 });
555 555 }
556 556
557 /**
558 * When a player uses a marketplace counter, path an idle CE clerk to the
559 * opposite side of that counter (staff side).
560 */
561 stationExchangeClerks (playerTileX, playerTileY)
562 {
563 const results = [];
564 for (const tile of this.market?.marketTiles ?? [])
565 {
566 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
567 { continue; }
568 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
569 { continue; }
570 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
571 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
572 if (stationTileX === playerTileX && stationTileY === playerTileY)
573 { continue; }
574 const owner = this.#ownerOfTile(stationTileX, stationTileY);
575 if (owner == null)
576 { continue; }
577 const result = this.workers[owner].call({
578 type: WorkerMessage.stationExchangeClerk,
579 stationTileX,
580 stationTileY
581 });
582 results.push(result);
583 }
584 return results;
585 }
586
557 587 despawnCharacter (characterId)
558 588 {
559 589 const entityId = this.characterEntities.get(characterId);
@@ -554,6 +554,36 @@ export class Simulation
554 });
554 });
555 }
555 }
556
556
557 /**
558 * When a player uses a marketplace counter, path an idle CE clerk to the
559 * opposite side of that counter (staff side).
560 */
561 stationExchangeClerks (playerTileX, playerTileY)
562 {
563 const results = [];
564 for (const tile of this.market?.marketTiles ?? [])
565 {
566 if (Math.max(Math.abs(tile.tileX - playerTileX), Math.abs(tile.tileY - playerTileY)) > 1)
567 { continue; }
568 if (tile.tileX === playerTileX && tile.tileY === playerTileY)
569 { continue; }
570 const stationTileX = tile.tileX + (tile.tileX - playerTileX);
571 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
572 if (stationTileX === playerTileX && stationTileY === playerTileY)
573 { continue; }
574 const owner = this.#ownerOfTile(stationTileX, stationTileY);
575 if (owner == null)
576 { continue; }
577 const result = this.workers[owner].call({
578 type: WorkerMessage.stationExchangeClerk,
579 stationTileX,
580 stationTileY
581 });
582 results.push(result);
583 }
584 return results;
585 }
586
557 despawnCharacter (characterId)
587 despawnCharacter (characterId)
558 {
588 {
559 const entityId = this.characterEntities.get(characterId);
589 const entityId = this.characterEntities.get(characterId);
server/src/simulation/spawners.js +67 −4
@@ -4,8 +4,10 @@ import {
4 4 normalizeSpawnerConfig,
5 5 listAmbientMobTypes,
6 6 mobDefinition,
7 mobSpriteName
7 mobSpriteName,
8 MobId
8 9 } from "../../../shared/definitions/mobs.js";
10 import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
9 11 import { emptyEquipment } from "../../../shared/items/inventory.js";
10 12 import { itemDefinition } from "../../../shared/definitions/items.js";
11 13 import { Component } from "../ecs/components.js";
@@ -15,6 +17,7 @@ export function collectSpawnRequests (world)
15 17 {
16 18 const requests = [];
17 19 const counts = countBySpawner(world);
20 const staffAlive = staffNamesBySpawner(world);
18 21 const reserved = new Set();
19 22 for (const [key, chunk] of world.chunks)
20 23 {
@@ -34,6 +37,43 @@ export function collectSpawnRequests (world)
34 37 const originX = chunkX * CHUNK_SIZE + localX;
35 38 const originY = chunkY * CHUNK_SIZE + localY;
36 39 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
40
41 if (config.centralExchange)
42 {
43 const alive = staffAlive.get(config.spawnerId) ?? new Set();
44 for (const staff of CENTRAL_EXCHANGE_STAFF)
45 {
46 if (alive.has(staff.name))
47 { continue; }
48 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
49 { break; }
50 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
51 if (!tile)
52 { break; }
53 reserved.add(`${tile.tileX},${tile.tileY}`);
54 alive.add(staff.name);
55 staffAlive.set(config.spawnerId, alive);
56 requests.push({
57 ...tile,
58 mobTypeId: MobId.centralExchange,
59 spawnerId: config.spawnerId,
60 originTileX: originX,
61 originTileY: originY,
62 wanderRangeTiles: config.maxWanderRangeTiles,
63 persistent,
64 sex: staff.sex,
65 displayName: staff.name,
66 equipment: config.equipment,
67 sells: [],
68 buysItems: false,
69 hiddenDiscount: config.hiddenDiscount,
70 centralExchange: true
71 });
72 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
73 }
74 continue;
75 }
76
37 77 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
38 78 {
39 79 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
@@ -53,7 +93,8 @@ export function collectSpawnRequests (world)
53 93 equipment: config.equipment,
54 94 sells: config.sells,
55 95 buysItems: config.buysItems,
56 hiddenDiscount: config.hiddenDiscount
96 hiddenDiscount: config.hiddenDiscount,
97 centralExchange: false
57 98 });
58 99 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
59 100 }
@@ -96,7 +137,10 @@ export function mobComponents (request)
96 137 spawnerId: request.spawnerId,
97 138 originTileX: request.originTileX ?? request.tileX,
98 139 originTileY: request.originTileY ?? request.tileY,
99 wanderRangeTiles: request.wanderRangeTiles ?? 4
140 wanderRangeTiles: request.wanderRangeTiles ?? 4,
141 centralExchange: !!request.centralExchange,
142 stationTileX: null,
143 stationTileY: null
100 144 };
101 145 }
102 146 if (def.persistent)
@@ -148,7 +192,8 @@ export function mobComponents (request)
148 192 }).filter((line) => line.itemId > 0)
149 193 : [];
150 194 const buysItems = !!request.buysItems;
151 if (catalog.length || buysItems || def.talkable)
195 const isExchange = !!request.centralExchange || def.centralExchange;
196 if (!isExchange && (catalog.length || buysItems || def.talkable))
152 197 {
153 198 components.shop = {
154 199 catalog,
@@ -219,6 +264,24 @@ function countBySpawner (world)
219 264 return counts;
220 265 }
221 266
267 function staffNamesBySpawner (world)
268 {
269 const map = new Map();
270 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
271 {
272 if (!entity.spawnOrigin?.centralExchange)
273 { continue; }
274 const id = entity.spawnOrigin.spawnerId;
275 const name = entity.appearance?.firstName;
276 if (!id || !name)
277 { continue; }
278 const set = map.get(id) ?? new Set();
279 set.add(name);
280 map.set(id, set);
281 }
282 return map;
283 }
284
222 285 function countCreatures (world, mobTypeId)
223 286 {
224 287 let count = 0;
@@ -4,8 +4,10 @@ import {
4 normalizeSpawnerConfig,
4 normalizeSpawnerConfig,
5 listAmbientMobTypes,
5 listAmbientMobTypes,
6 mobDefinition,
6 mobDefinition,
7 mobSpriteName
7 mobSpriteName,
8 MobId
8} from "../../../shared/definitions/mobs.js";
9} from "../../../shared/definitions/mobs.js";
10import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
9import { emptyEquipment } from "../../../shared/items/inventory.js";
11import { emptyEquipment } from "../../../shared/items/inventory.js";
10import { itemDefinition } from "../../../shared/definitions/items.js";
12import { itemDefinition } from "../../../shared/definitions/items.js";
11import { Component } from "../ecs/components.js";
13import { Component } from "../ecs/components.js";
@@ -15,6 +17,7 @@ export function collectSpawnRequests (world)
15{
17{
16 const requests = [];
18 const requests = [];
17 const counts = countBySpawner(world);
19 const counts = countBySpawner(world);
20 const staffAlive = staffNamesBySpawner(world);
18 const reserved = new Set();
21 const reserved = new Set();
19 for (const [key, chunk] of world.chunks)
22 for (const [key, chunk] of world.chunks)
20 {
23 {
@@ -34,6 +37,43 @@ export function collectSpawnRequests (world)
34 const originX = chunkX * CHUNK_SIZE + localX;
37 const originX = chunkX * CHUNK_SIZE + localX;
35 const originY = chunkY * CHUNK_SIZE + localY;
38 const originY = chunkY * CHUNK_SIZE + localY;
36 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
39 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
40
41 if (config.centralExchange)
42 {
43 const alive = staffAlive.get(config.spawnerId) ?? new Set();
44 for (const staff of CENTRAL_EXCHANGE_STAFF)
45 {
46 if (alive.has(staff.name))
47 { continue; }
48 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
49 { break; }
50 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
51 if (!tile)
52 { break; }
53 reserved.add(`${tile.tileX},${tile.tileY}`);
54 alive.add(staff.name);
55 staffAlive.set(config.spawnerId, alive);
56 requests.push({
57 ...tile,
58 mobTypeId: MobId.centralExchange,
59 spawnerId: config.spawnerId,
60 originTileX: originX,
61 originTileY: originY,
62 wanderRangeTiles: config.maxWanderRangeTiles,
63 persistent,
64 sex: staff.sex,
65 displayName: staff.name,
66 equipment: config.equipment,
67 sells: [],
68 buysItems: false,
69 hiddenDiscount: config.hiddenDiscount,
70 centralExchange: true
71 });
72 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
73 }
74 continue;
75 }
76
37 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
77 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
38 {
78 {
39 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
79 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
@@ -53,7 +93,8 @@ export function collectSpawnRequests (world)
53 equipment: config.equipment,
93 equipment: config.equipment,
54 sells: config.sells,
94 sells: config.sells,
55 buysItems: config.buysItems,
95 buysItems: config.buysItems,
56 hiddenDiscount: config.hiddenDiscount
96 hiddenDiscount: config.hiddenDiscount,
97 centralExchange: false
57 });
98 });
58 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
99 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
59 }
100 }
@@ -96,7 +137,10 @@ export function mobComponents (request)
96 spawnerId: request.spawnerId,
137 spawnerId: request.spawnerId,
97 originTileX: request.originTileX ?? request.tileX,
138 originTileX: request.originTileX ?? request.tileX,
98 originTileY: request.originTileY ?? request.tileY,
139 originTileY: request.originTileY ?? request.tileY,
99 wanderRangeTiles: request.wanderRangeTiles ?? 4
140 wanderRangeTiles: request.wanderRangeTiles ?? 4,
141 centralExchange: !!request.centralExchange,
142 stationTileX: null,
143 stationTileY: null
100 };
144 };
101 }
145 }
102 if (def.persistent)
146 if (def.persistent)
@@ -148,7 +192,8 @@ export function mobComponents (request)
148 }).filter((line) => line.itemId > 0)
192 }).filter((line) => line.itemId > 0)
149 : [];
193 : [];
150 const buysItems = !!request.buysItems;
194 const buysItems = !!request.buysItems;
151 if (catalog.length || buysItems || def.talkable)
195 const isExchange = !!request.centralExchange || def.centralExchange;
196 if (!isExchange && (catalog.length || buysItems || def.talkable))
152 {
197 {
153 components.shop = {
198 components.shop = {
154 catalog,
199 catalog,
@@ -219,6 +264,24 @@ function countBySpawner (world)
219 return counts;
264 return counts;
220}
265}
221
266
267function staffNamesBySpawner (world)
268{
269 const map = new Map();
270 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
271 {
272 if (!entity.spawnOrigin?.centralExchange)
273 { continue; }
274 const id = entity.spawnOrigin.spawnerId;
275 const name = entity.appearance?.firstName;
276 if (!id || !name)
277 { continue; }
278 const set = map.get(id) ?? new Set();
279 set.add(name);
280 map.set(id, set);
281 }
282 return map;
283}
284
222function countCreatures (world, mobTypeId)
285function countCreatures (world, mobTypeId)
223{
286{
224 let count = 0;
287 let count = 0;
server/src/simulation/workerWorld.js +108 −1
@@ -171,6 +171,8 @@ export class WorkerWorld
171 171 { this.itemLastSales.set(Number(key), sale); }
172 172 return { ok: true };
173 173 }
174 case WorkerMessage.stationExchangeClerk:
175 return this.#stationExchangeClerk(message);
174 176 default:
175 177 throw new Error(`Unknown worker message ${message.type}`);
176 178 }
@@ -981,6 +983,7 @@ export class WorkerWorld
981 983 events.push(...pruneShopBrowsers(this));
982 984 this.#queueAmbientWander();
983 985 this.#queueSpawnerWander();
986 this.#queueExchangeStations();
984 987 for (const entity of this.ecs.query(Component.position, Component.movement))
985 988 {
986 989 const { handle, entityId, position, movement } = entity;
@@ -1169,6 +1172,9 @@ export class WorkerWorld
1169 1172 const shop = this.ecs.get(entity.handle, Component.shop);
1170 1173 if (shopHasActiveBrowsers(shop))
1171 1174 { continue; }
1175 const origin = entity.spawnOrigin;
1176 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1177 { continue; }
1172 1178 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1173 1179 if (def?.freeFlight)
1174 1180 { continue; }
@@ -1180,7 +1186,6 @@ export class WorkerWorld
1180 1186 if (Math.random() > 0.4)
1181 1187 { continue; }
1182 1188
1183 const origin = entity.spawnOrigin;
1184 1189 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1185 1190 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1186 1191 const range = Math.max(0, origin.wanderRangeTiles | 0);
@@ -1207,6 +1212,108 @@ export class WorkerWorld
1207 1212 }
1208 1213 }
1209 1214
1215 /**
1216 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1217 * message: { stationTileX, stationTileY }
1218 */
1219 #stationExchangeClerk (message)
1220 {
1221 const stationTileX = message.stationTileX | 0;
1222 const stationTileY = message.stationTileY | 0;
1223 if (!this.isEnterable(stationTileX, stationTileY))
1224 { return { ok: false, reason: "blocked" }; }
1225
1226 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1227 {
1228 if (!entity.spawnOrigin?.centralExchange)
1229 { continue; }
1230 if (
1231 Number.isInteger(entity.spawnOrigin.stationTileX)
1232 && entity.spawnOrigin.stationTileX === stationTileX
1233 && entity.spawnOrigin.stationTileY === stationTileY
1234 )
1235 { return { ok: true, entityId: entity.entityId, already: true }; }
1236 }
1237
1238 let best = null;
1239 let bestDist = Infinity;
1240 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1241 {
1242 if (!entity.spawnOrigin?.centralExchange)
1243 { continue; }
1244 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1245 { continue; }
1246 const dist = Math.max(
1247 Math.abs(entity.position.tileX - stationTileX),
1248 Math.abs(entity.position.tileY - stationTileY)
1249 );
1250 if (dist < bestDist)
1251 {
1252 bestDist = dist;
1253 best = entity;
1254 }
1255 }
1256 if (!best)
1257 { return { ok: false, reason: "none-available" }; }
1258
1259 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1260 const tiles = findPath(
1261 best.position.tileX,
1262 best.position.tileY,
1263 stationTileX,
1264 stationTileY,
1265 (x, y) => this.walkableFor(best.entityId, x, y),
1266 bounds.minX,
1267 bounds.minY,
1268 bounds.maxX,
1269 bounds.maxY
1270 );
1271 best.spawnOrigin.stationTileX = stationTileX;
1272 best.spawnOrigin.stationTileY = stationTileY;
1273 if (tiles?.length)
1274 { best.path.tiles = tiles; }
1275 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1276 { best.path.tiles = []; }
1277 else
1278 { return { ok: false, reason: "no-path" }; }
1279 return { ok: true, entityId: best.entityId };
1280 }
1281
1282 /** Keep stationed CE clerks at their counter tile. */
1283 #queueExchangeStations ()
1284 {
1285 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1286 {
1287 if (!entity.spawnOrigin?.centralExchange)
1288 { continue; }
1289 const sx = entity.spawnOrigin.stationTileX;
1290 const sy = entity.spawnOrigin.stationTileY;
1291 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1292 { continue; }
1293 if (entity.position.tileX === sx && entity.position.tileY === sy)
1294 {
1295 entity.path.tiles = [];
1296 continue;
1297 }
1298 if (entity.path.tiles?.length)
1299 { continue; }
1300 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1301 const tiles = findPath(
1302 entity.position.tileX,
1303 entity.position.tileY,
1304 sx,
1305 sy,
1306 (x, y) => this.walkableFor(entity.entityId, x, y),
1307 bounds.minX,
1308 bounds.minY,
1309 bounds.maxX,
1310 bounds.maxY
1311 );
1312 if (tiles?.length)
1313 { entity.path.tiles = tiles; }
1314 }
1315 }
1316
1210 1317 #applyTransfer (message)
1211 1318 {
1212 1319 const payload = message.payload;
@@ -171,6 +171,8 @@ export class WorkerWorld
171 { this.itemLastSales.set(Number(key), sale); }
171 { this.itemLastSales.set(Number(key), sale); }
172 return { ok: true };
172 return { ok: true };
173 }
173 }
174 case WorkerMessage.stationExchangeClerk:
175 return this.#stationExchangeClerk(message);
174 default:
176 default:
175 throw new Error(`Unknown worker message ${message.type}`);
177 throw new Error(`Unknown worker message ${message.type}`);
176 }
178 }
@@ -981,6 +983,7 @@ export class WorkerWorld
981 events.push(...pruneShopBrowsers(this));
983 events.push(...pruneShopBrowsers(this));
982 this.#queueAmbientWander();
984 this.#queueAmbientWander();
983 this.#queueSpawnerWander();
985 this.#queueSpawnerWander();
986 this.#queueExchangeStations();
984 for (const entity of this.ecs.query(Component.position, Component.movement))
987 for (const entity of this.ecs.query(Component.position, Component.movement))
985 {
988 {
986 const { handle, entityId, position, movement } = entity;
989 const { handle, entityId, position, movement } = entity;
@@ -1169,6 +1172,9 @@ export class WorkerWorld
1169 const shop = this.ecs.get(entity.handle, Component.shop);
1172 const shop = this.ecs.get(entity.handle, Component.shop);
1170 if (shopHasActiveBrowsers(shop))
1173 if (shopHasActiveBrowsers(shop))
1171 { continue; }
1174 { continue; }
1175 const origin = entity.spawnOrigin;
1176 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1177 { continue; }
1172 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1178 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1173 if (def?.freeFlight)
1179 if (def?.freeFlight)
1174 { continue; }
1180 { continue; }
@@ -1180,7 +1186,6 @@ export class WorkerWorld
1180 if (Math.random() > 0.4)
1186 if (Math.random() > 0.4)
1181 { continue; }
1187 { continue; }
1182
1188
1183 const origin = entity.spawnOrigin;
1184 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1189 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1185 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1190 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
1186 const range = Math.max(0, origin.wanderRangeTiles | 0);
1191 const range = Math.max(0, origin.wanderRangeTiles | 0);
@@ -1207,6 +1212,108 @@ export class WorkerWorld
1207 }
1212 }
1208 }
1213 }
1209
1214
1215 /**
1216 * Send an idle Central Exchange clerk to the staff-side tile of a counter.
1217 * message: { stationTileX, stationTileY }
1218 */
1219 #stationExchangeClerk (message)
1220 {
1221 const stationTileX = message.stationTileX | 0;
1222 const stationTileY = message.stationTileY | 0;
1223 if (!this.isEnterable(stationTileX, stationTileY))
1224 { return { ok: false, reason: "blocked" }; }
1225
1226 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1227 {
1228 if (!entity.spawnOrigin?.centralExchange)
1229 { continue; }
1230 if (
1231 Number.isInteger(entity.spawnOrigin.stationTileX)
1232 && entity.spawnOrigin.stationTileX === stationTileX
1233 && entity.spawnOrigin.stationTileY === stationTileY
1234 )
1235 { return { ok: true, entityId: entity.entityId, already: true }; }
1236 }
1237
1238 let best = null;
1239 let bestDist = Infinity;
1240 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1241 {
1242 if (!entity.spawnOrigin?.centralExchange)
1243 { continue; }
1244 if (Number.isInteger(entity.spawnOrigin.stationTileX))
1245 { continue; }
1246 const dist = Math.max(
1247 Math.abs(entity.position.tileX - stationTileX),
1248 Math.abs(entity.position.tileY - stationTileY)
1249 );
1250 if (dist < bestDist)
1251 {
1252 bestDist = dist;
1253 best = entity;
1254 }
1255 }
1256 if (!best)
1257 { return { ok: false, reason: "none-available" }; }
1258
1259 const bounds = chunkBoundsAround(best.position.tileX, best.position.tileY, VISIBLE_CHUNK_RADIUS);
1260 const tiles = findPath(
1261 best.position.tileX,
1262 best.position.tileY,
1263 stationTileX,
1264 stationTileY,
1265 (x, y) => this.walkableFor(best.entityId, x, y),
1266 bounds.minX,
1267 bounds.minY,
1268 bounds.maxX,
1269 bounds.maxY
1270 );
1271 best.spawnOrigin.stationTileX = stationTileX;
1272 best.spawnOrigin.stationTileY = stationTileY;
1273 if (tiles?.length)
1274 { best.path.tiles = tiles; }
1275 else if (best.position.tileX === stationTileX && best.position.tileY === stationTileY)
1276 { best.path.tiles = []; }
1277 else
1278 { return { ok: false, reason: "no-path" }; }
1279 return { ok: true, entityId: best.entityId };
1280 }
1281
1282 /** Keep stationed CE clerks at their counter tile. */
1283 #queueExchangeStations ()
1284 {
1285 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position, Component.path))
1286 {
1287 if (!entity.spawnOrigin?.centralExchange)
1288 { continue; }
1289 const sx = entity.spawnOrigin.stationTileX;
1290 const sy = entity.spawnOrigin.stationTileY;
1291 if (!Number.isInteger(sx) || !Number.isInteger(sy))
1292 { continue; }
1293 if (entity.position.tileX === sx && entity.position.tileY === sy)
1294 {
1295 entity.path.tiles = [];
1296 continue;
1297 }
1298 if (entity.path.tiles?.length)
1299 { continue; }
1300 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
1301 const tiles = findPath(
1302 entity.position.tileX,
1303 entity.position.tileY,
1304 sx,
1305 sy,
1306 (x, y) => this.walkableFor(entity.entityId, x, y),
1307 bounds.minX,
1308 bounds.minY,
1309 bounds.maxX,
1310 bounds.maxY
1311 );
1312 if (tiles?.length)
1313 { entity.path.tiles = tiles; }
1314 }
1315 }
1316
1210 #applyTransfer (message)
1317 #applyTransfer (message)
1211 {
1318 {
1212 const payload = message.payload;
1319 const payload = message.payload;
server/src/world/chunkData.js +12 −0
@@ -3,6 +3,7 @@ import {
3 3 GroundType,
4 4 BlockType,
5 5 isBlockPassable,
6 isBlockOccludingLight,
6 7 isGroundPassable,
7 8 blockLightRange,
8 9 normalizeGround,
@@ -156,6 +157,17 @@ export function isChunkTilePassable (data, localX, localY)
156 157 return isBlockPassable(block?.typeId ?? null);
157 158 }
158 159
160 /** Ground + block clear for light rays (furniture may be impassable but not occluding). */
161 export function isChunkTileClearForLight (data, localX, localY)
162 {
163 const index = tileIndex(localX, localY);
164 const ground = normalizeGround(data.grounds[index]);
165 if (!isGroundPassable(ground.typeId))
166 { return false; }
167 const block = data.blocks[index];
168 return !isBlockOccludingLight(block?.typeId ?? null);
169 }
170
159 171 export function collectLightSources (chunkX, chunkY, data)
160 172 {
161 173 const sources = [];
@@ -3,6 +3,7 @@ import {
3 GroundType,
3 GroundType,
4 BlockType,
4 BlockType,
5 isBlockPassable,
5 isBlockPassable,
6 isBlockOccludingLight,
6 isGroundPassable,
7 isGroundPassable,
7 blockLightRange,
8 blockLightRange,
8 normalizeGround,
9 normalizeGround,
@@ -156,6 +157,17 @@ export function isChunkTilePassable (data, localX, localY)
156 return isBlockPassable(block?.typeId ?? null);
157 return isBlockPassable(block?.typeId ?? null);
157}
158}
158
159
160/** Ground + block clear for light rays (furniture may be impassable but not occluding). */
161export function isChunkTileClearForLight (data, localX, localY)
162{
163 const index = tileIndex(localX, localY);
164 const ground = normalizeGround(data.grounds[index]);
165 if (!isGroundPassable(ground.typeId))
166 { return false; }
167 const block = data.blocks[index];
168 return !isBlockOccludingLight(block?.typeId ?? null);
169}
170
159export function collectLightSources (chunkX, chunkY, data)
171export function collectLightSources (chunkX, chunkY, data)
160{
172{
161 const sources = [];
173 const sources = [];
server/tests/central-exchange.test.js added +172 −0
@@ -0,0 +1,172 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 NeighborBit,
5 computeNeighborConnectMask,
6 neighborConnectStateName,
7 parseNeighborConnectMask,
8 composeNeighborConnectState,
9 neighborConnectBlocksMatch,
10 parseMaterialNeighborConnectState
11 } from "../../shared/world/neighborConnect.js";
12 import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";
13 import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";
14 import { BlockType, BLOCK_DEFINITIONS } from "../../shared/definitions/tiles.js";
15 import { ItemId } from "../../shared/definitions/items.js";
16 import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
17 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
18 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
19 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
20 import { Component } from "../src/ecs/components.js";
21
22 test("neighbor connect masks cover all NESW combinations", () =>
23 {
24 assert.equal(neighborConnectStateName(0), "0");
25 assert.equal(neighborConnectStateName(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w), "15");
26 assert.equal(parseNeighborConnectMask("6"), NeighborBit.e | NeighborBit.s);
27 const mask = computeNeighborConnectMask((dx, dy) => dx === 1 || dy === -1);
28 assert.equal(mask, NeighborBit.n | NeighborBit.e);
29 });
30
31 test("material neighbor-connect states keep wood id and only match same material", () =>
32 {
33 const def = BLOCK_DEFINITIONS[BlockType.table];
34 assert.equal(composeNeighborConnectState(def, "oak", 3), "oak-3");
35 assert.deepEqual(parseMaterialNeighborConnectState("birch-10", def), { material: "birch", mask: 10 });
36 const pine = { typeId: BlockType.table, state: "pine-0" };
37 const pineNeighbor = { typeId: BlockType.table, state: "pine-2" };
38 const oakNeighbor = { typeId: BlockType.table, state: "oak-2" };
39 assert.equal(neighborConnectBlocksMatch(pine, pineNeighbor, def), true);
40 assert.equal(neighborConnectBlocksMatch(pine, oakNeighbor, def), false);
41 });
42
43 test("CE staff entries include sex labels and pickExchangeClerk returns a name", () =>
44 {
45 assert.ok(CENTRAL_EXCHANGE_STAFF.length >= 2);
46 for (const staff of CENTRAL_EXCHANGE_STAFF)
47 {
48 assert.ok(staff.name);
49 assert.ok(staff.sex === "male" || staff.sex === "female");
50 }
51 const name = pickExchangeClerk(() => 0);
52 assert.equal(name, CENTRAL_EXCHANGE_STAFF[0].name);
53 });
54
55 test("central exchange spawner config locks staff count and strips shop options", () =>
56 {
57 const config = normalizeSpawnerConfig({
58 mobTypeId: MobId.centralExchange,
59 maxAlive: 2,
60 sells: [{ itemId: ItemId.apple, quantity: 1 }],
61 buysItems: true,
62 displayName: "ignored"
63 }, "ce:0");
64 assert.equal(config.centralExchange, true);
65 assert.equal(config.maxAlive, CENTRAL_EXCHANGE_STAFF.length);
66 assert.equal(config.sells.length, 0);
67 assert.equal(config.buysItems, false);
68 assert.equal(isCentralExchangeSpawner(config), true);
69 });
70
71 test("central exchange spawner places every clerk with matching names", () =>
72 {
73 const harness = makeSimulation({ workerCount: 1 });
74 try
75 {
76 const data = createEmptyChunkData();
77 data.open = true;
78 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
79 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
80 data.spawners = [{
81 localX: 8,
82 localY: 8,
83 config: normalizeSpawnerConfig({
84 mobTypeId: MobId.centralExchange,
85 spawnRangeTiles: 6,
86 maxWanderRangeTiles: 6,
87 equipment: { chest: ItemId.clothShirt }
88 }, "ce-test")
89 }];
90 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
91 harness.simulation.reloadWorld();
92 harness.advance(50);
93 for (let i = 0; i < 30; i++)
94 { harness.simulation.step(); }
95
96 const record = harness.simulation.entityRecord(
97 harness.simulation.spawnCharacter(1, makeCharacter(harness.stateDb, { tileX: 7, tileY: 7 }))
98 );
99 const worker = harness.simulation.workers[record.workerId];
100 for (let i = 0; i < 40; i++)
101 { harness.simulation.step(); }
102
103 const clerks = [];
104 for (const entity of worker.world.ecs.query(Component.spawnOrigin, Component.appearance))
105 {
106 if (!entity.spawnOrigin?.centralExchange)
107 { continue; }
108 clerks.push(entity.appearance.firstName);
109 }
110 assert.equal(clerks.length, CENTRAL_EXCHANGE_STAFF.length);
111 for (const staff of CENTRAL_EXCHANGE_STAFF)
112 { assert.ok(clerks.includes(staff.name), staff.name); }
113 }
114 finally
115 { harness.close(); }
116 });
117
118 test("opening the market stations a CE clerk on the opposite side of the counter", () =>
119 {
120 const harness = makeSimulation({ workerCount: 1 });
121 try
122 {
123 const data = createEmptyChunkData();
124 data.open = true;
125 // Counter at (9,8); player will stand at (8,8); staff station = (10,8).
126 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
127 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
128 data.spawners = [{
129 localX: 12,
130 localY: 8,
131 config: normalizeSpawnerConfig({
132 mobTypeId: MobId.centralExchange,
133 spawnRangeTiles: 8,
134 maxWanderRangeTiles: 8
135 }, "ce-station")
136 }];
137 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
138 harness.simulation.reloadWorld();
139
140 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
141 const funded = addCoinsToSlots(emptySlots(), 10);
142 harness.stateDb.saveBag(character.character_id, {
143 inventory: funded.slots,
144 equipment: emptyEquipment(),
145 vault: [],
146 vaultReserved: []
147 });
148 const playerId = harness.simulation.spawnCharacter(1, character);
149 for (let i = 0; i < 40; i++)
150 { harness.simulation.step(); }
151
152 harness.simulation.enqueue(1, {
153 type: "open-market",
154 characterId: character.character_id
155 });
156 harness.simulation.step();
157
158 const record = harness.simulation.entityRecord(playerId);
159 const worker = harness.simulation.workers[record.workerId];
160 let stationed = false;
161 for (const entity of worker.world.ecs.query(Component.spawnOrigin))
162 {
163 if (!entity.spawnOrigin?.centralExchange)
164 { continue; }
165 if (entity.spawnOrigin.stationTileX === 10 && entity.spawnOrigin.stationTileY === 8)
166 { stationed = true; }
167 }
168 assert.equal(stationed, true);
169 }
170 finally
171 { harness.close(); }
172 });
@@ -0,0 +1,172 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 NeighborBit,
5 computeNeighborConnectMask,
6 neighborConnectStateName,
7 parseNeighborConnectMask,
8 composeNeighborConnectState,
9 neighborConnectBlocksMatch,
10 parseMaterialNeighborConnectState
11} from "../../shared/world/neighborConnect.js";
12import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";
13import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";
14import { BlockType, BLOCK_DEFINITIONS } from "../../shared/definitions/tiles.js";
15import { ItemId } from "../../shared/definitions/items.js";
16import { emptyEquipment, emptySlots, addCoinsToSlots } from "../../shared/items/inventory.js";
17import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
18import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
19import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
20import { Component } from "../src/ecs/components.js";
21
22test("neighbor connect masks cover all NESW combinations", () =>
23{
24 assert.equal(neighborConnectStateName(0), "0");
25 assert.equal(neighborConnectStateName(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w), "15");
26 assert.equal(parseNeighborConnectMask("6"), NeighborBit.e | NeighborBit.s);
27 const mask = computeNeighborConnectMask((dx, dy) => dx === 1 || dy === -1);
28 assert.equal(mask, NeighborBit.n | NeighborBit.e);
29});
30
31test("material neighbor-connect states keep wood id and only match same material", () =>
32{
33 const def = BLOCK_DEFINITIONS[BlockType.table];
34 assert.equal(composeNeighborConnectState(def, "oak", 3), "oak-3");
35 assert.deepEqual(parseMaterialNeighborConnectState("birch-10", def), { material: "birch", mask: 10 });
36 const pine = { typeId: BlockType.table, state: "pine-0" };
37 const pineNeighbor = { typeId: BlockType.table, state: "pine-2" };
38 const oakNeighbor = { typeId: BlockType.table, state: "oak-2" };
39 assert.equal(neighborConnectBlocksMatch(pine, pineNeighbor, def), true);
40 assert.equal(neighborConnectBlocksMatch(pine, oakNeighbor, def), false);
41});
42
43test("CE staff entries include sex labels and pickExchangeClerk returns a name", () =>
44{
45 assert.ok(CENTRAL_EXCHANGE_STAFF.length >= 2);
46 for (const staff of CENTRAL_EXCHANGE_STAFF)
47 {
48 assert.ok(staff.name);
49 assert.ok(staff.sex === "male" || staff.sex === "female");
50 }
51 const name = pickExchangeClerk(() => 0);
52 assert.equal(name, CENTRAL_EXCHANGE_STAFF[0].name);
53});
54
55test("central exchange spawner config locks staff count and strips shop options", () =>
56{
57 const config = normalizeSpawnerConfig({
58 mobTypeId: MobId.centralExchange,
59 maxAlive: 2,
60 sells: [{ itemId: ItemId.apple, quantity: 1 }],
61 buysItems: true,
62 displayName: "ignored"
63 }, "ce:0");
64 assert.equal(config.centralExchange, true);
65 assert.equal(config.maxAlive, CENTRAL_EXCHANGE_STAFF.length);
66 assert.equal(config.sells.length, 0);
67 assert.equal(config.buysItems, false);
68 assert.equal(isCentralExchangeSpawner(config), true);
69});
70
71test("central exchange spawner places every clerk with matching names", () =>
72{
73 const harness = makeSimulation({ workerCount: 1 });
74 try
75 {
76 const data = createEmptyChunkData();
77 data.open = true;
78 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
79 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
80 data.spawners = [{
81 localX: 8,
82 localY: 8,
83 config: normalizeSpawnerConfig({
84 mobTypeId: MobId.centralExchange,
85 spawnRangeTiles: 6,
86 maxWanderRangeTiles: 6,
87 equipment: { chest: ItemId.clothShirt }
88 }, "ce-test")
89 }];
90 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
91 harness.simulation.reloadWorld();
92 harness.advance(50);
93 for (let i = 0; i < 30; i++)
94 { harness.simulation.step(); }
95
96 const record = harness.simulation.entityRecord(
97 harness.simulation.spawnCharacter(1, makeCharacter(harness.stateDb, { tileX: 7, tileY: 7 }))
98 );
99 const worker = harness.simulation.workers[record.workerId];
100 for (let i = 0; i < 40; i++)
101 { harness.simulation.step(); }
102
103 const clerks = [];
104 for (const entity of worker.world.ecs.query(Component.spawnOrigin, Component.appearance))
105 {
106 if (!entity.spawnOrigin?.centralExchange)
107 { continue; }
108 clerks.push(entity.appearance.firstName);
109 }
110 assert.equal(clerks.length, CENTRAL_EXCHANGE_STAFF.length);
111 for (const staff of CENTRAL_EXCHANGE_STAFF)
112 { assert.ok(clerks.includes(staff.name), staff.name); }
113 }
114 finally
115 { harness.close(); }
116});
117
118test("opening the market stations a CE clerk on the opposite side of the counter", () =>
119{
120 const harness = makeSimulation({ workerCount: 1 });
121 try
122 {
123 const data = createEmptyChunkData();
124 data.open = true;
125 // Counter at (9,8); player will stand at (8,8); staff station = (10,8).
126 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
127 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
128 data.spawners = [{
129 localX: 12,
130 localY: 8,
131 config: normalizeSpawnerConfig({
132 mobTypeId: MobId.centralExchange,
133 spawnRangeTiles: 8,
134 maxWanderRangeTiles: 8
135 }, "ce-station")
136 }];
137 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
138 harness.simulation.reloadWorld();
139
140 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
141 const funded = addCoinsToSlots(emptySlots(), 10);
142 harness.stateDb.saveBag(character.character_id, {
143 inventory: funded.slots,
144 equipment: emptyEquipment(),
145 vault: [],
146 vaultReserved: []
147 });
148 const playerId = harness.simulation.spawnCharacter(1, character);
149 for (let i = 0; i < 40; i++)
150 { harness.simulation.step(); }
151
152 harness.simulation.enqueue(1, {
153 type: "open-market",
154 characterId: character.character_id
155 });
156 harness.simulation.step();
157
158 const record = harness.simulation.entityRecord(playerId);
159 const worker = harness.simulation.workers[record.workerId];
160 let stationed = false;
161 for (const entity of worker.world.ecs.query(Component.spawnOrigin))
162 {
163 if (!entity.spawnOrigin?.centralExchange)
164 { continue; }
165 if (entity.spawnOrigin.stationTileX === 10 && entity.spawnOrigin.stationTileY === 8)
166 { stationed = true; }
167 }
168 assert.equal(stationed, true);
169 }
170 finally
171 { harness.close(); }
172});
server/tests/lighting.test.js +37 −0
@@ -55,3 +55,40 @@ test("dynamic lights use the same wall occlusion as baked light", () =>
55 55 assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
56 56 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
57 57 });
58
59 test("tables and marketplace counters do not occlude light rays", () =>
60 {
61 const origin = createEmptyChunkData();
62 origin.open = true;
63 origin.blocks[0] = { typeId: BlockType.torch, config: null };
64 origin.blocks[1] = { typeId: BlockType.table, state: "pine-0", config: null };
65 origin.blocks[2] = { typeId: BlockType.marketplace, state: "0", config: null };
66
67 const baked = bakeLightMaps(0, 0, (x, y) =>
68 {
69 if (x === 0 && y === 0)
70 { return origin; }
71 return createEmptyChunkData();
72 }, 8);
73
74 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
75 assert.ok(self.light[3] > 0, "light passes through table and counter");
76 });
77
78 test("anvil occludes light by default (omit blocksLight)", () =>
79 {
80 const origin = createEmptyChunkData();
81 origin.open = true;
82 origin.blocks[0] = { typeId: BlockType.torch, config: null };
83 origin.blocks[1] = { typeId: BlockType.anvil, config: null };
84
85 const baked = bakeLightMaps(0, 0, (x, y) =>
86 {
87 if (x === 0 && y === 0)
88 { return origin; }
89 return createEmptyChunkData();
90 }, 8);
91
92 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
93 assert.equal(self.light[2], 0, "tile behind anvil stays unlit");
94 });
@@ -55,3 +55,40 @@ test("dynamic lights use the same wall occlusion as baked light", () =>
55 assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
55 assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
56 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
56 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
57});
57});
58
59test("tables and marketplace counters do not occlude light rays", () =>
60{
61 const origin = createEmptyChunkData();
62 origin.open = true;
63 origin.blocks[0] = { typeId: BlockType.torch, config: null };
64 origin.blocks[1] = { typeId: BlockType.table, state: "pine-0", config: null };
65 origin.blocks[2] = { typeId: BlockType.marketplace, state: "0", config: null };
66
67 const baked = bakeLightMaps(0, 0, (x, y) =>
68 {
69 if (x === 0 && y === 0)
70 { return origin; }
71 return createEmptyChunkData();
72 }, 8);
73
74 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
75 assert.ok(self.light[3] > 0, "light passes through table and counter");
76});
77
78test("anvil occludes light by default (omit blocksLight)", () =>
79{
80 const origin = createEmptyChunkData();
81 origin.open = true;
82 origin.blocks[0] = { typeId: BlockType.torch, config: null };
83 origin.blocks[1] = { typeId: BlockType.anvil, config: null };
84
85 const baked = bakeLightMaps(0, 0, (x, y) =>
86 {
87 if (x === 0 && y === 0)
88 { return origin; }
89 return createEmptyChunkData();
90 }, 8);
91
92 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
93 assert.equal(self.light[2], 0, "tile behind anvil stays unlit");
94});
server/tests/marketplace.test.js +42 −4
@@ -3,7 +3,8 @@ import assert from "node:assert/strict";
3 3 import { ItemId } from "../../shared/definitions/items.js";
4 4 import { BlockType } from "../../shared/definitions/tiles.js";
5 5 import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
6 import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";
6 import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js";
7 import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
7 8 import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
8 9 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9 10 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
@@ -42,6 +43,42 @@ test("midpoint trade price rounds half units deterministically", () =>
42 43 assert.equal(midpointTradePrice(80, 100), 90);
43 44 });
44 45
46 test("listing fee is 3% of notional rounded up", () =>
47 {
48 assert.equal(marketOrderListingFee(100, 1), 3);
49 assert.equal(marketOrderListingFee(10, 1), 1);
50 assert.equal(marketOrderListingFee(8, 2), 1);
51 assert.equal(marketOrderListingFee(0, 5), 0);
52 });
53
54 test("market funds spend whole coin cheques and return change", () =>
55 {
56 const slots = emptySlots();
57 slots[0] = {
58 itemId: ItemId.filledCheque,
59 quantity: 1,
60 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
61 };
62 const paid = takeMarketFunds(slots, 25);
63 assert.equal(paid.ok, true);
64 assert.equal(paid.change, 15);
65 assert.equal(paid.redeemedCheques.length, 1);
66 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
67 });
68
69 test("written cheque sell listing locks quantity to reserved goods", () =>
70 {
71 const listing = resolveMarketSellListing({
72 itemId: ItemId.filledCheque,
73 quantity: 1,
74 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
75 });
76 assert.equal(listing.isCheque, true);
77 assert.equal(listing.itemId, ItemId.apple);
78 assert.equal(listing.quantity, 7);
79 assert.equal(listing.quantityLocked, true);
80 });
81
45 82 function placePlaza (worldDb)
46 83 {
47 84 const data = createEmptyChunkData();
@@ -61,8 +98,9 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
61 98
62 99 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
63 100 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
64 const sellerBag = addCoinsToSlots(emptySlots(), 0);
65 sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 };
101 const sellerBag = addCoinsToSlots(emptySlots(), 5);
102 assert.equal(sellerBag.ok, true);
103 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
66 104 harness.stateDb.saveBag(seller.character_id, {
67 105 inventory: sellerBag.slots,
68 106 equipment: emptyEquipment(),
@@ -85,7 +123,7 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
85 123 harness.simulation.enqueue(1, {
86 124 type: "place-market-sell",
87 125 characterId: seller.character_id,
88 slotIndex: 0,
126 slotIndex: 1,
89 127 quantity: 2,
90 128 minUnitPrice: 8
91 129 });
@@ -3,7 +3,8 @@ import assert from "node:assert/strict";
3import { ItemId } from "../../shared/definitions/items.js";
3import { ItemId } from "../../shared/definitions/items.js";
4import { BlockType } from "../../shared/definitions/tiles.js";
4import { BlockType } from "../../shared/definitions/tiles.js";
5import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
5import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
6import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody } from "../../shared/market/exchange.js";
6import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee } from "../../shared/market/exchange.js";
7import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
7import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
8import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
8import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
10import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
@@ -42,6 +43,42 @@ test("midpoint trade price rounds half units deterministically", () =>
42 assert.equal(midpointTradePrice(80, 100), 90);
43 assert.equal(midpointTradePrice(80, 100), 90);
43});
44});
44
45
46test("listing fee is 3% of notional rounded up", () =>
47{
48 assert.equal(marketOrderListingFee(100, 1), 3);
49 assert.equal(marketOrderListingFee(10, 1), 1);
50 assert.equal(marketOrderListingFee(8, 2), 1);
51 assert.equal(marketOrderListingFee(0, 5), 0);
52});
53
54test("market funds spend whole coin cheques and return change", () =>
55{
56 const slots = emptySlots();
57 slots[0] = {
58 itemId: ItemId.filledCheque,
59 quantity: 1,
60 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
61 };
62 const paid = takeMarketFunds(slots, 25);
63 assert.equal(paid.ok, true);
64 assert.equal(paid.change, 15);
65 assert.equal(paid.redeemedCheques.length, 1);
66 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
67});
68
69test("written cheque sell listing locks quantity to reserved goods", () =>
70{
71 const listing = resolveMarketSellListing({
72 itemId: ItemId.filledCheque,
73 quantity: 1,
74 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
75 });
76 assert.equal(listing.isCheque, true);
77 assert.equal(listing.itemId, ItemId.apple);
78 assert.equal(listing.quantity, 7);
79 assert.equal(listing.quantityLocked, true);
80});
81
45function placePlaza (worldDb)
82function placePlaza (worldDb)
46{
83{
47 const data = createEmptyChunkData();
84 const data = createEmptyChunkData();
@@ -61,8 +98,9 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
61
98
62 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
99 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
63 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
100 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
64 const sellerBag = addCoinsToSlots(emptySlots(), 0);
101 const sellerBag = addCoinsToSlots(emptySlots(), 5);
65 sellerBag.slots[0] = { itemId: ItemId.apple, quantity: 2 };
102 assert.equal(sellerBag.ok, true);
103 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
66 harness.stateDb.saveBag(seller.character_id, {
104 harness.stateDb.saveBag(seller.character_id, {
67 inventory: sellerBag.slots,
105 inventory: sellerBag.slots,
68 equipment: emptyEquipment(),
106 equipment: emptyEquipment(),
@@ -85,7 +123,7 @@ test("sell then buy at Central Exchange matches at midpoint and pays seller by p
85 harness.simulation.enqueue(1, {
123 harness.simulation.enqueue(1, {
86 type: "place-market-sell",
124 type: "place-market-sell",
87 characterId: seller.character_id,
125 characterId: seller.character_id,
88 slotIndex: 0,
126 slotIndex: 1,
89 quantity: 2,
127 quantity: 2,
90 minUnitPrice: 8
128 minUnitPrice: 8
91 });
129 });
shared/definitions/mobs.js +58 −12
@@ -1,10 +1,13 @@
1 1 import { spriteImageName } from "./tileSprites.js";
2 import { centralExchangeStaffCount } from "../market/exchange.js";
2 3
3 4 export const MobId = Object.freeze({
4 5 deer: "deer",
5 6 pigeon: "pigeon",
6 7 rat: "rat",
7 humanoid: "humanoid"
8 humanoid: "humanoid",
9 /** Editor/spawner identity for Central Exchange staff (always humanoid bodies). */
10 centralExchange: "central-exchange"
8 11 });
9 12
10 13 /** @typedef {{ itemId: number, chance: number }} MobDrop */
@@ -126,6 +129,32 @@ export const MOB_DEFINITIONS = Object.freeze({
126 129 frames: 1,
127 130 framesPerRow: 1,
128 131 animationSpeed: 0
132 }),
133 [MobId.centralExchange]: Object.freeze({
134 mobTypeId: MobId.centralExchange,
135 key: "central-exchange",
136 assetFolder: "characters",
137 displayName: "Central Exchange staff",
138 health: 10,
139 maxHealth: 10,
140 canFight: false,
141 drops: Object.freeze([]),
142 sells: Object.freeze([]),
143 dialogue: Object.freeze([]),
144 persistent: false,
145 flying: false,
146 freeFlight: false,
147 ambient: false,
148 talkable: false,
149 untargetable: false,
150 aggressive: false,
151 usePlayerBody: true,
152 centralExchange: true,
153 gait: "walk",
154 sex: "male",
155 frames: 1,
156 framesPerRow: 1,
157 animationSpeed: 0
129 158 })
130 159 });
131 160
@@ -152,18 +181,22 @@ export function mobSpriteName (mobTypeId)
152 181 export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
153 182 {
154 183 const humanoid = mobTypeId === MobId.humanoid;
184 const centralExchange = mobTypeId === MobId.centralExchange;
155 185 return {
156 186 spawnerId,
157 187 mobTypeId,
158 maxAlive: humanoid ? 1 : 3,
159 spawnRangeTiles: humanoid ? 1 : 4,
160 maxWanderRangeTiles: humanoid ? 1 : 8,
188 maxAlive: centralExchange
189 ? centralExchangeStaffCount()
190 : (humanoid ? 1 : 3),
191 spawnRangeTiles: (humanoid || centralExchange) ? 1 : 4,
192 maxWanderRangeTiles: (humanoid || centralExchange) ? 1 : 8,
161 193 sex: "male",
162 194 displayName: humanoid ? "Shopkeeper" : "",
163 195 equipment: emptySpawnerEquipment(),
164 196 sells: [],
165 197 buysItems: false,
166 hiddenDiscount: 0.9
198 hiddenDiscount: 0.9,
199 centralExchange
167 200 };
168 201 }
169 202
@@ -227,8 +260,10 @@ function normalizeSells (raw)
227 260 export function normalizeSpawnerConfig (config, spawnerId = "spawner")
228 261 {
229 262 const mobTypeId = config?.mobTypeId ?? MobId.deer;
230 const base = defaultSpawnerConfig(spawnerId, mobTypeId);
231 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId };
263 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
264 const effectiveMob = centralExchange ? MobId.centralExchange : mobTypeId;
265 const base = defaultSpawnerConfig(spawnerId, effectiveMob);
266 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId: effectiveMob };
232 267 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
233 268 const maxWanderRangeTiles = Math.max(
234 269 spawnRangeTiles,
@@ -237,18 +272,22 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
237 272 const sex = merged.sex === "female" ? "female" : "male";
238 273 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
239 274 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
275 const staffCap = centralExchangeStaffCount();
240 276 return {
241 277 spawnerId: String(merged.spawnerId),
242 mobTypeId: merged.mobTypeId ?? MobId.deer,
243 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
278 mobTypeId: effectiveMob,
279 maxAlive: centralExchange
280 ? staffCap
281 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
244 282 spawnRangeTiles,
245 283 maxWanderRangeTiles,
246 284 sex,
247 285 displayName,
248 286 equipment: normalizeEquipment(merged.equipment),
249 sells: normalizeSells(merged.sells),
250 buysItems: !!merged.buysItems,
251 hiddenDiscount
287 sells: centralExchange ? [] : normalizeSells(merged.sells),
288 buysItems: centralExchange ? false : !!merged.buysItems,
289 hiddenDiscount,
290 centralExchange
252 291 };
253 292 }
254 293
@@ -267,3 +306,10 @@ export function isHumanoidMob (mobTypeId)
267 306 {
268 307 return mobDefinition(mobTypeId)?.usePlayerBody === true;
269 308 }
309
310 export function isCentralExchangeSpawner (configOrMobTypeId)
311 {
312 if (configOrMobTypeId && typeof configOrMobTypeId === "object")
313 { return !!configOrMobTypeId.centralExchange || configOrMobTypeId.mobTypeId === MobId.centralExchange; }
314 return configOrMobTypeId === MobId.centralExchange;
315 }
@@ -1,10 +1,13 @@
1import { spriteImageName } from "./tileSprites.js";
1import { spriteImageName } from "./tileSprites.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
2
3
3export const MobId = Object.freeze({
4export const MobId = Object.freeze({
4 deer: "deer",
5 deer: "deer",
5 pigeon: "pigeon",
6 pigeon: "pigeon",
6 rat: "rat",
7 rat: "rat",
7 humanoid: "humanoid"
8 humanoid: "humanoid",
9 /** Editor/spawner identity for Central Exchange staff (always humanoid bodies). */
10 centralExchange: "central-exchange"
8});
11});
9
12
10/** @typedef {{ itemId: number, chance: number }} MobDrop */
13/** @typedef {{ itemId: number, chance: number }} MobDrop */
@@ -126,6 +129,32 @@ export const MOB_DEFINITIONS = Object.freeze({
126 frames: 1,
129 frames: 1,
127 framesPerRow: 1,
130 framesPerRow: 1,
128 animationSpeed: 0
131 animationSpeed: 0
132 }),
133 [MobId.centralExchange]: Object.freeze({
134 mobTypeId: MobId.centralExchange,
135 key: "central-exchange",
136 assetFolder: "characters",
137 displayName: "Central Exchange staff",
138 health: 10,
139 maxHealth: 10,
140 canFight: false,
141 drops: Object.freeze([]),
142 sells: Object.freeze([]),
143 dialogue: Object.freeze([]),
144 persistent: false,
145 flying: false,
146 freeFlight: false,
147 ambient: false,
148 talkable: false,
149 untargetable: false,
150 aggressive: false,
151 usePlayerBody: true,
152 centralExchange: true,
153 gait: "walk",
154 sex: "male",
155 frames: 1,
156 framesPerRow: 1,
157 animationSpeed: 0
129 })
158 })
130});
159});
131
160
@@ -152,18 +181,22 @@ export function mobSpriteName (mobTypeId)
152export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
181export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
153{
182{
154 const humanoid = mobTypeId === MobId.humanoid;
183 const humanoid = mobTypeId === MobId.humanoid;
184 const centralExchange = mobTypeId === MobId.centralExchange;
155 return {
185 return {
156 spawnerId,
186 spawnerId,
157 mobTypeId,
187 mobTypeId,
158 maxAlive: humanoid ? 1 : 3,
188 maxAlive: centralExchange
159 spawnRangeTiles: humanoid ? 1 : 4,
189 ? centralExchangeStaffCount()
160 maxWanderRangeTiles: humanoid ? 1 : 8,
190 : (humanoid ? 1 : 3),
191 spawnRangeTiles: (humanoid || centralExchange) ? 1 : 4,
192 maxWanderRangeTiles: (humanoid || centralExchange) ? 1 : 8,
161 sex: "male",
193 sex: "male",
162 displayName: humanoid ? "Shopkeeper" : "",
194 displayName: humanoid ? "Shopkeeper" : "",
163 equipment: emptySpawnerEquipment(),
195 equipment: emptySpawnerEquipment(),
164 sells: [],
196 sells: [],
165 buysItems: false,
197 buysItems: false,
166 hiddenDiscount: 0.9
198 hiddenDiscount: 0.9,
199 centralExchange
167 };
200 };
168}
201}
169
202
@@ -227,8 +260,10 @@ function normalizeSells (raw)
227export function normalizeSpawnerConfig (config, spawnerId = "spawner")
260export function normalizeSpawnerConfig (config, spawnerId = "spawner")
228{
261{
229 const mobTypeId = config?.mobTypeId ?? MobId.deer;
262 const mobTypeId = config?.mobTypeId ?? MobId.deer;
230 const base = defaultSpawnerConfig(spawnerId, mobTypeId);
263 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
231 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId };
264 const effectiveMob = centralExchange ? MobId.centralExchange : mobTypeId;
265 const base = defaultSpawnerConfig(spawnerId, effectiveMob);
266 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId: effectiveMob };
232 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
267 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
233 const maxWanderRangeTiles = Math.max(
268 const maxWanderRangeTiles = Math.max(
234 spawnRangeTiles,
269 spawnRangeTiles,
@@ -237,18 +272,22 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
237 const sex = merged.sex === "female" ? "female" : "male";
272 const sex = merged.sex === "female" ? "female" : "male";
238 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
273 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
239 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
274 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
275 const staffCap = centralExchangeStaffCount();
240 return {
276 return {
241 spawnerId: String(merged.spawnerId),
277 spawnerId: String(merged.spawnerId),
242 mobTypeId: merged.mobTypeId ?? MobId.deer,
278 mobTypeId: effectiveMob,
243 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
279 maxAlive: centralExchange
280 ? staffCap
281 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
244 spawnRangeTiles,
282 spawnRangeTiles,
245 maxWanderRangeTiles,
283 maxWanderRangeTiles,
246 sex,
284 sex,
247 displayName,
285 displayName,
248 equipment: normalizeEquipment(merged.equipment),
286 equipment: normalizeEquipment(merged.equipment),
249 sells: normalizeSells(merged.sells),
287 sells: centralExchange ? [] : normalizeSells(merged.sells),
250 buysItems: !!merged.buysItems,
288 buysItems: centralExchange ? false : !!merged.buysItems,
251 hiddenDiscount
289 hiddenDiscount,
290 centralExchange
252 };
291 };
253}
292}
254
293
@@ -267,3 +306,10 @@ export function isHumanoidMob (mobTypeId)
267{
306{
268 return mobDefinition(mobTypeId)?.usePlayerBody === true;
307 return mobDefinition(mobTypeId)?.usePlayerBody === true;
269}
308}
309
310export function isCentralExchangeSpawner (configOrMobTypeId)
311{
312 if (configOrMobTypeId && typeof configOrMobTypeId === "object")
313 { return !!configOrMobTypeId.centralExchange || configOrMobTypeId.mobTypeId === MobId.centralExchange; }
314 return configOrMobTypeId === MobId.centralExchange;
315}
shared/definitions/tiles.js +75 −4
@@ -3,10 +3,15 @@ import {
3 3 oreBoulderState,
4 4 materialFromOreBoulderState,
5 5 MATERIAL_DISPLAY_NAME,
6 WoodTier
6 WoodTier,
7 WOOD_TIER_ORDER
7 8 } from "./materialTiers.js";
8 9 import { spriteImageName, resolveState } from "./tileSprites.js";
9 10 import { isSeasonalStumpState, SeasonId } from "../world/season.js";
11 import {
12 composeNeighborConnectState,
13 definitionUsesMaterialNeighborConnect
14 } from "../world/neighborConnect.js";
10 15
11 16 export const GroundType = Object.freeze({
12 17 grass: 1,
@@ -29,7 +34,8 @@ export const BlockType = Object.freeze({
29 34 woodworkingBench: 10,
30 35 craftingBench: 11,
31 36 pineTree: 12,
32 marketplace: 13
37 marketplace: 13,
38 table: 14
33 39 });
34 40
35 41 export const GROUND_DEFINITIONS = Object.freeze({
@@ -232,13 +238,33 @@ export const BLOCK_DEFINITIONS = Object.freeze({
232 238 [BlockType.marketplace]: Object.freeze({
233 239 id: BlockType.marketplace,
234 240 key: "marketplace",
235 displayName: "Central Exchange",
241 displayName: "Central Exchange counter",
236 242 passable: false,
243 /** Furniture: blocks movement but not baked/dynamic light rays. */
244 blocksLight: false,
237 245 lightRangeTiles: 0,
238 246 frames: 1,
239 247 framesPerRow: 1,
240 248 animationSpeed: 0,
241 outdoor: false
249 outdoor: false,
250 /** Autotile via N/E/S/W bitmask states `"0"`…`"15"`. */
251 neighborConnect: true
252 }),
253 [BlockType.table]: Object.freeze({
254 id: BlockType.table,
255 key: "table",
256 displayName: "Table",
257 passable: false,
258 blocksLight: false,
259 lightRangeTiles: 0,
260 frames: 1,
261 framesPerRow: 1,
262 animationSpeed: 0,
263 outdoor: false,
264 /** Magenta base `0`–`15`; catalog expands `${wood}-${mask}` with wood tints. */
265 neighborConnect: true,
266 neighborConnectByMaterial: true,
267 defaultNeighborMaterial: WoodTier.pine
242 268 })
243 269 });
244 270
@@ -328,6 +354,33 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
328 354 }
329 355 continue;
330 356 }
357 if (def.neighborConnect)
358 {
359 if (definitionUsesMaterialNeighborConnect(def))
360 {
361 for (const material of WOOD_TIER_ORDER)
362 {
363 const state = composeNeighborConnectState(def, material, 0);
364 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
365 entries.push({
366 typeId: def.id,
367 state,
368 key: def.key,
369 displayName: `${label} table`,
370 spriteName: spriteImageName("block", def.key, state)
371 });
372 }
373 continue;
374 }
375 entries.push({
376 typeId: def.id,
377 state: "0",
378 key: def.key,
379 displayName: def.displayName,
380 spriteName: spriteImageName("block", def.key, "0")
381 });
382 continue;
383 }
331 384 const states = catalog?.blocks?.[def.key]?.states ?? [];
332 385 const state = resolveState(states, null);
333 386 entries.push({
@@ -399,6 +452,24 @@ export function isBlockPassable (typeId)
399 452 return def ? def.passable : false;
400 453 }
401 454
455 /**
456 * Whether a block occludes baked/dynamic light rays through its tile.
457 * Defaults to `!passable` when `blocksLight` is omitted (walls block, open floor does not).
458 * Set `blocksLight: false` on furniture (table, counter, anvil, …) to let light through
459 * while keeping `passable: false` for movement.
460 */
461 export function isBlockOccludingLight (typeId)
462 {
463 if (typeId == null)
464 { return false; }
465 const def = blockDefinition(typeId);
466 if (!def)
467 { return true; }
468 if (def.blocksLight != null)
469 { return !!def.blocksLight; }
470 return def.passable === false;
471 }
472
402 473 export function blockLightRange (typeId)
403 474 {
404 475 const def = blockDefinition(typeId);
@@ -3,10 +3,15 @@ import {
3 oreBoulderState,
3 oreBoulderState,
4 materialFromOreBoulderState,
4 materialFromOreBoulderState,
5 MATERIAL_DISPLAY_NAME,
5 MATERIAL_DISPLAY_NAME,
6 WoodTier
6 WoodTier,
7 WOOD_TIER_ORDER
7} from "./materialTiers.js";
8} from "./materialTiers.js";
8import { spriteImageName, resolveState } from "./tileSprites.js";
9import { spriteImageName, resolveState } from "./tileSprites.js";
9import { isSeasonalStumpState, SeasonId } from "../world/season.js";
10import { isSeasonalStumpState, SeasonId } from "../world/season.js";
11import {
12 composeNeighborConnectState,
13 definitionUsesMaterialNeighborConnect
14} from "../world/neighborConnect.js";
10
15
11export const GroundType = Object.freeze({
16export const GroundType = Object.freeze({
12 grass: 1,
17 grass: 1,
@@ -29,7 +34,8 @@ export const BlockType = Object.freeze({
29 woodworkingBench: 10,
34 woodworkingBench: 10,
30 craftingBench: 11,
35 craftingBench: 11,
31 pineTree: 12,
36 pineTree: 12,
32 marketplace: 13
37 marketplace: 13,
38 table: 14
33});
39});
34
40
35export const GROUND_DEFINITIONS = Object.freeze({
41export const GROUND_DEFINITIONS = Object.freeze({
@@ -232,13 +238,33 @@ export const BLOCK_DEFINITIONS = Object.freeze({
232 [BlockType.marketplace]: Object.freeze({
238 [BlockType.marketplace]: Object.freeze({
233 id: BlockType.marketplace,
239 id: BlockType.marketplace,
234 key: "marketplace",
240 key: "marketplace",
235 displayName: "Central Exchange",
241 displayName: "Central Exchange counter",
236 passable: false,
242 passable: false,
243 /** Furniture: blocks movement but not baked/dynamic light rays. */
244 blocksLight: false,
237 lightRangeTiles: 0,
245 lightRangeTiles: 0,
238 frames: 1,
246 frames: 1,
239 framesPerRow: 1,
247 framesPerRow: 1,
240 animationSpeed: 0,
248 animationSpeed: 0,
241 outdoor: false
249 outdoor: false,
250 /** Autotile via N/E/S/W bitmask states `"0"`…`"15"`. */
251 neighborConnect: true
252 }),
253 [BlockType.table]: Object.freeze({
254 id: BlockType.table,
255 key: "table",
256 displayName: "Table",
257 passable: false,
258 blocksLight: false,
259 lightRangeTiles: 0,
260 frames: 1,
261 framesPerRow: 1,
262 animationSpeed: 0,
263 outdoor: false,
264 /** Magenta base `0`–`15`; catalog expands `${wood}-${mask}` with wood tints. */
265 neighborConnect: true,
266 neighborConnectByMaterial: true,
267 defaultNeighborMaterial: WoodTier.pine
242 })
268 })
243});
269});
244
270
@@ -328,6 +354,33 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
328 }
354 }
329 continue;
355 continue;
330 }
356 }
357 if (def.neighborConnect)
358 {
359 if (definitionUsesMaterialNeighborConnect(def))
360 {
361 for (const material of WOOD_TIER_ORDER)
362 {
363 const state = composeNeighborConnectState(def, material, 0);
364 const label = MATERIAL_DISPLAY_NAME[material] ?? material;
365 entries.push({
366 typeId: def.id,
367 state,
368 key: def.key,
369 displayName: `${label} table`,
370 spriteName: spriteImageName("block", def.key, state)
371 });
372 }
373 continue;
374 }
375 entries.push({
376 typeId: def.id,
377 state: "0",
378 key: def.key,
379 displayName: def.displayName,
380 spriteName: spriteImageName("block", def.key, "0")
381 });
382 continue;
383 }
331 const states = catalog?.blocks?.[def.key]?.states ?? [];
384 const states = catalog?.blocks?.[def.key]?.states ?? [];
332 const state = resolveState(states, null);
385 const state = resolveState(states, null);
333 entries.push({
386 entries.push({
@@ -399,6 +452,24 @@ export function isBlockPassable (typeId)
399 return def ? def.passable : false;
452 return def ? def.passable : false;
400}
453}
401
454
455/**
456 * Whether a block occludes baked/dynamic light rays through its tile.
457 * Defaults to `!passable` when `blocksLight` is omitted (walls block, open floor does not).
458 * Set `blocksLight: false` on furniture (table, counter, anvil, …) to let light through
459 * while keeping `passable: false` for movement.
460 */
461export function isBlockOccludingLight (typeId)
462{
463 if (typeId == null)
464 { return false; }
465 const def = blockDefinition(typeId);
466 if (!def)
467 { return true; }
468 if (def.blocksLight != null)
469 { return !!def.blocksLight; }
470 return def.passable === false;
471}
472
402export function blockLightRange (typeId)
473export function blockLightRange (typeId)
403{
474{
404 const def = blockDefinition(typeId);
475 const def = blockDefinition(typeId);
shared/lighting/tilePassable.js +11 −3
@@ -1,7 +1,15 @@
1 1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import { isBlockPassable, isGroundPassable, normalizeGround } from "../definitions/tiles.js";
2 import {
3 isBlockOccludingLight,
4 isGroundPassable,
5 normalizeGround
6 } from "../definitions/tiles.js";
3 7
4 /** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
8 /**
9 * Light-ray clearance from a chunk snapshot map keyed by "chunkX,chunkY".
10 * Uses {@link isBlockOccludingLight} (not movement passability), so furniture
11 * with `blocksLight: false` does not cast night shade shadows.
12 */
5 13 export function makeSnapshotPassable (chunks)
6 14 {
7 15 return (tileX, tileY) =>
@@ -18,6 +26,6 @@ export function makeSnapshotPassable (chunks)
18 26 if (!isGroundPassable(ground.typeId))
19 27 { return false; }
20 28 const block = snapshot.blocks?.[index];
21 return isBlockPassable(block?.typeId ?? null);
29 return !isBlockOccludingLight(block?.typeId ?? null);
22 30 };
23 31 }
@@ -1,7 +1,15 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import { isBlockPassable, isGroundPassable, normalizeGround } from "../definitions/tiles.js";
2import {
3 isBlockOccludingLight,
4 isGroundPassable,
5 normalizeGround
6} from "../definitions/tiles.js";
3
7
4/** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
8/**
9 * Light-ray clearance from a chunk snapshot map keyed by "chunkX,chunkY".
10 * Uses {@link isBlockOccludingLight} (not movement passability), so furniture
11 * with `blocksLight: false` does not cast night shade shadows.
12 */
5export function makeSnapshotPassable (chunks)
13export function makeSnapshotPassable (chunks)
6{
14{
7 return (tileX, tileY) =>
15 return (tileX, tileY) =>
@@ -18,6 +26,6 @@ export function makeSnapshotPassable (chunks)
18 if (!isGroundPassable(ground.typeId))
26 if (!isGroundPassable(ground.typeId))
19 { return false; }
27 { return false; }
20 const block = snapshot.blocks?.[index];
28 const block = snapshot.blocks?.[index];
21 return isBlockPassable(block?.typeId ?? null);
29 return !isBlockOccludingLight(block?.typeId ?? null);
22 };
30 };
23}
31}
shared/market/exchange.js +28 −9
@@ -2,21 +2,40 @@
2 2
3 3 export const MARKET_ORDER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
4 4
5 /** Named clerks; sex drives humanoid body. */
5 6 export const CENTRAL_EXCHANGE_STAFF = Object.freeze([
6 "Bobby Pennies",
7 "Ada Ledger",
8 "Clive Quill",
9 "Marge Tally",
10 "Nigel Coinwright",
11 "Pearl Balance",
12 "Otto Vault",
13 "Iris Counter"
7 Object.freeze({ name: "Bobby Pennies", sex: "male" }),
8 Object.freeze({ name: "Ada Ledger", sex: "female" }),
9 Object.freeze({ name: "Clive Quill", sex: "male" }),
10 Object.freeze({ name: "Marge Tally", sex: "female" }),
11 Object.freeze({ name: "Nigel Coinwright", sex: "male" }),
12 Object.freeze({ name: "Pearl Balance", sex: "female" }),
13 Object.freeze({ name: "Otto Vault", sex: "male" }),
14 Object.freeze({ name: "Iris Counter", sex: "female" })
14 15 ]);
15 16
17 export function centralExchangeStaffCount ()
18 {
19 return CENTRAL_EXCHANGE_STAFF.length;
20 }
21
16 22 export function pickExchangeClerk (random = Math.random)
17 23 {
18 24 const index = Math.floor(random() * CENTRAL_EXCHANGE_STAFF.length) % CENTRAL_EXCHANGE_STAFF.length;
19 return CENTRAL_EXCHANGE_STAFF[index];
25 return CENTRAL_EXCHANGE_STAFF[index].name;
26 }
27
28 /** Listing fee charged when placing a buy or sell order (non-refundable). */
29 export const MARKET_ORDER_FEE_RATE = 0.03;
30
31 /** Fee = ceil(3% of unitPrice × quantity), minimum 1 when the notional is positive. */
32 export function marketOrderListingFee (unitPrice, quantity)
33 {
34 const notional = Math.max(0, Math.floor(Number(unitPrice) || 0))
35 * Math.max(0, Math.floor(Number(quantity) || 0));
36 if (notional <= 0)
37 { return 0; }
38 return Math.max(1, Math.ceil(notional * MARKET_ORDER_FEE_RATE));
20 39 }
21 40
22 41 export function exchangeSignature (clerkName)
@@ -2,21 +2,40 @@
2
2
3export const MARKET_ORDER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
3export const MARKET_ORDER_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
4
4
5/** Named clerks; sex drives humanoid body. */
5export const CENTRAL_EXCHANGE_STAFF = Object.freeze([
6export const CENTRAL_EXCHANGE_STAFF = Object.freeze([
6 "Bobby Pennies",
7 Object.freeze({ name: "Bobby Pennies", sex: "male" }),
7 "Ada Ledger",
8 Object.freeze({ name: "Ada Ledger", sex: "female" }),
8 "Clive Quill",
9 Object.freeze({ name: "Clive Quill", sex: "male" }),
9 "Marge Tally",
10 Object.freeze({ name: "Marge Tally", sex: "female" }),
10 "Nigel Coinwright",
11 Object.freeze({ name: "Nigel Coinwright", sex: "male" }),
11 "Pearl Balance",
12 Object.freeze({ name: "Pearl Balance", sex: "female" }),
12 "Otto Vault",
13 Object.freeze({ name: "Otto Vault", sex: "male" }),
13 "Iris Counter"
14 Object.freeze({ name: "Iris Counter", sex: "female" })
14]);
15]);
15
16
17export function centralExchangeStaffCount ()
18{
19 return CENTRAL_EXCHANGE_STAFF.length;
20}
21
16export function pickExchangeClerk (random = Math.random)
22export function pickExchangeClerk (random = Math.random)
17{
23{
18 const index = Math.floor(random() * CENTRAL_EXCHANGE_STAFF.length) % CENTRAL_EXCHANGE_STAFF.length;
24 const index = Math.floor(random() * CENTRAL_EXCHANGE_STAFF.length) % CENTRAL_EXCHANGE_STAFF.length;
19 return CENTRAL_EXCHANGE_STAFF[index];
25 return CENTRAL_EXCHANGE_STAFF[index].name;
26}
27
28/** Listing fee charged when placing a buy or sell order (non-refundable). */
29export const MARKET_ORDER_FEE_RATE = 0.03;
30
31/** Fee = ceil(3% of unitPrice × quantity), minimum 1 when the notional is positive. */
32export function marketOrderListingFee (unitPrice, quantity)
33{
34 const notional = Math.max(0, Math.floor(Number(unitPrice) || 0))
35 * Math.max(0, Math.floor(Number(quantity) || 0));
36 if (notional <= 0)
37 { return 0; }
38 return Math.max(1, Math.ceil(notional * MARKET_ORDER_FEE_RATE));
20}
39}
21
40
22export function exchangeSignature (clerkName)
41export function exchangeSignature (clerkName)
shared/market/funds.js added +169 −0
@@ -0,0 +1,169 @@
1 import { ItemId, itemDefinition } from "../definitions/items.js";
2 import { cloneStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3
4 /** Filled cheque that reserves coins (usable as market payment, whole only). */
5 export function isCoinChequeStack (stack)
6 {
7 if ((stack?.itemId | 0) !== ItemId.filledCheque)
8 { return false; }
9 const instance = stack.instance;
10 return instance?.kind === "filled-cheque" && (instance.itemId | 0) === ItemId.coins;
11 }
12
13 export function coinChequeAmount (stack)
14 {
15 if (!isCoinChequeStack(stack))
16 { return 0; }
17 return Math.max(0, stack.instance.quantity | 0);
18 }
19
20 /**
21 * Pay `amount` using coin stacks (partial OK) then whole coin-cheques only.
22 * Cheques are never partially spent: if a cheque exceeds the remaining debt,
23 * the surplus is returned as `change` (caller adds coins back).
24 * Taken cheque stacks are listed in `redeemedCheques` so the server can release
25 * vault reservations.
26 */
27 export function takeMarketFunds (slots, amount)
28 {
29 let remaining = stackQuantity(amount);
30 const redeemedCheques = [];
31 if (!remaining)
32 {
33 return {
34 ok: true,
35 slots: (slots ?? []).map(cloneStack),
36 change: 0,
37 redeemedCheques
38 };
39 }
40
41 let next = (slots ?? []).map(cloneStack);
42 let change = 0;
43
44 for (let i = 0; i < next.length && remaining > 0; i++)
45 {
46 if (!next[i] || next[i].itemId !== ItemId.coins)
47 { continue; }
48 const taken = takeFromSlot(next, i, remaining);
49 if (!taken.ok)
50 { continue; }
51 next = taken.slots;
52 remaining -= stackQuantity(taken.taken?.quantity);
53 }
54
55 while (remaining > 0)
56 {
57 let fitIndex = -1;
58 let fitAmount = 0;
59 let coverIndex = -1;
60 let coverAmount = 0;
61 for (let i = 0; i < next.length; i++)
62 {
63 const face = coinChequeAmount(next[i]);
64 if (face <= 0)
65 { continue; }
66 if (face <= remaining && face > fitAmount)
67 {
68 fitIndex = i;
69 fitAmount = face;
70 }
71 if (face >= remaining && (coverIndex < 0 || face < coverAmount))
72 {
73 coverIndex = i;
74 coverAmount = face;
75 }
76 }
77 const useIndex = fitIndex >= 0 ? fitIndex : coverIndex;
78 const useAmount = fitIndex >= 0 ? fitAmount : coverAmount;
79 if (useIndex < 0)
80 {
81 return {
82 ok: false,
83 slots: (slots ?? []).map(cloneStack),
84 change: 0,
85 redeemedCheques: []
86 };
87 }
88 const taken = takeFromSlot(next, useIndex, 1);
89 if (!taken.ok || !taken.taken)
90 {
91 return {
92 ok: false,
93 slots: (slots ?? []).map(cloneStack),
94 change: 0,
95 redeemedCheques: []
96 };
97 }
98 next = taken.slots;
99 redeemedCheques.push(cloneStack(taken.taken));
100 if (useAmount >= remaining)
101 {
102 change += useAmount - remaining;
103 remaining = 0;
104 }
105 else
106 { remaining -= useAmount; }
107 }
108
109 return { ok: true, slots: next, change, redeemedCheques };
110 }
111
112 export function countMarketFunds (slots)
113 {
114 let total = 0;
115 for (const slot of slots ?? [])
116 {
117 if (!slot)
118 { continue; }
119 if (slot.itemId === ItemId.coins)
120 { total += stackQuantity(slot.quantity); }
121 else
122 { total += coinChequeAmount(slot); }
123 }
124 return total;
125 }
126
127 /** Resolve what a market sell order lists from a bag slot. */
128 export function resolveMarketSellListing (stack)
129 {
130 if (!stack?.itemId)
131 { return null; }
132 if ((stack.itemId | 0) === ItemId.coins)
133 { return null; }
134 if ((stack.itemId | 0) === ItemId.filledCheque)
135 {
136 const instance = stack.instance;
137 if (instance?.kind !== "filled-cheque")
138 { return null; }
139 const goodsItemId = instance.itemId | 0;
140 const goodsQuantity = Math.max(1, instance.quantity | 0);
141 if (!goodsItemId || !itemDefinition(goodsItemId) || goodsItemId === ItemId.coins)
142 { return null; }
143 return {
144 isCheque: true,
145 itemId: goodsItemId,
146 quantity: goodsQuantity,
147 quantityLocked: true,
148 displayName: itemDefinition(goodsItemId)?.displayName ?? "item",
149 escrowStack: cloneStack(stack)
150 };
151 }
152 const def = itemDefinition(stack.itemId);
153 if (!def || def.marketplaceSellable === false)
154 { return null; }
155 return {
156 isCheque: false,
157 itemId: stack.itemId | 0,
158 quantity: Math.max(1, stack.quantity | 0),
159 quantityLocked: false,
160 displayName: def.displayName,
161 escrowStack: null
162 };
163 }
164
165 export function isFilledChequeEscrow (stack)
166 {
167 return (stack?.itemId | 0) === ItemId.filledCheque
168 && stack?.instance?.kind === "filled-cheque";
169 }
@@ -0,0 +1,169 @@
1import { ItemId, itemDefinition } from "../definitions/items.js";
2import { cloneStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3
4/** Filled cheque that reserves coins (usable as market payment, whole only). */
5export function isCoinChequeStack (stack)
6{
7 if ((stack?.itemId | 0) !== ItemId.filledCheque)
8 { return false; }
9 const instance = stack.instance;
10 return instance?.kind === "filled-cheque" && (instance.itemId | 0) === ItemId.coins;
11}
12
13export function coinChequeAmount (stack)
14{
15 if (!isCoinChequeStack(stack))
16 { return 0; }
17 return Math.max(0, stack.instance.quantity | 0);
18}
19
20/**
21 * Pay `amount` using coin stacks (partial OK) then whole coin-cheques only.
22 * Cheques are never partially spent: if a cheque exceeds the remaining debt,
23 * the surplus is returned as `change` (caller adds coins back).
24 * Taken cheque stacks are listed in `redeemedCheques` so the server can release
25 * vault reservations.
26 */
27export function takeMarketFunds (slots, amount)
28{
29 let remaining = stackQuantity(amount);
30 const redeemedCheques = [];
31 if (!remaining)
32 {
33 return {
34 ok: true,
35 slots: (slots ?? []).map(cloneStack),
36 change: 0,
37 redeemedCheques
38 };
39 }
40
41 let next = (slots ?? []).map(cloneStack);
42 let change = 0;
43
44 for (let i = 0; i < next.length && remaining > 0; i++)
45 {
46 if (!next[i] || next[i].itemId !== ItemId.coins)
47 { continue; }
48 const taken = takeFromSlot(next, i, remaining);
49 if (!taken.ok)
50 { continue; }
51 next = taken.slots;
52 remaining -= stackQuantity(taken.taken?.quantity);
53 }
54
55 while (remaining > 0)
56 {
57 let fitIndex = -1;
58 let fitAmount = 0;
59 let coverIndex = -1;
60 let coverAmount = 0;
61 for (let i = 0; i < next.length; i++)
62 {
63 const face = coinChequeAmount(next[i]);
64 if (face <= 0)
65 { continue; }
66 if (face <= remaining && face > fitAmount)
67 {
68 fitIndex = i;
69 fitAmount = face;
70 }
71 if (face >= remaining && (coverIndex < 0 || face < coverAmount))
72 {
73 coverIndex = i;
74 coverAmount = face;
75 }
76 }
77 const useIndex = fitIndex >= 0 ? fitIndex : coverIndex;
78 const useAmount = fitIndex >= 0 ? fitAmount : coverAmount;
79 if (useIndex < 0)
80 {
81 return {
82 ok: false,
83 slots: (slots ?? []).map(cloneStack),
84 change: 0,
85 redeemedCheques: []
86 };
87 }
88 const taken = takeFromSlot(next, useIndex, 1);
89 if (!taken.ok || !taken.taken)
90 {
91 return {
92 ok: false,
93 slots: (slots ?? []).map(cloneStack),
94 change: 0,
95 redeemedCheques: []
96 };
97 }
98 next = taken.slots;
99 redeemedCheques.push(cloneStack(taken.taken));
100 if (useAmount >= remaining)
101 {
102 change += useAmount - remaining;
103 remaining = 0;
104 }
105 else
106 { remaining -= useAmount; }
107 }
108
109 return { ok: true, slots: next, change, redeemedCheques };
110}
111
112export function countMarketFunds (slots)
113{
114 let total = 0;
115 for (const slot of slots ?? [])
116 {
117 if (!slot)
118 { continue; }
119 if (slot.itemId === ItemId.coins)
120 { total += stackQuantity(slot.quantity); }
121 else
122 { total += coinChequeAmount(slot); }
123 }
124 return total;
125}
126
127/** Resolve what a market sell order lists from a bag slot. */
128export function resolveMarketSellListing (stack)
129{
130 if (!stack?.itemId)
131 { return null; }
132 if ((stack.itemId | 0) === ItemId.coins)
133 { return null; }
134 if ((stack.itemId | 0) === ItemId.filledCheque)
135 {
136 const instance = stack.instance;
137 if (instance?.kind !== "filled-cheque")
138 { return null; }
139 const goodsItemId = instance.itemId | 0;
140 const goodsQuantity = Math.max(1, instance.quantity | 0);
141 if (!goodsItemId || !itemDefinition(goodsItemId) || goodsItemId === ItemId.coins)
142 { return null; }
143 return {
144 isCheque: true,
145 itemId: goodsItemId,
146 quantity: goodsQuantity,
147 quantityLocked: true,
148 displayName: itemDefinition(goodsItemId)?.displayName ?? "item",
149 escrowStack: cloneStack(stack)
150 };
151 }
152 const def = itemDefinition(stack.itemId);
153 if (!def || def.marketplaceSellable === false)
154 { return null; }
155 return {
156 isCheque: false,
157 itemId: stack.itemId | 0,
158 quantity: Math.max(1, stack.quantity | 0),
159 quantityLocked: false,
160 displayName: def.displayName,
161 escrowStack: null
162 };
163}
164
165export function isFilledChequeEscrow (stack)
166{
167 return (stack?.itemId | 0) === ItemId.filledCheque
168 && stack?.instance?.kind === "filled-cheque";
169}
shared/world/neighborConnect.js added +142 −0
@@ -0,0 +1,142 @@
1 /**
2 * Generic neighbor-connect autotile masks (N/E/S/W).
3 * Stored as block/ground `state` string `"0"`…`"15"` for bakeable sprite variants.
4 * Same pattern can later apply to walls and selected grounds.
5 */
6
7 export const NeighborBit = Object.freeze({
8 n: 1,
9 e: 2,
10 s: 4,
11 w: 8
12 });
13
14 export const NEIGHBOR_CONNECT_MASK_COUNT = 16;
15
16 export function neighborConnectMask ({ n = false, e = false, s = false, w = false } = {})
17 {
18 return (n ? NeighborBit.n : 0)
19 | (e ? NeighborBit.e : 0)
20 | (s ? NeighborBit.s : 0)
21 | (w ? NeighborBit.w : 0);
22 }
23
24 export function neighborConnectStateName (mask)
25 {
26 const m = Math.max(0, Math.min(15, mask | 0));
27 return String(m);
28 }
29
30 export function parseNeighborConnectMask (state)
31 {
32 if (state == null || state === "")
33 { return 0; }
34 const n = Number(state);
35 if (!Number.isFinite(n))
36 { return 0; }
37 return Math.max(0, Math.min(15, n | 0));
38 }
39
40 export function hasNeighborBit (mask, bit)
41 {
42 return ((mask | 0) & bit) !== 0;
43 }
44
45 /** Cardinal offsets in tile space (y increases south in this project). */
46 export const NEIGHBOR_CARDINALS = Object.freeze([
47 Object.freeze({ bit: NeighborBit.n, dx: 0, dy: -1, key: "n" }),
48 Object.freeze({ bit: NeighborBit.e, dx: 1, dy: 0, key: "e" }),
49 Object.freeze({ bit: NeighborBit.s, dx: 0, dy: 1, key: "s" }),
50 Object.freeze({ bit: NeighborBit.w, dx: -1, dy: 0, key: "w" })
51 ]);
52
53 /**
54 * @param {(dx: number, dy: number) => boolean} isConnectedNeighbor
55 * true when the adjacent tile should join (same connectable type).
56 */
57 export function computeNeighborConnectMask (isConnectedNeighbor)
58 {
59 let mask = 0;
60 for (const dir of NEIGHBOR_CARDINALS)
61 {
62 if (isConnectedNeighbor(dir.dx, dir.dy))
63 { mask |= dir.bit; }
64 }
65 return mask;
66 }
67
68 export function definitionUsesNeighborConnect (def)
69 {
70 return !!def?.neighborConnect;
71 }
72
73 export function definitionUsesMaterialNeighborConnect (def)
74 {
75 return !!def?.neighborConnect && !!def?.neighborConnectByMaterial;
76 }
77
78 function clampMask (value)
79 {
80 const n = Number(value);
81 if (!Number.isFinite(n))
82 { return 0; }
83 return Math.max(0, Math.min(15, n | 0));
84 }
85
86 /**
87 * Tables (and similar) store `${material}-${mask}` e.g. `pine-3`.
88 * Plain masks (`"7"`) stay valid for counters.
89 */
90 export function parseMaterialNeighborConnectState (state, def = null)
91 {
92 const fallback = def?.defaultNeighborMaterial ?? "pine";
93 const s = String(state ?? "").trim();
94 const paired = /^([a-z][a-z0-9]*)-(\d+)$/i.exec(s);
95 if (paired)
96 {
97 return {
98 material: paired[1].toLowerCase(),
99 mask: clampMask(paired[2])
100 };
101 }
102 if (/^\d+$/.test(s))
103 {
104 return { material: fallback, mask: clampMask(s) };
105 }
106 if (/^[a-z][a-z0-9]*$/i.test(s))
107 {
108 return { material: s.toLowerCase(), mask: 0 };
109 }
110 return { material: fallback, mask: 0 };
111 }
112
113 export function composeNeighborConnectState (def, currentState, mask)
114 {
115 const m = clampMask(mask);
116 if (definitionUsesMaterialNeighborConnect(def))
117 {
118 const { material } = parseMaterialNeighborConnectState(currentState, def);
119 return `${material}-${m}`;
120 }
121 return neighborConnectStateName(m);
122 }
123
124 /** True when two blocks should join for neighbor-connect (same type; same material if required). */
125 export function neighborConnectBlocksMatch (self, neighbor, def)
126 {
127 if (!self || !neighbor || (self.typeId | 0) !== (neighbor.typeId | 0))
128 { return false; }
129 if (!definitionUsesMaterialNeighborConnect(def))
130 { return true; }
131 const a = parseMaterialNeighborConnectState(self.state, def).material;
132 const b = parseMaterialNeighborConnectState(neighbor.state, def).material;
133 return a === b;
134 }
135
136 /** Resolve the visual mask from any neighbor-connect state string. */
137 export function parseNeighborConnectMaskFromState (state, def = null)
138 {
139 if (definitionUsesMaterialNeighborConnect(def))
140 { return parseMaterialNeighborConnectState(state, def).mask; }
141 return parseNeighborConnectMask(state);
142 }
@@ -0,0 +1,142 @@
1/**
2 * Generic neighbor-connect autotile masks (N/E/S/W).
3 * Stored as block/ground `state` string `"0"`…`"15"` for bakeable sprite variants.
4 * Same pattern can later apply to walls and selected grounds.
5 */
6
7export const NeighborBit = Object.freeze({
8 n: 1,
9 e: 2,
10 s: 4,
11 w: 8
12});
13
14export const NEIGHBOR_CONNECT_MASK_COUNT = 16;
15
16export function neighborConnectMask ({ n = false, e = false, s = false, w = false } = {})
17{
18 return (n ? NeighborBit.n : 0)
19 | (e ? NeighborBit.e : 0)
20 | (s ? NeighborBit.s : 0)
21 | (w ? NeighborBit.w : 0);
22}
23
24export function neighborConnectStateName (mask)
25{
26 const m = Math.max(0, Math.min(15, mask | 0));
27 return String(m);
28}
29
30export function parseNeighborConnectMask (state)
31{
32 if (state == null || state === "")
33 { return 0; }
34 const n = Number(state);
35 if (!Number.isFinite(n))
36 { return 0; }
37 return Math.max(0, Math.min(15, n | 0));
38}
39
40export function hasNeighborBit (mask, bit)
41{
42 return ((mask | 0) & bit) !== 0;
43}
44
45/** Cardinal offsets in tile space (y increases south in this project). */
46export const NEIGHBOR_CARDINALS = Object.freeze([
47 Object.freeze({ bit: NeighborBit.n, dx: 0, dy: -1, key: "n" }),
48 Object.freeze({ bit: NeighborBit.e, dx: 1, dy: 0, key: "e" }),
49 Object.freeze({ bit: NeighborBit.s, dx: 0, dy: 1, key: "s" }),
50 Object.freeze({ bit: NeighborBit.w, dx: -1, dy: 0, key: "w" })
51]);
52
53/**
54 * @param {(dx: number, dy: number) => boolean} isConnectedNeighbor
55 * true when the adjacent tile should join (same connectable type).
56 */
57export function computeNeighborConnectMask (isConnectedNeighbor)
58{
59 let mask = 0;
60 for (const dir of NEIGHBOR_CARDINALS)
61 {
62 if (isConnectedNeighbor(dir.dx, dir.dy))
63 { mask |= dir.bit; }
64 }
65 return mask;
66}
67
68export function definitionUsesNeighborConnect (def)
69{
70 return !!def?.neighborConnect;
71}
72
73export function definitionUsesMaterialNeighborConnect (def)
74{
75 return !!def?.neighborConnect && !!def?.neighborConnectByMaterial;
76}
77
78function clampMask (value)
79{
80 const n = Number(value);
81 if (!Number.isFinite(n))
82 { return 0; }
83 return Math.max(0, Math.min(15, n | 0));
84}
85
86/**
87 * Tables (and similar) store `${material}-${mask}` e.g. `pine-3`.
88 * Plain masks (`"7"`) stay valid for counters.
89 */
90export function parseMaterialNeighborConnectState (state, def = null)
91{
92 const fallback = def?.defaultNeighborMaterial ?? "pine";
93 const s = String(state ?? "").trim();
94 const paired = /^([a-z][a-z0-9]*)-(\d+)$/i.exec(s);
95 if (paired)
96 {
97 return {
98 material: paired[1].toLowerCase(),
99 mask: clampMask(paired[2])
100 };
101 }
102 if (/^\d+$/.test(s))
103 {
104 return { material: fallback, mask: clampMask(s) };
105 }
106 if (/^[a-z][a-z0-9]*$/i.test(s))
107 {
108 return { material: s.toLowerCase(), mask: 0 };
109 }
110 return { material: fallback, mask: 0 };
111}
112
113export function composeNeighborConnectState (def, currentState, mask)
114{
115 const m = clampMask(mask);
116 if (definitionUsesMaterialNeighborConnect(def))
117 {
118 const { material } = parseMaterialNeighborConnectState(currentState, def);
119 return `${material}-${m}`;
120 }
121 return neighborConnectStateName(m);
122}
123
124/** True when two blocks should join for neighbor-connect (same type; same material if required). */
125export function neighborConnectBlocksMatch (self, neighbor, def)
126{
127 if (!self || !neighbor || (self.typeId | 0) !== (neighbor.typeId | 0))
128 { return false; }
129 if (!definitionUsesMaterialNeighborConnect(def))
130 { return true; }
131 const a = parseMaterialNeighborConnectState(self.state, def).material;
132 const b = parseMaterialNeighborConnectState(neighbor.state, def).material;
133 return a === b;
134}
135
136/** Resolve the visual mask from any neighbor-connect state string. */
137export function parseNeighborConnectMaskFromState (state, def = null)
138{
139 if (definitionUsesMaterialNeighborConnect(def))
140 { return parseMaterialNeighborConnectState(state, def).mask; }
141 return parseNeighborConnectMask(state);
142}
shared/world/season.js +6 −2
@@ -177,9 +177,13 @@ export function seasonIdFromVisualState (state)
177 177 return null;
178 178 }
179 179
180 /** States the editor may cycle/paint (excludes seasonal overlays and tree stumps). */
180 /** States the editor may cycle/paint (excludes seasonal overlays, tree stumps, and autotile masks). */
181 181 export function placeableStatesForType (catalog, layer, key)
182 182 {
183 183 return statesForType(catalog, layer, key)
184 .filter((state) => !isSeasonalOverlayVariant(state) && !isSeasonalStumpState(state));
184 .filter((state) =>
185 !isSeasonalOverlayVariant(state)
186 && !isSeasonalStumpState(state)
187 && !/^\d+$/.test(String(state))
188 );
185 189 }
@@ -177,9 +177,13 @@ export function seasonIdFromVisualState (state)
177 return null;
177 return null;
178}
178}
179
179
180/** States the editor may cycle/paint (excludes seasonal overlays and tree stumps). */
180/** States the editor may cycle/paint (excludes seasonal overlays, tree stumps, and autotile masks). */
181export function placeableStatesForType (catalog, layer, key)
181export function placeableStatesForType (catalog, layer, key)
182{
182{
183 return statesForType(catalog, layer, key)
183 return statesForType(catalog, layer, key)
184 .filter((state) => !isSeasonalOverlayVariant(state) && !isSeasonalStumpState(state));
184 .filter((state) =>
185 !isSeasonalOverlayVariant(state)
186 && !isSeasonalStumpState(state)
187 && !/^\d+$/.test(String(state))
188 );
185}
189}