BlueGit

timfa questward

Merge branch 'master' of git@gitlab.com:Timfa/questward.git

timfa Tim Falken · pushed by timfa

Authored 2026-09-14 · 2 months ago

Hash
a1b4336e9f5bdcb0b40be3e0dea3076ddab9fb3d
39 files changed +4921 −1212
client/src/editor/conditionSetEditor.js +94 −0
@@ -137,6 +137,14 @@ export function renderConditionSet (when, onChange, ctx = {})
137 137 bump(false);
138 138 }));
139 139 }
140 else if (cond.kind === ConditionKind.killMobFromSpawner)
141 {
142 row.append(killMobFromSpawnerConditionFields(cond, ctx, () =>
143 {
144 set.all[index].condition = cond;
145 bump(false);
146 }));
147 }
140 148 else if (cond.kind === ConditionKind.atTile)
141 149 {
142 150 row.append(atTileConditionFields(cond, ctx, () =>
@@ -488,6 +496,90 @@ function killCountConditionFields (cond, onChanged)
488 496 return wrap;
489 497 }
490 498
499 /** Mob + spawner combobox + count for killMobFromSpawner conditions. */
500 function killMobFromSpawnerConditionFields (cond, ctx, onChanged)
501 {
502 const wrap = document.createElement("div");
503 wrap.className = "quest-condition-pair";
504 const mobSelect = document.createElement("select");
505 for (const def of listSpawnableMobTypes())
506 {
507 const opt = document.createElement("option");
508 opt.value = def.mobTypeId;
509 opt.textContent = def.displayName ?? def.mobTypeId;
510 if (def.mobTypeId === cond.mobTypeId)
511 { opt.selected = true; }
512 mobSelect.append(opt);
513 }
514 if (cond.mobTypeId && ![...mobSelect.options].some((o) => o.value === cond.mobTypeId))
515 {
516 const missing = document.createElement("option");
517 missing.value = cond.mobTypeId;
518 missing.textContent = `${cond.mobTypeId} (missing)`;
519 missing.selected = true;
520 mobSelect.append(missing);
521 }
522 if (!cond.mobTypeId && mobSelect.options.length)
523 {
524 cond.mobTypeId = mobSelect.options[0].value;
525 mobSelect.options[0].selected = true;
526 }
527
528 const spawnerRoot = document.createElement("div");
529 spawnerRoot.style.minWidth = "10rem";
530 const combo = createDimensionCombobox({
531 root: spawnerRoot,
532 allowCreate: false,
533 allowUnknown: true,
534 placeholder: "Spawner id…",
535 emptyLabel: "No spawners for this mob",
536 onSelect (id)
537 {
538 cond.spawnerId = id || "";
539 onChanged();
540 }
541 });
542
543 function refreshSpawnerOptions ()
544 {
545 const rows = typeof ctx.getSpawnerOptions === "function"
546 ? (ctx.getSpawnerOptions(cond.mobTypeId) ?? [])
547 : [];
548 combo.setOptions(rows.map((row) => ({
549 id: row.spawnerId,
550 label: row.spawnerId,
551 hint: row.mobTypeId
552 ? `${row.mobTypeId} @ ${row.tileX},${row.tileY}`
553 : `${row.tileX},${row.tileY}`
554 })));
555 combo.setValue(cond.spawnerId || null);
556 }
557
558 const qty = document.createElement("input");
559 qty.type = "number";
560 qty.min = "1";
561 qty.step = "1";
562 qty.style.width = "5rem";
563 qty.value = String(Math.max(1, Number(cond.count) || 1));
564 qty.title = "Kill count";
565
566 mobSelect.addEventListener("change", () =>
567 {
568 cond.mobTypeId = mobSelect.value || undefined;
569 refreshSpawnerOptions();
570 onChanged();
571 });
572 qty.addEventListener("input", () =>
573 {
574 cond.count = Math.max(1, Number(qty.value) || 1);
575 onChanged();
576 });
577
578 refreshSpawnerOptions();
579 wrap.append(mobSelect, spawnerRoot, qty);
580 return wrap;
581 }
582
491 583 /** Dialogue picker + step-id dropdown from that tree. */
492 584 function dialogueHeardConditionFields (cond, dialogueList, onChanged)
493 585 {
@@ -778,6 +870,8 @@ function defaultCondition (kind)
778 870 return { kind, dialogueId: "", trigger: "" };
779 871 case ConditionKind.killCount:
780 872 return { kind, mobTypeId: "deer", count: 1 };
873 case ConditionKind.killMobFromSpawner:
874 return { kind, mobTypeId: "deer", spawnerId: "", count: 1 };
781 875 case ConditionKind.atTile:
782 876 case ConditionKind.nearTile:
783 877 return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0, ...(kind === ConditionKind.nearTile ? { range: 1 } : {}) };
@@ -137,6 +137,14 @@ export function renderConditionSet (when, onChange, ctx = {})
137 bump(false);
137 bump(false);
138 }));
138 }));
139 }
139 }
140 else if (cond.kind === ConditionKind.killMobFromSpawner)
141 {
142 row.append(killMobFromSpawnerConditionFields(cond, ctx, () =>
143 {
144 set.all[index].condition = cond;
145 bump(false);
146 }));
147 }
140 else if (cond.kind === ConditionKind.atTile)
148 else if (cond.kind === ConditionKind.atTile)
141 {
149 {
142 row.append(atTileConditionFields(cond, ctx, () =>
150 row.append(atTileConditionFields(cond, ctx, () =>
@@ -488,6 +496,90 @@ function killCountConditionFields (cond, onChanged)
488 return wrap;
496 return wrap;
489}
497}
490
498
499/** Mob + spawner combobox + count for killMobFromSpawner conditions. */
500function killMobFromSpawnerConditionFields (cond, ctx, onChanged)
501{
502 const wrap = document.createElement("div");
503 wrap.className = "quest-condition-pair";
504 const mobSelect = document.createElement("select");
505 for (const def of listSpawnableMobTypes())
506 {
507 const opt = document.createElement("option");
508 opt.value = def.mobTypeId;
509 opt.textContent = def.displayName ?? def.mobTypeId;
510 if (def.mobTypeId === cond.mobTypeId)
511 { opt.selected = true; }
512 mobSelect.append(opt);
513 }
514 if (cond.mobTypeId && ![...mobSelect.options].some((o) => o.value === cond.mobTypeId))
515 {
516 const missing = document.createElement("option");
517 missing.value = cond.mobTypeId;
518 missing.textContent = `${cond.mobTypeId} (missing)`;
519 missing.selected = true;
520 mobSelect.append(missing);
521 }
522 if (!cond.mobTypeId && mobSelect.options.length)
523 {
524 cond.mobTypeId = mobSelect.options[0].value;
525 mobSelect.options[0].selected = true;
526 }
527
528 const spawnerRoot = document.createElement("div");
529 spawnerRoot.style.minWidth = "10rem";
530 const combo = createDimensionCombobox({
531 root: spawnerRoot,
532 allowCreate: false,
533 allowUnknown: true,
534 placeholder: "Spawner id…",
535 emptyLabel: "No spawners for this mob",
536 onSelect (id)
537 {
538 cond.spawnerId = id || "";
539 onChanged();
540 }
541 });
542
543 function refreshSpawnerOptions ()
544 {
545 const rows = typeof ctx.getSpawnerOptions === "function"
546 ? (ctx.getSpawnerOptions(cond.mobTypeId) ?? [])
547 : [];
548 combo.setOptions(rows.map((row) => ({
549 id: row.spawnerId,
550 label: row.spawnerId,
551 hint: row.mobTypeId
552 ? `${row.mobTypeId} @ ${row.tileX},${row.tileY}`
553 : `${row.tileX},${row.tileY}`
554 })));
555 combo.setValue(cond.spawnerId || null);
556 }
557
558 const qty = document.createElement("input");
559 qty.type = "number";
560 qty.min = "1";
561 qty.step = "1";
562 qty.style.width = "5rem";
563 qty.value = String(Math.max(1, Number(cond.count) || 1));
564 qty.title = "Kill count";
565
566 mobSelect.addEventListener("change", () =>
567 {
568 cond.mobTypeId = mobSelect.value || undefined;
569 refreshSpawnerOptions();
570 onChanged();
571 });
572 qty.addEventListener("input", () =>
573 {
574 cond.count = Math.max(1, Number(qty.value) || 1);
575 onChanged();
576 });
577
578 refreshSpawnerOptions();
579 wrap.append(mobSelect, spawnerRoot, qty);
580 return wrap;
581}
582
491/** Dialogue picker + step-id dropdown from that tree. */
583/** Dialogue picker + step-id dropdown from that tree. */
492function dialogueHeardConditionFields (cond, dialogueList, onChanged)
584function dialogueHeardConditionFields (cond, dialogueList, onChanged)
493{
585{
@@ -778,6 +870,8 @@ function defaultCondition (kind)
778 return { kind, dialogueId: "", trigger: "" };
870 return { kind, dialogueId: "", trigger: "" };
779 case ConditionKind.killCount:
871 case ConditionKind.killCount:
780 return { kind, mobTypeId: "deer", count: 1 };
872 return { kind, mobTypeId: "deer", count: 1 };
873 case ConditionKind.killMobFromSpawner:
874 return { kind, mobTypeId: "deer", spawnerId: "", count: 1 };
781 case ConditionKind.atTile:
875 case ConditionKind.atTile:
782 case ConditionKind.nearTile:
876 case ConditionKind.nearTile:
783 return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0, ...(kind === ConditionKind.nearTile ? { range: 1 } : {}) };
877 return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0, ...(kind === ConditionKind.nearTile ? { range: 1 } : {}) };
client/src/editor/dialoguesModal.js +4 −2
@@ -15,7 +15,8 @@ export function initDialoguesModal ({
15 15 MessageType,
16 16 describeWorldTile = null,
17 17 centerEditorOnTile = null,
18 getDimensionOptions = null
18 getDimensionOptions = null,
19 getSpawnerOptions = null
19 20 })
20 21 {
21 22 const backdrop = document.getElementById("dialogues-backdrop");
@@ -70,7 +71,8 @@ export function initDialoguesModal ({
70 71 dialogues,
71 72 describeWorldTile,
72 73 centerEditorOnTile,
73 getDimensionOptions
74 getDimensionOptions,
75 getSpawnerOptions
74 76 };
75 77 }
76 78
@@ -15,7 +15,8 @@ export function initDialoguesModal ({
15 MessageType,
15 MessageType,
16 describeWorldTile = null,
16 describeWorldTile = null,
17 centerEditorOnTile = null,
17 centerEditorOnTile = null,
18 getDimensionOptions = null
18 getDimensionOptions = null,
19 getSpawnerOptions = null
19})
20})
20{
21{
21 const backdrop = document.getElementById("dialogues-backdrop");
22 const backdrop = document.getElementById("dialogues-backdrop");
@@ -70,7 +71,8 @@ export function initDialoguesModal ({
70 dialogues,
71 dialogues,
71 describeWorldTile,
72 describeWorldTile,
72 centerEditorOnTile,
73 centerEditorOnTile,
73 getDimensionOptions
74 getDimensionOptions,
75 getSpawnerOptions
74 };
76 };
75 }
77 }
76
78
client/src/editor/dimensionCombobox.js +59 −3
@@ -5,7 +5,9 @@
5 5 export function createDimensionCombobox ({
6 6 root,
7 7 allowCreate = false,
8 allowUnknown = false,
8 9 placeholder = "Dimension…",
10 emptyLabel = "No matches",
9 11 onSelect,
10 12 onCreate
11 13 })
@@ -41,6 +43,25 @@ export function createDimensionCombobox ({
41 43 let selectedId = null;
42 44 let open = false;
43 45
46 function isKnownId (id)
47 {
48 return !!id && options.some((opt) => opt.id === id);
49 }
50
51 function updateValidity ()
52 {
53 const invalid = allowUnknown && !!selectedId && !isKnownId(selectedId);
54 root.classList.toggle("dim-combo-invalid", invalid);
55 if (invalid)
56 {
57 root.classList.remove("dim-combo-invalid-pulse");
58 void root.offsetWidth;
59 root.classList.add("dim-combo-invalid-pulse");
60 }
61 else
62 { root.classList.remove("dim-combo-invalid-pulse"); }
63 }
64
44 65 function selectedOption ()
45 66 {
46 67 return options.find((opt) => opt.id === selectedId) ?? null;
@@ -147,7 +168,7 @@ export function createDimensionCombobox ({
147 168 {
148 169 const empty = document.createElement("li");
149 170 empty.className = "dim-combo-empty";
150 empty.textContent = "No dimensions";
171 empty.textContent = emptyLabel;
151 172 list.append(empty);
152 173 }
153 174 }
@@ -156,6 +177,7 @@ export function createDimensionCombobox ({
156 177 {
157 178 selectedId = id;
158 179 syncInputFromSelection();
180 updateValidity();
159 181 setOpen(false);
160 182 onSelect?.(id);
161 183 }
@@ -225,13 +247,45 @@ export function createDimensionCombobox ({
225 247 }
226 248 }
227 249 });
250 input.addEventListener("input", () =>
251 {
252 if (!allowUnknown)
253 { return; }
254 const typed = input.value.trim();
255 const exact = exactMatchId(typed);
256 selectedId = exact ?? (typed || null);
257 updateValidity();
258 onSelect?.(selectedId);
259 });
228 260 input.addEventListener("blur", () =>
229 261 {
230 262 window.setTimeout(() =>
231 263 {
232 264 if (!root.contains(document.activeElement))
233 265 {
234 syncInputFromSelection();
266 if (allowUnknown)
267 {
268 const typed = input.value.trim();
269 const exact = exactMatchId(typed);
270 if (exact)
271 { choose(exact); }
272 else if (typed)
273 {
274 selectedId = typed;
275 input.value = typed;
276 updateValidity();
277 onSelect?.(typed);
278 }
279 else
280 {
281 selectedId = null;
282 input.value = "";
283 updateValidity();
284 onSelect?.(null);
285 }
286 }
287 else
288 { syncInputFromSelection(); }
235 289 setOpen(false);
236 290 }
237 291 }, 0);
@@ -241,9 +295,10 @@ export function createDimensionCombobox ({
241 295 setOptions (nextOptions)
242 296 {
243 297 options = Array.isArray(nextOptions) ? nextOptions.slice() : [];
244 if (selectedId && !options.some((opt) => opt.id === selectedId))
298 if (selectedId && !options.some((opt) => opt.id === selectedId) && !allowUnknown)
245 299 { selectedId = options[0]?.id ?? null; }
246 300 syncInputFromSelection();
301 updateValidity();
247 302 if (open)
248 303 { renderList(); }
249 304 },
@@ -251,6 +306,7 @@ export function createDimensionCombobox ({
251 306 {
252 307 selectedId = id;
253 308 syncInputFromSelection();
309 updateValidity();
254 310 if (open)
255 311 { renderList(); }
256 312 },
@@ -5,7 +5,9 @@
5export function createDimensionCombobox ({
5export function createDimensionCombobox ({
6 root,
6 root,
7 allowCreate = false,
7 allowCreate = false,
8 allowUnknown = false,
8 placeholder = "Dimension…",
9 placeholder = "Dimension…",
10 emptyLabel = "No matches",
9 onSelect,
11 onSelect,
10 onCreate
12 onCreate
11})
13})
@@ -41,6 +43,25 @@ export function createDimensionCombobox ({
41 let selectedId = null;
43 let selectedId = null;
42 let open = false;
44 let open = false;
43
45
46 function isKnownId (id)
47 {
48 return !!id && options.some((opt) => opt.id === id);
49 }
50
51 function updateValidity ()
52 {
53 const invalid = allowUnknown && !!selectedId && !isKnownId(selectedId);
54 root.classList.toggle("dim-combo-invalid", invalid);
55 if (invalid)
56 {
57 root.classList.remove("dim-combo-invalid-pulse");
58 void root.offsetWidth;
59 root.classList.add("dim-combo-invalid-pulse");
60 }
61 else
62 { root.classList.remove("dim-combo-invalid-pulse"); }
63 }
64
44 function selectedOption ()
65 function selectedOption ()
45 {
66 {
46 return options.find((opt) => opt.id === selectedId) ?? null;
67 return options.find((opt) => opt.id === selectedId) ?? null;
@@ -147,7 +168,7 @@ export function createDimensionCombobox ({
147 {
168 {
148 const empty = document.createElement("li");
169 const empty = document.createElement("li");
149 empty.className = "dim-combo-empty";
170 empty.className = "dim-combo-empty";
150 empty.textContent = "No dimensions";
171 empty.textContent = emptyLabel;
151 list.append(empty);
172 list.append(empty);
152 }
173 }
153 }
174 }
@@ -156,6 +177,7 @@ export function createDimensionCombobox ({
156 {
177 {
157 selectedId = id;
178 selectedId = id;
158 syncInputFromSelection();
179 syncInputFromSelection();
180 updateValidity();
159 setOpen(false);
181 setOpen(false);
160 onSelect?.(id);
182 onSelect?.(id);
161 }
183 }
@@ -225,13 +247,45 @@ export function createDimensionCombobox ({
225 }
247 }
226 }
248 }
227 });
249 });
250 input.addEventListener("input", () =>
251 {
252 if (!allowUnknown)
253 { return; }
254 const typed = input.value.trim();
255 const exact = exactMatchId(typed);
256 selectedId = exact ?? (typed || null);
257 updateValidity();
258 onSelect?.(selectedId);
259 });
228 input.addEventListener("blur", () =>
260 input.addEventListener("blur", () =>
229 {
261 {
230 window.setTimeout(() =>
262 window.setTimeout(() =>
231 {
263 {
232 if (!root.contains(document.activeElement))
264 if (!root.contains(document.activeElement))
233 {
265 {
234 syncInputFromSelection();
266 if (allowUnknown)
267 {
268 const typed = input.value.trim();
269 const exact = exactMatchId(typed);
270 if (exact)
271 { choose(exact); }
272 else if (typed)
273 {
274 selectedId = typed;
275 input.value = typed;
276 updateValidity();
277 onSelect?.(typed);
278 }
279 else
280 {
281 selectedId = null;
282 input.value = "";
283 updateValidity();
284 onSelect?.(null);
285 }
286 }
287 else
288 { syncInputFromSelection(); }
235 setOpen(false);
289 setOpen(false);
236 }
290 }
237 }, 0);
291 }, 0);
@@ -241,9 +295,10 @@ export function createDimensionCombobox ({
241 setOptions (nextOptions)
295 setOptions (nextOptions)
242 {
296 {
243 options = Array.isArray(nextOptions) ? nextOptions.slice() : [];
297 options = Array.isArray(nextOptions) ? nextOptions.slice() : [];
244 if (selectedId && !options.some((opt) => opt.id === selectedId))
298 if (selectedId && !options.some((opt) => opt.id === selectedId) && !allowUnknown)
245 { selectedId = options[0]?.id ?? null; }
299 { selectedId = options[0]?.id ?? null; }
246 syncInputFromSelection();
300 syncInputFromSelection();
301 updateValidity();
247 if (open)
302 if (open)
248 { renderList(); }
303 { renderList(); }
249 },
304 },
@@ -251,6 +306,7 @@ export function createDimensionCombobox ({
251 {
306 {
252 selectedId = id;
307 selectedId = id;
253 syncInputFromSelection();
308 syncInputFromSelection();
309 updateValidity();
254 if (open)
310 if (open)
255 { renderList(); }
311 { renderList(); }
256 },
312 },
client/src/editor/main.js +60 −2
@@ -1934,6 +1934,58 @@ async function main ()
1934 1934 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1935 1935 isOverworld
1936 1936 });
1937
1938 function collectEditorSpawners ()
1939 {
1940 const byId = new Map();
1941 function add (row)
1942 {
1943 const id = String(row?.spawnerId ?? "").trim();
1944 if (!id)
1945 { return; }
1946 byId.set(id, {
1947 spawnerId: id,
1948 mobTypeId: row.mobTypeId ?? null,
1949 dimensionId: row.dimensionId ?? OVERWORLD_ID,
1950 tileX: row.tileX | 0,
1951 tileY: row.tileY | 0
1952 });
1953 }
1954 for (const row of questsModal?.getServerSpawners?.() ?? [])
1955 { add(row); }
1956 function addChunk (cx, cy, dim, spawners)
1957 {
1958 for (const entry of spawners ?? [])
1959 {
1960 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
1961 add({
1962 spawnerId: config.spawnerId,
1963 mobTypeId: config.mobTypeId,
1964 dimensionId: dim,
1965 tileX: cx * CHUNK_SIZE + (entry.localX | 0),
1966 tileY: cy * CHUNK_SIZE + (entry.localY | 0)
1967 });
1968 }
1969 }
1970 if (draft)
1971 { addChunk(chunkX, chunkY, selectedDimensionId, draft.spawners); }
1972 for (const [key, data] of dirtyNeighborChunks)
1973 {
1974 const [cx, cy] = key.split(",").map(Number);
1975 if (!Number.isFinite(cx) || !Number.isFinite(cy))
1976 { continue; }
1977 addChunk(cx, cy, selectedDimensionId, data.spawners);
1978 }
1979 for (const [key, spawners] of neighborSpawnersByChunk)
1980 {
1981 const [cx, cy] = key.split(",").map(Number);
1982 if (!Number.isFinite(cx) || !Number.isFinite(cy))
1983 { continue; }
1984 addChunk(cx, cy, selectedDimensionId, spawners);
1985 }
1986 return [...byId.values()].sort((a, b) => a.spawnerId.localeCompare(b.spawnerId));
1987 }
1988
1937 1989 questsModal = initQuestsModal({
1938 1990 socket,
1939 1991 MessageType,
@@ -1944,7 +1996,10 @@ async function main ()
1944 1996 label: dim.displayName || dim.dimensionId,
1945 1997 disabled: dim.deletedAt != null,
1946 1998 hint: dim.deletedAt != null ? "soft-deleted" : null
1947 }))
1999 })),
2000 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2001 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2002 )
1948 2003 });
1949 2004 dialoguesModal = initDialoguesModal({
1950 2005 socket,
@@ -1956,7 +2011,10 @@ async function main ()
1956 2011 label: dim.displayName || dim.dimensionId,
1957 2012 disabled: dim.deletedAt != null,
1958 2013 hint: dim.deletedAt != null ? "soft-deleted" : null
1959 }))
2014 })),
2015 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2016 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2017 )
1960 2018 });
1961 2019 giftsModal = initGiftsModal({ socket, MessageType });
1962 2020 initSidePanelTabs();
@@ -1934,6 +1934,58 @@ async function main ()
1934 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1934 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1935 isOverworld
1935 isOverworld
1936 });
1936 });
1937
1938function collectEditorSpawners ()
1939{
1940 const byId = new Map();
1941 function add (row)
1942 {
1943 const id = String(row?.spawnerId ?? "").trim();
1944 if (!id)
1945 { return; }
1946 byId.set(id, {
1947 spawnerId: id,
1948 mobTypeId: row.mobTypeId ?? null,
1949 dimensionId: row.dimensionId ?? OVERWORLD_ID,
1950 tileX: row.tileX | 0,
1951 tileY: row.tileY | 0
1952 });
1953 }
1954 for (const row of questsModal?.getServerSpawners?.() ?? [])
1955 { add(row); }
1956 function addChunk (cx, cy, dim, spawners)
1957 {
1958 for (const entry of spawners ?? [])
1959 {
1960 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
1961 add({
1962 spawnerId: config.spawnerId,
1963 mobTypeId: config.mobTypeId,
1964 dimensionId: dim,
1965 tileX: cx * CHUNK_SIZE + (entry.localX | 0),
1966 tileY: cy * CHUNK_SIZE + (entry.localY | 0)
1967 });
1968 }
1969 }
1970 if (draft)
1971 { addChunk(chunkX, chunkY, selectedDimensionId, draft.spawners); }
1972 for (const [key, data] of dirtyNeighborChunks)
1973 {
1974 const [cx, cy] = key.split(",").map(Number);
1975 if (!Number.isFinite(cx) || !Number.isFinite(cy))
1976 { continue; }
1977 addChunk(cx, cy, selectedDimensionId, data.spawners);
1978 }
1979 for (const [key, spawners] of neighborSpawnersByChunk)
1980 {
1981 const [cx, cy] = key.split(",").map(Number);
1982 if (!Number.isFinite(cx) || !Number.isFinite(cy))
1983 { continue; }
1984 addChunk(cx, cy, selectedDimensionId, spawners);
1985 }
1986 return [...byId.values()].sort((a, b) => a.spawnerId.localeCompare(b.spawnerId));
1987}
1988
1937 questsModal = initQuestsModal({
1989 questsModal = initQuestsModal({
1938 socket,
1990 socket,
1939 MessageType,
1991 MessageType,
@@ -1944,7 +1996,10 @@ async function main ()
1944 label: dim.displayName || dim.dimensionId,
1996 label: dim.displayName || dim.dimensionId,
1945 disabled: dim.deletedAt != null,
1997 disabled: dim.deletedAt != null,
1946 hint: dim.deletedAt != null ? "soft-deleted" : null
1998 hint: dim.deletedAt != null ? "soft-deleted" : null
1947 }))
1999 })),
2000 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2001 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2002 )
1948 });
2003 });
1949 dialoguesModal = initDialoguesModal({
2004 dialoguesModal = initDialoguesModal({
1950 socket,
2005 socket,
@@ -1956,7 +2011,10 @@ async function main ()
1956 label: dim.displayName || dim.dimensionId,
2011 label: dim.displayName || dim.dimensionId,
1957 disabled: dim.deletedAt != null,
2012 disabled: dim.deletedAt != null,
1958 hint: dim.deletedAt != null ? "soft-deleted" : null
2013 hint: dim.deletedAt != null ? "soft-deleted" : null
1959 }))
2014 })),
2015 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2016 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2017 )
1960 });
2018 });
1961 giftsModal = initGiftsModal({ socket, MessageType });
2019 giftsModal = initGiftsModal({ socket, MessageType });
1962 initSidePanelTabs();
2020 initSidePanelTabs();
client/src/editor/questsModal.js +12 −2
@@ -9,7 +9,8 @@ export function initQuestsModal ({
9 9 MessageType,
10 10 describeWorldTile = null,
11 11 centerEditorOnTile = null,
12 getDimensionOptions = null
12 getDimensionOptions = null,
13 getSpawnerOptions = null
13 14 })
14 15 {
15 16 const backdrop = document.getElementById("quests-backdrop");
@@ -24,6 +25,8 @@ export function initQuestsModal ({
24 25 let quests = [];
25 26 /** @type {ReturnType<typeof normalizeDialogueTree>[]} */
26 27 let dialogues = [];
28 /** @type {{ spawnerId: string, mobTypeId?: string, dimensionId?: string, tileX?: number, tileY?: number }[]} */
29 let serverSpawners = [];
27 30 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
28 31 let draft = null;
29 32 let selectedId = null;
@@ -260,7 +263,12 @@ export function initQuestsModal ({
260 263 obj.when = next;
261 264 if (remount)
262 265 { renderEditor(); }
263 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }));
266 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions, getSpawnerOptions: (mobTypeId) =>
267 {
268 if (typeof getSpawnerOptions === "function")
269 { return getSpawnerOptions(mobTypeId) ?? []; }
270 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
271 } }));
264 272 box.append(objBox);
265 273 });
266 274 editorEl.append(box);
@@ -496,6 +504,7 @@ export function initQuestsModal ({
496 504 return {
497 505 isOpen: () => open,
498 506 getQuests: () => quests,
507 getServerSpawners: () => serverSpawners.slice(),
499 508 handleMessage (message)
500 509 {
501 510 if (message.type === MessageType.editorDialogues)
@@ -508,6 +517,7 @@ export function initQuestsModal ({
508 517 if (message.type !== MessageType.editorQuests)
509 518 { return; }
510 519 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
520 serverSpawners = Array.isArray(message.spawners) ? message.spawners.slice() : [];
511 521 changelog = message.changelog ?? [];
512 522 if (draft)
513 523 {
@@ -9,7 +9,8 @@ export function initQuestsModal ({
9 MessageType,
9 MessageType,
10 describeWorldTile = null,
10 describeWorldTile = null,
11 centerEditorOnTile = null,
11 centerEditorOnTile = null,
12 getDimensionOptions = null
12 getDimensionOptions = null,
13 getSpawnerOptions = null
13})
14})
14{
15{
15 const backdrop = document.getElementById("quests-backdrop");
16 const backdrop = document.getElementById("quests-backdrop");
@@ -24,6 +25,8 @@ export function initQuestsModal ({
24 let quests = [];
25 let quests = [];
25 /** @type {ReturnType<typeof normalizeDialogueTree>[]} */
26 /** @type {ReturnType<typeof normalizeDialogueTree>[]} */
26 let dialogues = [];
27 let dialogues = [];
28 /** @type {{ spawnerId: string, mobTypeId?: string, dimensionId?: string, tileX?: number, tileY?: number }[]} */
29 let serverSpawners = [];
27 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
30 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
28 let draft = null;
31 let draft = null;
29 let selectedId = null;
32 let selectedId = null;
@@ -260,7 +263,12 @@ export function initQuestsModal ({
260 obj.when = next;
263 obj.when = next;
261 if (remount)
264 if (remount)
262 { renderEditor(); }
265 { renderEditor(); }
263 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }));
266 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions, getSpawnerOptions: (mobTypeId) =>
267 {
268 if (typeof getSpawnerOptions === "function")
269 { return getSpawnerOptions(mobTypeId) ?? []; }
270 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
271 } }));
264 box.append(objBox);
272 box.append(objBox);
265 });
273 });
266 editorEl.append(box);
274 editorEl.append(box);
@@ -496,6 +504,7 @@ export function initQuestsModal ({
496 return {
504 return {
497 isOpen: () => open,
505 isOpen: () => open,
498 getQuests: () => quests,
506 getQuests: () => quests,
507 getServerSpawners: () => serverSpawners.slice(),
499 handleMessage (message)
508 handleMessage (message)
500 {
509 {
501 if (message.type === MessageType.editorDialogues)
510 if (message.type === MessageType.editorDialogues)
@@ -508,6 +517,7 @@ export function initQuestsModal ({
508 if (message.type !== MessageType.editorQuests)
517 if (message.type !== MessageType.editorQuests)
509 { return; }
518 { return; }
510 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
519 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
520 serverSpawners = Array.isArray(message.spawners) ? message.spawners.slice() : [];
511 changelog = message.changelog ?? [];
521 changelog = message.changelog ?? [];
512 if (draft)
522 if (draft)
513 {
523 {
client/src/editor/tileConfigModal.js +60 −12
@@ -713,6 +713,27 @@ export function initTileConfigModal ({
713 713 nameHint.className = "hint";
714 714 nameHint.textContent = `Optional. Empty uses the mob default (${placeholder}).`;
715 715 wrap.append(nameHint);
716
717 // Wildlife: Passive without Aggressive checkbox (Aggressive comes from mob def).
718 if (!isHumanoidMob(config.mobTypeId) && !isCentralExchangeSpawner(config))
719 {
720 const defAggressive = !!def?.aggressive;
721 const passiveLabel = document.createElement("label");
722 passiveLabel.className = "spawner-buys-row";
723 const passive = document.createElement("input");
724 passive.type = "checkbox";
725 passive.name = "passive";
726 passive.checked = !!config.passive && !defAggressive;
727 passive.disabled = defAggressive;
728 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
729 wrap.append(passiveLabel);
730 const passiveHint = document.createElement("p");
731 passiveHint.className = "hint";
732 passiveHint.textContent = defAggressive
733 ? "Unavailable: this mob type is Aggressive by definition."
734 : "Passive mobs take hits but never retaliate when attacked.";
735 wrap.append(passiveHint);
736 }
716 737 }
717 738
718 739 const dropsHeader = document.createElement("div");
@@ -784,14 +805,28 @@ export function initTileConfigModal ({
784 805 aggressive.type = "checkbox";
785 806 aggressive.name = "aggressive";
786 807 aggressive.checked = !!config.aggressive;
787 aggressive.addEventListener("change", () => syncBountyForAggressive());
808 aggressive.addEventListener("change", () => syncAggressivePassive());
788 809 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
789 810 wrap.append(aggressiveLabel);
790 811 const aggressiveHint = document.createElement("p");
791 812 aggressiveHint.className = "hint";
792 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
813 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0 and Passive is unavailable.";
793 814 wrap.append(aggressiveHint);
794 815
816 const passiveLabel = document.createElement("label");
817 passiveLabel.className = "spawner-buys-row";
818 const passive = document.createElement("input");
819 passive.type = "checkbox";
820 passive.name = "passive";
821 passive.checked = !!config.passive && !config.aggressive;
822 passive.disabled = !!config.aggressive;
823 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
824 wrap.append(passiveLabel);
825 const passiveHint = document.createElement("p");
826 passiveHint.className = "hint";
827 passiveHint.textContent = "Only available while Aggressive is off. Passive mobs never retaliate when attacked.";
828 wrap.append(passiveHint);
829
795 830 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
796 831
797 832 const equipHeader = document.createElement("div");
@@ -1016,20 +1051,32 @@ export function initTileConfigModal ({
1016 1051 }
1017 1052 }
1018 1053
1019 function syncBountyForAggressive ()
1054 function syncAggressivePassive ()
1020 1055 {
1021 1056 const bountyInput = form.querySelector('[name="bounty"]');
1022 1057 const aggressiveInput = form.querySelector('[name="aggressive"]');
1023 if (!bountyInput)
1024 { return; }
1058 const passiveInput = form.querySelector('[name="passive"]');
1025 1059 const aggressive = !!aggressiveInput?.checked;
1026 if (aggressive)
1060 if (bountyInput)
1061 {
1062 if (aggressive)
1063 {
1064 bountyInput.value = "0";
1065 bountyInput.disabled = true;
1066 }
1067 else
1068 { bountyInput.disabled = false; }
1069 }
1070 if (passiveInput)
1027 1071 {
1028 bountyInput.value = "0";
1029 bountyInput.disabled = true;
1072 if (aggressive)
1073 {
1074 passiveInput.checked = false;
1075 passiveInput.disabled = true;
1076 }
1077 else
1078 { passiveInput.disabled = false; }
1030 1079 }
1031 else
1032 { bountyInput.disabled = false; }
1033 1080 }
1034 1081
1035 1082 function openSpawner (ctx)
@@ -1078,7 +1125,7 @@ export function initTileConfigModal ({
1078 1125 syncCommonSpawnerSection(defaults);
1079 1126 syncHumanoidSection(defaults);
1080 1127 syncSpellsSection(defaults);
1081 syncBountyForAggressive();
1128 syncAggressivePassive();
1082 1129 });
1083 1130 spellsDraft = (config.spells ?? []).map((line) => ({
1084 1131 spellId: String(line.spellId ?? "")
@@ -1086,7 +1133,7 @@ export function initTileConfigModal ({
1086 1133 syncCommonSpawnerSection(config);
1087 1134 syncHumanoidSection(config);
1088 1135 syncSpellsSection(config);
1089 syncBountyForAggressive();
1136 syncAggressivePassive();
1090 1137 show(true);
1091 1138 }
1092 1139
@@ -1298,6 +1345,7 @@ export function initTileConfigModal ({
1298 1345 level: Number(data.get("level") || 1),
1299 1346 bounty: Number(data.get("bounty") || 0),
1300 1347 aggressive: data.get("aggressive") === "on",
1348 passive: data.get("aggressive") === "on" ? false : data.get("passive") === "on",
1301 1349 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1302 1350 sex: String(data.get("sex") || "male"),
1303 1351 displayName: String(data.get("displayName") || ""),
@@ -713,6 +713,27 @@ export function initTileConfigModal ({
713 nameHint.className = "hint";
713 nameHint.className = "hint";
714 nameHint.textContent = `Optional. Empty uses the mob default (${placeholder}).`;
714 nameHint.textContent = `Optional. Empty uses the mob default (${placeholder}).`;
715 wrap.append(nameHint);
715 wrap.append(nameHint);
716
717 // Wildlife: Passive without Aggressive checkbox (Aggressive comes from mob def).
718 if (!isHumanoidMob(config.mobTypeId) && !isCentralExchangeSpawner(config))
719 {
720 const defAggressive = !!def?.aggressive;
721 const passiveLabel = document.createElement("label");
722 passiveLabel.className = "spawner-buys-row";
723 const passive = document.createElement("input");
724 passive.type = "checkbox";
725 passive.name = "passive";
726 passive.checked = !!config.passive && !defAggressive;
727 passive.disabled = defAggressive;
728 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
729 wrap.append(passiveLabel);
730 const passiveHint = document.createElement("p");
731 passiveHint.className = "hint";
732 passiveHint.textContent = defAggressive
733 ? "Unavailable: this mob type is Aggressive by definition."
734 : "Passive mobs take hits but never retaliate when attacked.";
735 wrap.append(passiveHint);
736 }
716 }
737 }
717
738
718 const dropsHeader = document.createElement("div");
739 const dropsHeader = document.createElement("div");
@@ -784,14 +805,28 @@ export function initTileConfigModal ({
784 aggressive.type = "checkbox";
805 aggressive.type = "checkbox";
785 aggressive.name = "aggressive";
806 aggressive.name = "aggressive";
786 aggressive.checked = !!config.aggressive;
807 aggressive.checked = !!config.aggressive;
787 aggressive.addEventListener("change", () => syncBountyForAggressive());
808 aggressive.addEventListener("change", () => syncAggressivePassive());
788 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
809 aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)"));
789 wrap.append(aggressiveLabel);
810 wrap.append(aggressiveLabel);
790 const aggressiveHint = document.createElement("p");
811 const aggressiveHint = document.createElement("p");
791 aggressiveHint.className = "hint";
812 aggressiveHint.className = "hint";
792 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
813 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0 and Passive is unavailable.";
793 wrap.append(aggressiveHint);
814 wrap.append(aggressiveHint);
794
815
816 const passiveLabel = document.createElement("label");
817 passiveLabel.className = "spawner-buys-row";
818 const passive = document.createElement("input");
819 passive.type = "checkbox";
820 passive.name = "passive";
821 passive.checked = !!config.passive && !config.aggressive;
822 passive.disabled = !!config.aggressive;
823 passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)"));
824 wrap.append(passiveLabel);
825 const passiveHint = document.createElement("p");
826 passiveHint.className = "hint";
827 passiveHint.textContent = "Only available while Aggressive is off. Passive mobs never retaliate when attacked.";
828 wrap.append(passiveHint);
829
795 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
830 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
796
831
797 const equipHeader = document.createElement("div");
832 const equipHeader = document.createElement("div");
@@ -1016,20 +1051,32 @@ export function initTileConfigModal ({
1016 }
1051 }
1017 }
1052 }
1018
1053
1019 function syncBountyForAggressive ()
1054 function syncAggressivePassive ()
1020 {
1055 {
1021 const bountyInput = form.querySelector('[name="bounty"]');
1056 const bountyInput = form.querySelector('[name="bounty"]');
1022 const aggressiveInput = form.querySelector('[name="aggressive"]');
1057 const aggressiveInput = form.querySelector('[name="aggressive"]');
1023 if (!bountyInput)
1058 const passiveInput = form.querySelector('[name="passive"]');
1024 { return; }
1025 const aggressive = !!aggressiveInput?.checked;
1059 const aggressive = !!aggressiveInput?.checked;
1026 if (aggressive)
1060 if (bountyInput)
1061 {
1062 if (aggressive)
1063 {
1064 bountyInput.value = "0";
1065 bountyInput.disabled = true;
1066 }
1067 else
1068 { bountyInput.disabled = false; }
1069 }
1070 if (passiveInput)
1027 {
1071 {
1028 bountyInput.value = "0";
1072 if (aggressive)
1029 bountyInput.disabled = true;
1073 {
1074 passiveInput.checked = false;
1075 passiveInput.disabled = true;
1076 }
1077 else
1078 { passiveInput.disabled = false; }
1030 }
1079 }
1031 else
1032 { bountyInput.disabled = false; }
1033 }
1080 }
1034
1081
1035 function openSpawner (ctx)
1082 function openSpawner (ctx)
@@ -1078,7 +1125,7 @@ export function initTileConfigModal ({
1078 syncCommonSpawnerSection(defaults);
1125 syncCommonSpawnerSection(defaults);
1079 syncHumanoidSection(defaults);
1126 syncHumanoidSection(defaults);
1080 syncSpellsSection(defaults);
1127 syncSpellsSection(defaults);
1081 syncBountyForAggressive();
1128 syncAggressivePassive();
1082 });
1129 });
1083 spellsDraft = (config.spells ?? []).map((line) => ({
1130 spellsDraft = (config.spells ?? []).map((line) => ({
1084 spellId: String(line.spellId ?? "")
1131 spellId: String(line.spellId ?? "")
@@ -1086,7 +1133,7 @@ export function initTileConfigModal ({
1086 syncCommonSpawnerSection(config);
1133 syncCommonSpawnerSection(config);
1087 syncHumanoidSection(config);
1134 syncHumanoidSection(config);
1088 syncSpellsSection(config);
1135 syncSpellsSection(config);
1089 syncBountyForAggressive();
1136 syncAggressivePassive();
1090 show(true);
1137 show(true);
1091 }
1138 }
1092
1139
@@ -1298,6 +1345,7 @@ export function initTileConfigModal ({
1298 level: Number(data.get("level") || 1),
1345 level: Number(data.get("level") || 1),
1299 bounty: Number(data.get("bounty") || 0),
1346 bounty: Number(data.get("bounty") || 0),
1300 aggressive: data.get("aggressive") === "on",
1347 aggressive: data.get("aggressive") === "on",
1348 passive: data.get("aggressive") === "on" ? false : data.get("passive") === "on",
1301 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1349 spawnerId: String(data.get("spawnerId") || context.config.spawnerId),
1302 sex: String(data.get("sex") || "male"),
1350 sex: String(data.get("sex") || "male"),
1303 displayName: String(data.get("displayName") || ""),
1351 displayName: String(data.get("displayName") || ""),
client/src/play/main.js +1 −0
@@ -1789,6 +1789,7 @@ function startPlay (payload)
1789 1789 if (!view)
1790 1790 {
1791 1791 view = new WorldView(game, scene, catalog);
1792 view.worldBorderWalkableOnly = true;
1792 1793 graphicsSettingsUi?.apply();
1793 1794 const ticker = new GameObject(0, 0, null, 10);
1794 1795 ticker.update = (dt) =>
@@ -1789,6 +1789,7 @@ function startPlay (payload)
1789 if (!view)
1789 if (!view)
1790 {
1790 {
1791 view = new WorldView(game, scene, catalog);
1791 view = new WorldView(game, scene, catalog);
1792 view.worldBorderWalkableOnly = true;
1792 graphicsSettingsUi?.apply();
1793 graphicsSettingsUi?.apply();
1793 const ticker = new GameObject(0, 0, null, 10);
1794 const ticker = new GameObject(0, 0, null, 10);
1794 ticker.update = (dt) =>
1795 ticker.update = (dt) =>
client/src/render/fluidAtlasChunkShaders.js added +513 −0
@@ -0,0 +1,513 @@
1 /**
2 * Chunk-wide fluid atlas fragment shaders (single-pass bake).
3 * Derive localTile + puv from atlas v_texCoord; sample 16×16 pack textures.
4 */
5
6 const FBM_COMMON = [
7 "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
8 "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
9 "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }",
10 "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }",
11 "float snoise(vec3 v) {",
12 " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);",
13 " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);",
14 " vec3 i = floor(v + dot(v, C.yyy));",
15 " vec3 x0 = v - i + dot(i, C.xxx);",
16 " vec3 g = step(x0.yzx, x0.xyz);",
17 " vec3 l = 1.0 - g;",
18 " vec3 i1 = min(g.xyz, l.zxy);",
19 " vec3 i2 = max(g.xyz, l.zxy);",
20 " vec3 x1 = x0 - i1 + C.xxx;",
21 " vec3 x2 = x0 - i2 + C.yyy;",
22 " vec3 x3 = x0 - D.yyy;",
23 " i = mod289(i);",
24 " vec4 p = permute(permute(permute(",
25 " i.z + vec4(0.0, i1.z, i2.z, 1.0))",
26 " + i.y + vec4(0.0, i1.y, i2.y, 1.0))",
27 " + i.x + vec4(0.0, i1.x, i2.x, 1.0));",
28 " float n_ = 0.142857142857;",
29 " vec3 ns = n_ * D.wyz - D.xzx;",
30 " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);",
31 " vec4 x_ = floor(j * ns.z);",
32 " vec4 y_ = floor(j - 7.0 * x_);",
33 " vec4 x = x_ * ns.x + ns.yyyy;",
34 " vec4 y = y_ * ns.x + ns.yyyy;",
35 " vec4 h = 1.0 - abs(x) - abs(y);",
36 " vec4 b0 = vec4(x.xy, y.xy);",
37 " vec4 b1 = vec4(x.zw, y.zw);",
38 " vec4 s0 = floor(b0) * 2.0 + 1.0;",
39 " vec4 s1 = floor(b1) * 2.0 + 1.0;",
40 " vec4 sh = -step(h, vec4(0.0));",
41 " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;",
42 " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;",
43 " vec3 p0 = vec3(a0.xy, h.x);",
44 " vec3 p1 = vec3(a0.zw, h.y);",
45 " vec3 p2 = vec3(a1.xy, h.z);",
46 " vec3 p3 = vec3(a1.zw, h.w);",
47 " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));",
48 " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;",
49 " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);",
50 " m = m * m;",
51 " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));",
52 "}",
53 "float fbm(vec3 p) {",
54 " float sum = 0.0;",
55 " float amp = 0.5;",
56 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
57 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
58 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
59 " sum += amp * snoise(p);",
60 " return sum;",
61 "}",
62 "vec2 wrapUv(vec2 uv) {",
63 " return fract(uv) * 0.998 + 0.001;",
64 "}",
65 "float bit4(float packedByte, float bitIndex) {",
66 " float div = floor(packedByte / pow(2.0, bitIndex));",
67 " return step(0.5, mod(div, 2.0));",
68 "}"
69 ].join("\n");
70
71 const ATLAS_TILE_SETUP = [
72 " vec2 atlasPx = floor(v_texCoord * u_atlasPx);",
73 " vec2 localTile = floor(atlasPx / u_tilePx);",
74 " vec2 puv = (mod(atlasPx, u_tilePx) + 0.5) / u_tilePx;",
75 " vec2 packUV = (localTile + 0.5) / u_tilePx;",
76 " vec4 mask = texture2D(u_tileMask, packUV);",
77 " float kind = floor(mask.r * 255.0 + 0.5);",
78 " if (kind < 0.5 || abs(kind - u_kindFilter) > 0.5) { discard; }",
79 " float edgeBits = floor(mask.g * 255.0 + 0.5);",
80 " float diagBits = floor(mask.b * 255.0 + 0.5);",
81 " float shoreCardBits = floor(mask.a * 255.0 + 0.5);",
82 " float u_edgeN = bit4(edgeBits, 0.0);",
83 " float u_edgeE = bit4(edgeBits, 1.0);",
84 " float u_edgeS = bit4(edgeBits, 2.0);",
85 " float u_edgeW = bit4(edgeBits, 3.0);",
86 " float u_edgeNE = bit4(diagBits, 0.0);",
87 " float u_edgeNW = bit4(diagBits, 1.0);",
88 " float u_edgeSE = bit4(diagBits, 2.0);",
89 " float u_edgeSW = bit4(diagBits, 3.0);",
90 " vec4 shorePack = texture2D(u_tileShore, packUV);",
91 " float shoreDiagBits = floor(shorePack.r * 255.0 + 0.5);",
92 " float u_hasShore = step(0.5, shorePack.g);",
93 " float u_shoreEdgeN = bit4(shoreCardBits, 0.0);",
94 " float u_shoreEdgeE = bit4(shoreCardBits, 1.0);",
95 " float u_shoreEdgeS = bit4(shoreCardBits, 2.0);",
96 " float u_shoreEdgeW = bit4(shoreCardBits, 3.0);",
97 " float u_shoreEdgeNE = bit4(shoreDiagBits, 0.0);",
98 " float u_shoreEdgeNW = bit4(shoreDiagBits, 1.0);",
99 " float u_shoreEdgeSE = bit4(shoreDiagBits, 2.0);",
100 " float u_shoreEdgeSW = bit4(shoreDiagBits, 3.0);",
101 " vec4 litPack = texture2D(u_tileLit, packUV);",
102 " float u_litNW = litPack.r;",
103 " float u_litNE = litPack.g;",
104 " float u_litSW = litPack.b;",
105 " float u_litSE = litPack.a;",
106 " vec4 deepPack = texture2D(u_tileDeep, packUV);",
107 " float u_deepNW = deepPack.r;",
108 " float u_deepNE = deepPack.g;",
109 " float u_deepSW = deepPack.b;",
110 " float u_deepSE = deepPack.a;",
111 " vec4 shoreUv = texture2D(u_tileShoreUv, packUV);",
112 " vec2 world = u_chunkOrigin + localTile + puv;"
113 ].join("\n");
114
115 const TUNE_UNIFORMS_WATER = [
116 "uniform float u_flowX;",
117 "uniform float u_flowY;",
118 "uniform float u_flowZ;",
119 "uniform float u_waveScale;",
120 "uniform float u_fbmAmp;",
121 "uniform float u_texAmp;",
122 "uniform float u_distort;",
123 "uniform float u_normalZ;",
124 "uniform float u_waveGain;",
125 "uniform float u_crestLo;",
126 "uniform float u_crestHi;",
127 "uniform float u_crestPow;",
128 "uniform float u_glitterPow;",
129 "uniform float u_crestGlitter;",
130 "uniform float u_glitterCap;",
131 "uniform float u_glitterMix;",
132 "uniform float u_shadeLo;",
133 "uniform float u_shadeHi;",
134 "uniform float u_bodyLo;",
135 "uniform float u_bodyHi;",
136 "uniform float u_litLo;",
137 "uniform float u_litHi;",
138 "uniform float u_litMix;",
139 "uniform float u_edgeDark;",
140 "uniform float u_lightDirX;",
141 "uniform float u_lightDirY;",
142 "uniform float u_lightDirZ;",
143 "uniform float u_normalEps;",
144 "uniform float u_foamStrength;",
145 "uniform float u_shoreClip;",
146 "uniform float u_deepDark;",
147 "uniform float u_deepAbrupt;"
148 ].join("\n");
149
150 const TUNE_UNIFORMS_LAVA = [
151 "uniform float u_flowX;",
152 "uniform float u_flowY;",
153 "uniform float u_flowZ;",
154 "uniform float u_waveScale;",
155 "uniform float u_fbmAmp;",
156 "uniform float u_texAmp;",
157 "uniform float u_distort;",
158 "uniform float u_normalZ;",
159 "uniform float u_waveGain;",
160 "uniform float u_crestLo;",
161 "uniform float u_crestHi;",
162 "uniform float u_crestPow;",
163 "uniform float u_glitterPow;",
164 "uniform float u_crestGlitter;",
165 "uniform float u_glitterCap;",
166 "uniform float u_glitterMix;",
167 "uniform float u_shadeLo;",
168 "uniform float u_shadeHi;",
169 "uniform float u_bodyLo;",
170 "uniform float u_bodyHi;",
171 "uniform float u_litLo;",
172 "uniform float u_litHi;",
173 "uniform float u_litMix;",
174 "uniform float u_edgeDark;",
175 "uniform float u_lightDirX;",
176 "uniform float u_lightDirY;",
177 "uniform float u_lightDirZ;",
178 "uniform float u_normalEps;",
179 "uniform float u_shoreClip;"
180 ].join("\n");
181
182 const PACK_UNIFORMS = [
183 "uniform sampler2D u_tileMask;",
184 "uniform sampler2D u_tileShore;",
185 "uniform sampler2D u_tileLit;",
186 "uniform sampler2D u_tileDeep;",
187 "uniform sampler2D u_tileShoreUv;",
188 "uniform vec2 u_chunkOrigin;",
189 "uniform float u_atlasPx;",
190 "uniform float u_tilePx;",
191 "uniform float u_kindFilter;",
192 "uniform float u_time;",
193 "uniform float u_ambientDark;"
194 ].join("\n");
195
196 export const WATER_ATLAS_CHUNK_FRAG = [
197 "precision mediump float;",
198 "varying vec2 v_texCoord;",
199 "uniform sampler2D u_texture;",
200 "uniform sampler2D u_secondary;",
201 "uniform float u_alpha;",
202 PACK_UNIFORMS,
203 TUNE_UNIFORMS_WATER,
204 FBM_COMMON,
205 "float sampleShore(",
206 " float enabled, float useShore, float hasShore, vec2 shoreNu, vec4 u_shoreUvRect,",
207 " inout vec3 shoreRgb, inout float shoreW",
208 ") {",
209 " if (enabled < 0.5 || useShore < 0.5 || hasShore < 0.5) { return 0.0; }",
210 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
211 " vec4 shore = texture2D(u_secondary, shoreUv);",
212 " if (shore.a <= 0.1) { return 0.0; }",
213 " shoreRgb = shore.rgb;",
214 " shoreW = 1.0;",
215 " return 1.0;",
216 "}",
217 "void main() {",
218 ATLAS_TILE_SETUP,
219 " float t = u_time;",
220 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
221 " float eps = max(u_normalEps, 0.001);",
222 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
223 " float nC = fbm(base);",
224 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
225 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
226 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
227 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
228 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
229 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
230 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
231 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
232 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
233 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
234 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
235 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
236 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
237 " float edgeProx = 0.0;",
238 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
239 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
240 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
241 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
242 " if (u_edgeNE > 0.5) {",
243 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
244 " }",
245 " if (u_edgeNW > 0.5) {",
246 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
247 " }",
248 " if (u_edgeSE > 0.5) {",
249 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
250 " }",
251 " if (u_edgeSW > 0.5) {",
252 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
253 " }",
254 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
255 " float deepTop = mix(u_deepNW, u_deepNE, puv.x);",
256 " float deepBot = mix(u_deepSW, u_deepSE, puv.x);",
257 " float deepMix = mix(deepTop, deepBot, puv.y);",
258 " float deepAmt = pow(clamp(deepMix, 0.0, 1.0), max(u_deepAbrupt, 0.05));",
259 " float darkW = clamp(u_deepDark, 0.0, 1.0);",
260 " vec3 deepCol = mix(vec3(0.12, 0.34, 0.54), mix(vec3(0.05, 0.16, 0.34), vec3(0.015, 0.055, 0.14), darkW), deepAmt);",
261 " vec3 midCol = mix(vec3(0.24, 0.52, 0.70), mix(vec3(0.10, 0.30, 0.50), vec3(0.04, 0.14, 0.28), darkW), deepAmt);",
262 " vec3 litCol = mix(vec3(0.52, 0.78, 0.90), mix(vec3(0.26, 0.46, 0.66), vec3(0.12, 0.28, 0.46), darkW), deepAmt);",
263 " vec3 sparkCol = mix(vec3(0.98, 1.0, 1.0), mix(vec3(0.72, 0.88, 0.98), vec3(0.48, 0.68, 0.86), darkW), deepAmt);",
264 " vec3 foamCol = vec3(0.94, 0.99, 1.0);",
265 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
266 " vec3 rgb = mix(deepCol, midCol, smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody));",
267 " rgb = mix(rgb, litCol, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix);",
268 " rgb *= shade;",
269 " rgb = mix(rgb, sparkCol, min(glitter, u_glitterCap) * u_glitterMix * (1.0 - edgeProx * 0.7));",
270 " rgb = mix(rgb, deepCol, edgeProx * u_edgeDark);",
271 " float shoreW = 0.0;",
272 " vec3 shoreRgb = rgb;",
273 " if (u_edgeN > 0.5) {",
274 " sampleShore(1.0, u_shoreEdgeN, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
275 " }",
276 " if (u_edgeS > 0.5) {",
277 " sampleShore(1.0, u_shoreEdgeS, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
278 " }",
279 " if (u_edgeW > 0.5) {",
280 " sampleShore(1.0, u_shoreEdgeW, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
281 " }",
282 " if (u_edgeE > 0.5) {",
283 " sampleShore(1.0, u_shoreEdgeE, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
284 " }",
285 " if (u_edgeNE > 0.5) {",
286 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
287 " }",
288 " if (u_edgeNW > 0.5) {",
289 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), u_hasShore, vec2(puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
290 " }",
291 " if (u_edgeSE > 0.5) {",
292 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
293 " }",
294 " if (u_edgeSW > 0.5) {",
295 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
296 " }",
297 " float darkAmt = 1.0 - smoothstep(0.18, 0.52, waveBody);",
298 " float retreat = edgeProx * (0.35 + 0.65 * darkAmt);",
299 " float shoreClip = u_shoreClip;",
300 " float shoreMask = step(shoreClip, retreat) * shoreW;",
301 " float foamAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.24, shoreClip - 0.08, retreat)",
302 " * (1.0 - smoothstep(shoreClip - 0.08, shoreClip, retreat));",
303 " rgb = mix(rgb, foamCol, foamAmt * u_foamStrength);",
304 " rgb = mix(rgb, shoreRgb, shoreMask);",
305 " float litTop = mix(u_litNW, u_litNE, puv.x);",
306 " float litBottom = mix(u_litSW, u_litSE, puv.x);",
307 " float lit = mix(litTop, litBottom, puv.y);",
308 " float darkness = u_ambientDark * (1.0 - lit);",
309 " rgb = mix(rgb, vec3(0.0), darkness);",
310 " gl_FragColor = vec4(rgb, u_alpha);",
311 "}"
312 ].join("\n");
313
314 export const LAVA_ATLAS_CHUNK_FRAG = [
315 "precision mediump float;",
316 "varying vec2 v_texCoord;",
317 "uniform sampler2D u_texture;",
318 "uniform sampler2D u_secondary;",
319 "uniform float u_alpha;",
320 PACK_UNIFORMS,
321 TUNE_UNIFORMS_LAVA,
322 FBM_COMMON,
323 "float sampleShore(",
324 " float enabled, float useShore, float hasShore, vec2 shoreNu, vec4 u_shoreUvRect,",
325 " inout vec3 shoreRgb, inout float shoreW",
326 ") {",
327 " if (enabled < 0.5 || useShore < 0.5 || hasShore < 0.5) { return 0.0; }",
328 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
329 " vec4 shore = texture2D(u_secondary, shoreUv);",
330 " if (shore.a <= 0.1) { return 0.0; }",
331 " shoreRgb = shore.rgb;",
332 " shoreW = 1.0;",
333 " return 1.0;",
334 "}",
335 "void main() {",
336 ATLAS_TILE_SETUP,
337 " float t = u_time;",
338 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
339 " float eps = max(u_normalEps, 0.001);",
340 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
341 " float nC = fbm(base);",
342 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
343 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
344 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
345 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
346 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
347 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
348 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
349 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
350 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
351 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
352 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
353 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
354 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
355 " float edgeProx = 0.0;",
356 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
357 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
358 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
359 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
360 " if (u_edgeNE > 0.5) {",
361 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
362 " }",
363 " if (u_edgeNW > 0.5) {",
364 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
365 " }",
366 " if (u_edgeSE > 0.5) {",
367 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
368 " }",
369 " if (u_edgeSW > 0.5) {",
370 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
371 " }",
372 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
373 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
374 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
375 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
376 " vec3 darkRed = vec3(0.16, 0.015, 0.01);",
377 " vec3 brightRed = vec3(0.78, 0.08, 0.02);",
378 " vec3 orange = vec3(0.98, 0.38, 0.04);",
379 " vec3 yellow = vec3(1.0, 0.9, 0.28);",
380 " vec3 rgb = mix(darkRed, brightRed, smoothstep(0.0, 0.38, heat));",
381 " rgb = mix(rgb, orange, smoothstep(0.28, 0.68, heat));",
382 " float yellowAmt = smoothstep(0.55, 0.98, heat);",
383 " rgb = mix(rgb, yellow, yellowAmt);",
384 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
385 " rgb *= shade;",
386 " rgb = mix(rgb, darkRed, edgeProx * u_edgeDark * 0.35);",
387 " float shoreW = 0.0;",
388 " vec3 shoreRgb = rgb;",
389 " if (u_edgeN > 0.5) {",
390 " sampleShore(1.0, u_shoreEdgeN, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
391 " }",
392 " if (u_edgeS > 0.5) {",
393 " sampleShore(1.0, u_shoreEdgeS, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
394 " }",
395 " if (u_edgeW > 0.5) {",
396 " sampleShore(1.0, u_shoreEdgeW, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
397 " }",
398 " if (u_edgeE > 0.5) {",
399 " sampleShore(1.0, u_shoreEdgeE, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
400 " }",
401 " if (u_edgeNE > 0.5) {",
402 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
403 " }",
404 " if (u_edgeNW > 0.5) {",
405 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), u_hasShore, vec2(puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
406 " }",
407 " if (u_edgeSE > 0.5) {",
408 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
409 " }",
410 " if (u_edgeSW > 0.5) {",
411 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
412 " }",
413 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
414 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
415 " float shoreClip = u_shoreClip;",
416 " float shoreMask = step(shoreClip, retreat) * shoreW;",
417 " float crustAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.2, shoreClip - 0.06, retreat)",
418 " * (1.0 - smoothstep(shoreClip - 0.06, shoreClip, retreat));",
419 " rgb = mix(rgb, vec3(0.05, 0.01, 0.0), crustAmt);",
420 " rgb = mix(rgb, shoreRgb, shoreMask);",
421 " float litTop = mix(u_litNW, u_litNE, puv.x);",
422 " float litBottom = mix(u_litSW, u_litSE, puv.x);",
423 " float lit = mix(litTop, litBottom, puv.y);",
424 " float darkness = u_ambientDark * (1.0 - lit);",
425 " rgb = mix(rgb, vec3(0.0), darkness);",
426 " gl_FragColor = vec4(rgb, u_alpha);",
427 "}"
428 ].join("\n");
429
430 export const LAVA_BLOOM_ATLAS_CHUNK_FRAG = [
431 "precision mediump float;",
432 "varying vec2 v_texCoord;",
433 "uniform sampler2D u_texture;",
434 "uniform float u_alpha;",
435 "uniform sampler2D u_tileMask;",
436 "uniform vec2 u_chunkOrigin;",
437 "uniform float u_atlasPx;",
438 "uniform float u_tilePx;",
439 "uniform float u_kindFilter;",
440 "uniform float u_time;",
441 TUNE_UNIFORMS_LAVA,
442 "uniform float u_bloomStrength;",
443 FBM_COMMON,
444 "void main() {",
445 " vec2 atlasPx = floor(v_texCoord * u_atlasPx);",
446 " vec2 localTile = floor(atlasPx / u_tilePx);",
447 " vec2 puv = (mod(atlasPx, u_tilePx) + 0.5) / u_tilePx;",
448 " vec2 packUV = (localTile + 0.5) / u_tilePx;",
449 " vec4 mask = texture2D(u_tileMask, packUV);",
450 " float kind = floor(mask.r * 255.0 + 0.5);",
451 " if (kind < 0.5 || abs(kind - u_kindFilter) > 0.5) { discard; }",
452 " float edgeBits = floor(mask.g * 255.0 + 0.5);",
453 " float diagBits = floor(mask.b * 255.0 + 0.5);",
454 " float u_edgeN = bit4(edgeBits, 0.0);",
455 " float u_edgeE = bit4(edgeBits, 1.0);",
456 " float u_edgeS = bit4(edgeBits, 2.0);",
457 " float u_edgeW = bit4(edgeBits, 3.0);",
458 " float u_edgeNE = bit4(diagBits, 0.0);",
459 " float u_edgeNW = bit4(diagBits, 1.0);",
460 " float u_edgeSE = bit4(diagBits, 2.0);",
461 " float u_edgeSW = bit4(diagBits, 3.0);",
462 " vec2 world = u_chunkOrigin + localTile + puv;",
463 " float t = u_time;",
464 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
465 " float eps = max(u_normalEps, 0.001);",
466 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
467 " float nC = fbm(base);",
468 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
469 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
470 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
471 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
472 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
473 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
474 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
475 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
476 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
477 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
478 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
479 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
480 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
481 " float edgeProx = 0.0;",
482 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
483 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
484 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
485 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
486 " if (u_edgeNE > 0.5) {",
487 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
488 " }",
489 " if (u_edgeNW > 0.5) {",
490 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
491 " }",
492 " if (u_edgeSE > 0.5) {",
493 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
494 " }",
495 " if (u_edgeSW > 0.5) {",
496 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
497 " }",
498 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
499 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
500 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
501 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
502 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
503 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
504 " float hasEdge = max(max(u_edgeN, u_edgeE), max(u_edgeS, u_edgeW));",
505 " hasEdge = max(hasEdge, max(max(u_edgeNE, u_edgeNW), max(u_edgeSE, u_edgeSW)));",
506 " float shoreW = step(0.5, hasEdge);",
507 " float shoreMask = step(u_shoreClip, retreat) * shoreW;",
508 " float yellowAmt = smoothstep(0.55, 0.98, heat) * (1.0 - edgeProx * 0.85) * (1.0 - shoreMask);",
509 " float bloom = yellowAmt * max(u_bloomStrength, 0.0);",
510 " vec3 glow = vec3(1.0, 0.82, 0.28) * bloom;",
511 " gl_FragColor = vec4(glow, bloom * u_alpha);",
512 "}"
513 ].join("\n");
@@ -0,0 +1,513 @@
1/**
2 * Chunk-wide fluid atlas fragment shaders (single-pass bake).
3 * Derive localTile + puv from atlas v_texCoord; sample 16×16 pack textures.
4 */
5
6const FBM_COMMON = [
7 "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
8 "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
9 "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }",
10 "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }",
11 "float snoise(vec3 v) {",
12 " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);",
13 " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);",
14 " vec3 i = floor(v + dot(v, C.yyy));",
15 " vec3 x0 = v - i + dot(i, C.xxx);",
16 " vec3 g = step(x0.yzx, x0.xyz);",
17 " vec3 l = 1.0 - g;",
18 " vec3 i1 = min(g.xyz, l.zxy);",
19 " vec3 i2 = max(g.xyz, l.zxy);",
20 " vec3 x1 = x0 - i1 + C.xxx;",
21 " vec3 x2 = x0 - i2 + C.yyy;",
22 " vec3 x3 = x0 - D.yyy;",
23 " i = mod289(i);",
24 " vec4 p = permute(permute(permute(",
25 " i.z + vec4(0.0, i1.z, i2.z, 1.0))",
26 " + i.y + vec4(0.0, i1.y, i2.y, 1.0))",
27 " + i.x + vec4(0.0, i1.x, i2.x, 1.0));",
28 " float n_ = 0.142857142857;",
29 " vec3 ns = n_ * D.wyz - D.xzx;",
30 " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);",
31 " vec4 x_ = floor(j * ns.z);",
32 " vec4 y_ = floor(j - 7.0 * x_);",
33 " vec4 x = x_ * ns.x + ns.yyyy;",
34 " vec4 y = y_ * ns.x + ns.yyyy;",
35 " vec4 h = 1.0 - abs(x) - abs(y);",
36 " vec4 b0 = vec4(x.xy, y.xy);",
37 " vec4 b1 = vec4(x.zw, y.zw);",
38 " vec4 s0 = floor(b0) * 2.0 + 1.0;",
39 " vec4 s1 = floor(b1) * 2.0 + 1.0;",
40 " vec4 sh = -step(h, vec4(0.0));",
41 " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;",
42 " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;",
43 " vec3 p0 = vec3(a0.xy, h.x);",
44 " vec3 p1 = vec3(a0.zw, h.y);",
45 " vec3 p2 = vec3(a1.xy, h.z);",
46 " vec3 p3 = vec3(a1.zw, h.w);",
47 " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));",
48 " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;",
49 " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);",
50 " m = m * m;",
51 " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));",
52 "}",
53 "float fbm(vec3 p) {",
54 " float sum = 0.0;",
55 " float amp = 0.5;",
56 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
57 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
58 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
59 " sum += amp * snoise(p);",
60 " return sum;",
61 "}",
62 "vec2 wrapUv(vec2 uv) {",
63 " return fract(uv) * 0.998 + 0.001;",
64 "}",
65 "float bit4(float packedByte, float bitIndex) {",
66 " float div = floor(packedByte / pow(2.0, bitIndex));",
67 " return step(0.5, mod(div, 2.0));",
68 "}"
69].join("\n");
70
71const ATLAS_TILE_SETUP = [
72 " vec2 atlasPx = floor(v_texCoord * u_atlasPx);",
73 " vec2 localTile = floor(atlasPx / u_tilePx);",
74 " vec2 puv = (mod(atlasPx, u_tilePx) + 0.5) / u_tilePx;",
75 " vec2 packUV = (localTile + 0.5) / u_tilePx;",
76 " vec4 mask = texture2D(u_tileMask, packUV);",
77 " float kind = floor(mask.r * 255.0 + 0.5);",
78 " if (kind < 0.5 || abs(kind - u_kindFilter) > 0.5) { discard; }",
79 " float edgeBits = floor(mask.g * 255.0 + 0.5);",
80 " float diagBits = floor(mask.b * 255.0 + 0.5);",
81 " float shoreCardBits = floor(mask.a * 255.0 + 0.5);",
82 " float u_edgeN = bit4(edgeBits, 0.0);",
83 " float u_edgeE = bit4(edgeBits, 1.0);",
84 " float u_edgeS = bit4(edgeBits, 2.0);",
85 " float u_edgeW = bit4(edgeBits, 3.0);",
86 " float u_edgeNE = bit4(diagBits, 0.0);",
87 " float u_edgeNW = bit4(diagBits, 1.0);",
88 " float u_edgeSE = bit4(diagBits, 2.0);",
89 " float u_edgeSW = bit4(diagBits, 3.0);",
90 " vec4 shorePack = texture2D(u_tileShore, packUV);",
91 " float shoreDiagBits = floor(shorePack.r * 255.0 + 0.5);",
92 " float u_hasShore = step(0.5, shorePack.g);",
93 " float u_shoreEdgeN = bit4(shoreCardBits, 0.0);",
94 " float u_shoreEdgeE = bit4(shoreCardBits, 1.0);",
95 " float u_shoreEdgeS = bit4(shoreCardBits, 2.0);",
96 " float u_shoreEdgeW = bit4(shoreCardBits, 3.0);",
97 " float u_shoreEdgeNE = bit4(shoreDiagBits, 0.0);",
98 " float u_shoreEdgeNW = bit4(shoreDiagBits, 1.0);",
99 " float u_shoreEdgeSE = bit4(shoreDiagBits, 2.0);",
100 " float u_shoreEdgeSW = bit4(shoreDiagBits, 3.0);",
101 " vec4 litPack = texture2D(u_tileLit, packUV);",
102 " float u_litNW = litPack.r;",
103 " float u_litNE = litPack.g;",
104 " float u_litSW = litPack.b;",
105 " float u_litSE = litPack.a;",
106 " vec4 deepPack = texture2D(u_tileDeep, packUV);",
107 " float u_deepNW = deepPack.r;",
108 " float u_deepNE = deepPack.g;",
109 " float u_deepSW = deepPack.b;",
110 " float u_deepSE = deepPack.a;",
111 " vec4 shoreUv = texture2D(u_tileShoreUv, packUV);",
112 " vec2 world = u_chunkOrigin + localTile + puv;"
113].join("\n");
114
115const TUNE_UNIFORMS_WATER = [
116 "uniform float u_flowX;",
117 "uniform float u_flowY;",
118 "uniform float u_flowZ;",
119 "uniform float u_waveScale;",
120 "uniform float u_fbmAmp;",
121 "uniform float u_texAmp;",
122 "uniform float u_distort;",
123 "uniform float u_normalZ;",
124 "uniform float u_waveGain;",
125 "uniform float u_crestLo;",
126 "uniform float u_crestHi;",
127 "uniform float u_crestPow;",
128 "uniform float u_glitterPow;",
129 "uniform float u_crestGlitter;",
130 "uniform float u_glitterCap;",
131 "uniform float u_glitterMix;",
132 "uniform float u_shadeLo;",
133 "uniform float u_shadeHi;",
134 "uniform float u_bodyLo;",
135 "uniform float u_bodyHi;",
136 "uniform float u_litLo;",
137 "uniform float u_litHi;",
138 "uniform float u_litMix;",
139 "uniform float u_edgeDark;",
140 "uniform float u_lightDirX;",
141 "uniform float u_lightDirY;",
142 "uniform float u_lightDirZ;",
143 "uniform float u_normalEps;",
144 "uniform float u_foamStrength;",
145 "uniform float u_shoreClip;",
146 "uniform float u_deepDark;",
147 "uniform float u_deepAbrupt;"
148].join("\n");
149
150const TUNE_UNIFORMS_LAVA = [
151 "uniform float u_flowX;",
152 "uniform float u_flowY;",
153 "uniform float u_flowZ;",
154 "uniform float u_waveScale;",
155 "uniform float u_fbmAmp;",
156 "uniform float u_texAmp;",
157 "uniform float u_distort;",
158 "uniform float u_normalZ;",
159 "uniform float u_waveGain;",
160 "uniform float u_crestLo;",
161 "uniform float u_crestHi;",
162 "uniform float u_crestPow;",
163 "uniform float u_glitterPow;",
164 "uniform float u_crestGlitter;",
165 "uniform float u_glitterCap;",
166 "uniform float u_glitterMix;",
167 "uniform float u_shadeLo;",
168 "uniform float u_shadeHi;",
169 "uniform float u_bodyLo;",
170 "uniform float u_bodyHi;",
171 "uniform float u_litLo;",
172 "uniform float u_litHi;",
173 "uniform float u_litMix;",
174 "uniform float u_edgeDark;",
175 "uniform float u_lightDirX;",
176 "uniform float u_lightDirY;",
177 "uniform float u_lightDirZ;",
178 "uniform float u_normalEps;",
179 "uniform float u_shoreClip;"
180].join("\n");
181
182const PACK_UNIFORMS = [
183 "uniform sampler2D u_tileMask;",
184 "uniform sampler2D u_tileShore;",
185 "uniform sampler2D u_tileLit;",
186 "uniform sampler2D u_tileDeep;",
187 "uniform sampler2D u_tileShoreUv;",
188 "uniform vec2 u_chunkOrigin;",
189 "uniform float u_atlasPx;",
190 "uniform float u_tilePx;",
191 "uniform float u_kindFilter;",
192 "uniform float u_time;",
193 "uniform float u_ambientDark;"
194].join("\n");
195
196export const WATER_ATLAS_CHUNK_FRAG = [
197 "precision mediump float;",
198 "varying vec2 v_texCoord;",
199 "uniform sampler2D u_texture;",
200 "uniform sampler2D u_secondary;",
201 "uniform float u_alpha;",
202 PACK_UNIFORMS,
203 TUNE_UNIFORMS_WATER,
204 FBM_COMMON,
205 "float sampleShore(",
206 " float enabled, float useShore, float hasShore, vec2 shoreNu, vec4 u_shoreUvRect,",
207 " inout vec3 shoreRgb, inout float shoreW",
208 ") {",
209 " if (enabled < 0.5 || useShore < 0.5 || hasShore < 0.5) { return 0.0; }",
210 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
211 " vec4 shore = texture2D(u_secondary, shoreUv);",
212 " if (shore.a <= 0.1) { return 0.0; }",
213 " shoreRgb = shore.rgb;",
214 " shoreW = 1.0;",
215 " return 1.0;",
216 "}",
217 "void main() {",
218 ATLAS_TILE_SETUP,
219 " float t = u_time;",
220 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
221 " float eps = max(u_normalEps, 0.001);",
222 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
223 " float nC = fbm(base);",
224 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
225 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
226 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
227 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
228 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
229 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
230 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
231 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
232 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
233 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
234 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
235 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
236 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
237 " float edgeProx = 0.0;",
238 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
239 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
240 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
241 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
242 " if (u_edgeNE > 0.5) {",
243 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
244 " }",
245 " if (u_edgeNW > 0.5) {",
246 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
247 " }",
248 " if (u_edgeSE > 0.5) {",
249 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
250 " }",
251 " if (u_edgeSW > 0.5) {",
252 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
253 " }",
254 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
255 " float deepTop = mix(u_deepNW, u_deepNE, puv.x);",
256 " float deepBot = mix(u_deepSW, u_deepSE, puv.x);",
257 " float deepMix = mix(deepTop, deepBot, puv.y);",
258 " float deepAmt = pow(clamp(deepMix, 0.0, 1.0), max(u_deepAbrupt, 0.05));",
259 " float darkW = clamp(u_deepDark, 0.0, 1.0);",
260 " vec3 deepCol = mix(vec3(0.12, 0.34, 0.54), mix(vec3(0.05, 0.16, 0.34), vec3(0.015, 0.055, 0.14), darkW), deepAmt);",
261 " vec3 midCol = mix(vec3(0.24, 0.52, 0.70), mix(vec3(0.10, 0.30, 0.50), vec3(0.04, 0.14, 0.28), darkW), deepAmt);",
262 " vec3 litCol = mix(vec3(0.52, 0.78, 0.90), mix(vec3(0.26, 0.46, 0.66), vec3(0.12, 0.28, 0.46), darkW), deepAmt);",
263 " vec3 sparkCol = mix(vec3(0.98, 1.0, 1.0), mix(vec3(0.72, 0.88, 0.98), vec3(0.48, 0.68, 0.86), darkW), deepAmt);",
264 " vec3 foamCol = vec3(0.94, 0.99, 1.0);",
265 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
266 " vec3 rgb = mix(deepCol, midCol, smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody));",
267 " rgb = mix(rgb, litCol, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix);",
268 " rgb *= shade;",
269 " rgb = mix(rgb, sparkCol, min(glitter, u_glitterCap) * u_glitterMix * (1.0 - edgeProx * 0.7));",
270 " rgb = mix(rgb, deepCol, edgeProx * u_edgeDark);",
271 " float shoreW = 0.0;",
272 " vec3 shoreRgb = rgb;",
273 " if (u_edgeN > 0.5) {",
274 " sampleShore(1.0, u_shoreEdgeN, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
275 " }",
276 " if (u_edgeS > 0.5) {",
277 " sampleShore(1.0, u_shoreEdgeS, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
278 " }",
279 " if (u_edgeW > 0.5) {",
280 " sampleShore(1.0, u_shoreEdgeW, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
281 " }",
282 " if (u_edgeE > 0.5) {",
283 " sampleShore(1.0, u_shoreEdgeE, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
284 " }",
285 " if (u_edgeNE > 0.5) {",
286 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
287 " }",
288 " if (u_edgeNW > 0.5) {",
289 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), u_hasShore, vec2(puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
290 " }",
291 " if (u_edgeSE > 0.5) {",
292 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
293 " }",
294 " if (u_edgeSW > 0.5) {",
295 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
296 " }",
297 " float darkAmt = 1.0 - smoothstep(0.18, 0.52, waveBody);",
298 " float retreat = edgeProx * (0.35 + 0.65 * darkAmt);",
299 " float shoreClip = u_shoreClip;",
300 " float shoreMask = step(shoreClip, retreat) * shoreW;",
301 " float foamAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.24, shoreClip - 0.08, retreat)",
302 " * (1.0 - smoothstep(shoreClip - 0.08, shoreClip, retreat));",
303 " rgb = mix(rgb, foamCol, foamAmt * u_foamStrength);",
304 " rgb = mix(rgb, shoreRgb, shoreMask);",
305 " float litTop = mix(u_litNW, u_litNE, puv.x);",
306 " float litBottom = mix(u_litSW, u_litSE, puv.x);",
307 " float lit = mix(litTop, litBottom, puv.y);",
308 " float darkness = u_ambientDark * (1.0 - lit);",
309 " rgb = mix(rgb, vec3(0.0), darkness);",
310 " gl_FragColor = vec4(rgb, u_alpha);",
311 "}"
312].join("\n");
313
314export const LAVA_ATLAS_CHUNK_FRAG = [
315 "precision mediump float;",
316 "varying vec2 v_texCoord;",
317 "uniform sampler2D u_texture;",
318 "uniform sampler2D u_secondary;",
319 "uniform float u_alpha;",
320 PACK_UNIFORMS,
321 TUNE_UNIFORMS_LAVA,
322 FBM_COMMON,
323 "float sampleShore(",
324 " float enabled, float useShore, float hasShore, vec2 shoreNu, vec4 u_shoreUvRect,",
325 " inout vec3 shoreRgb, inout float shoreW",
326 ") {",
327 " if (enabled < 0.5 || useShore < 0.5 || hasShore < 0.5) { return 0.0; }",
328 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
329 " vec4 shore = texture2D(u_secondary, shoreUv);",
330 " if (shore.a <= 0.1) { return 0.0; }",
331 " shoreRgb = shore.rgb;",
332 " shoreW = 1.0;",
333 " return 1.0;",
334 "}",
335 "void main() {",
336 ATLAS_TILE_SETUP,
337 " float t = u_time;",
338 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
339 " float eps = max(u_normalEps, 0.001);",
340 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
341 " float nC = fbm(base);",
342 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
343 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
344 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
345 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
346 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
347 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
348 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
349 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
350 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
351 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
352 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
353 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
354 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
355 " float edgeProx = 0.0;",
356 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
357 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
358 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
359 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
360 " if (u_edgeNE > 0.5) {",
361 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
362 " }",
363 " if (u_edgeNW > 0.5) {",
364 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
365 " }",
366 " if (u_edgeSE > 0.5) {",
367 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
368 " }",
369 " if (u_edgeSW > 0.5) {",
370 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
371 " }",
372 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
373 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
374 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
375 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
376 " vec3 darkRed = vec3(0.16, 0.015, 0.01);",
377 " vec3 brightRed = vec3(0.78, 0.08, 0.02);",
378 " vec3 orange = vec3(0.98, 0.38, 0.04);",
379 " vec3 yellow = vec3(1.0, 0.9, 0.28);",
380 " vec3 rgb = mix(darkRed, brightRed, smoothstep(0.0, 0.38, heat));",
381 " rgb = mix(rgb, orange, smoothstep(0.28, 0.68, heat));",
382 " float yellowAmt = smoothstep(0.55, 0.98, heat);",
383 " rgb = mix(rgb, yellow, yellowAmt);",
384 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
385 " rgb *= shade;",
386 " rgb = mix(rgb, darkRed, edgeProx * u_edgeDark * 0.35);",
387 " float shoreW = 0.0;",
388 " vec3 shoreRgb = rgb;",
389 " if (u_edgeN > 0.5) {",
390 " sampleShore(1.0, u_shoreEdgeN, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
391 " }",
392 " if (u_edgeS > 0.5) {",
393 " sampleShore(1.0, u_shoreEdgeS, u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
394 " }",
395 " if (u_edgeW > 0.5) {",
396 " sampleShore(1.0, u_shoreEdgeW, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
397 " }",
398 " if (u_edgeE > 0.5) {",
399 " sampleShore(1.0, u_shoreEdgeE, u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
400 " }",
401 " if (u_edgeNE > 0.5) {",
402 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
403 " }",
404 " if (u_edgeNW > 0.5) {",
405 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), u_hasShore, vec2(puv.x, puv.y), shoreUv, shoreRgb, shoreW);",
406 " }",
407 " if (u_edgeSE > 0.5) {",
408 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), u_hasShore, vec2(1.0 - puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
409 " }",
410 " if (u_edgeSW > 0.5) {",
411 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), u_hasShore, vec2(puv.x, 1.0 - puv.y), shoreUv, shoreRgb, shoreW);",
412 " }",
413 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
414 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
415 " float shoreClip = u_shoreClip;",
416 " float shoreMask = step(shoreClip, retreat) * shoreW;",
417 " float crustAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.2, shoreClip - 0.06, retreat)",
418 " * (1.0 - smoothstep(shoreClip - 0.06, shoreClip, retreat));",
419 " rgb = mix(rgb, vec3(0.05, 0.01, 0.0), crustAmt);",
420 " rgb = mix(rgb, shoreRgb, shoreMask);",
421 " float litTop = mix(u_litNW, u_litNE, puv.x);",
422 " float litBottom = mix(u_litSW, u_litSE, puv.x);",
423 " float lit = mix(litTop, litBottom, puv.y);",
424 " float darkness = u_ambientDark * (1.0 - lit);",
425 " rgb = mix(rgb, vec3(0.0), darkness);",
426 " gl_FragColor = vec4(rgb, u_alpha);",
427 "}"
428].join("\n");
429
430export const LAVA_BLOOM_ATLAS_CHUNK_FRAG = [
431 "precision mediump float;",
432 "varying vec2 v_texCoord;",
433 "uniform sampler2D u_texture;",
434 "uniform float u_alpha;",
435 "uniform sampler2D u_tileMask;",
436 "uniform vec2 u_chunkOrigin;",
437 "uniform float u_atlasPx;",
438 "uniform float u_tilePx;",
439 "uniform float u_kindFilter;",
440 "uniform float u_time;",
441 TUNE_UNIFORMS_LAVA,
442 "uniform float u_bloomStrength;",
443 FBM_COMMON,
444 "void main() {",
445 " vec2 atlasPx = floor(v_texCoord * u_atlasPx);",
446 " vec2 localTile = floor(atlasPx / u_tilePx);",
447 " vec2 puv = (mod(atlasPx, u_tilePx) + 0.5) / u_tilePx;",
448 " vec2 packUV = (localTile + 0.5) / u_tilePx;",
449 " vec4 mask = texture2D(u_tileMask, packUV);",
450 " float kind = floor(mask.r * 255.0 + 0.5);",
451 " if (kind < 0.5 || abs(kind - u_kindFilter) > 0.5) { discard; }",
452 " float edgeBits = floor(mask.g * 255.0 + 0.5);",
453 " float diagBits = floor(mask.b * 255.0 + 0.5);",
454 " float u_edgeN = bit4(edgeBits, 0.0);",
455 " float u_edgeE = bit4(edgeBits, 1.0);",
456 " float u_edgeS = bit4(edgeBits, 2.0);",
457 " float u_edgeW = bit4(edgeBits, 3.0);",
458 " float u_edgeNE = bit4(diagBits, 0.0);",
459 " float u_edgeNW = bit4(diagBits, 1.0);",
460 " float u_edgeSE = bit4(diagBits, 2.0);",
461 " float u_edgeSW = bit4(diagBits, 3.0);",
462 " vec2 world = u_chunkOrigin + localTile + puv;",
463 " float t = u_time;",
464 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
465 " float eps = max(u_normalEps, 0.001);",
466 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
467 " float nC = fbm(base);",
468 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
469 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
470 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
471 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
472 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
473 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
474 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
475 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
476 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
477 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
478 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
479 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
480 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
481 " float edgeProx = 0.0;",
482 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
483 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
484 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
485 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
486 " if (u_edgeNE > 0.5) {",
487 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
488 " }",
489 " if (u_edgeNW > 0.5) {",
490 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
491 " }",
492 " if (u_edgeSE > 0.5) {",
493 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
494 " }",
495 " if (u_edgeSW > 0.5) {",
496 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
497 " }",
498 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
499 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
500 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
501 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
502 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
503 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
504 " float hasEdge = max(max(u_edgeN, u_edgeE), max(u_edgeS, u_edgeW));",
505 " hasEdge = max(hasEdge, max(max(u_edgeNE, u_edgeNW), max(u_edgeSE, u_edgeSW)));",
506 " float shoreW = step(0.5, hasEdge);",
507 " float shoreMask = step(u_shoreClip, retreat) * shoreW;",
508 " float yellowAmt = smoothstep(0.55, 0.98, heat) * (1.0 - edgeProx * 0.85) * (1.0 - shoreMask);",
509 " float bloom = yellowAmt * max(u_bloomStrength, 0.0);",
510 " vec3 glow = vec3(1.0, 0.82, 0.28) * bloom;",
511 " gl_FragColor = vec4(glow, bloom * u_alpha);",
512 "}"
513].join("\n");
client/src/render/fluidChunkAtlas.js added +389 −0
@@ -0,0 +1,389 @@
1 /**
2 * Per-chunk fluid (water / lava) atlas: render procedural shaders at true
3 * SPRITE_SIZE_PX, then nearest-upscale the atlas to chunk world size.
4 *
5 * Tile placement is Y-down (localY), content upright (no per-tile mirrorY —
6 * that breaks world-space noise continuity / seams). FBO↔sprite V mismatch
7 * is corrected only by mirrorY on the atlas GameObject.
8 *
9 * Single-pass bake packs per-tile uniforms into 16×16 RGBA textures and draws
10 * the full atlas with one (or two, water+lava) chunk shader pass.
11 */
12
13 import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
14 import { frameworkImageFromCanvas } from "./canvasSprite.js";
15
16 export const FLUID_ATLAS_PX = CHUNK_SIZE * SPRITE_SIZE_PX;
17 export const FLUID_PACK_SIZE = CHUNK_SIZE;
18
19 /** Kind bytes stored in pack mask.R (0 = empty). */
20 export const FLUID_KIND_WATER = 1;
21 export const FLUID_KIND_LAVA = 2;
22
23 /**
24 * @param {import("../../frameworkv3/framework/engine/gl/glContext.js").default | object} glCtx
25 * @returns {{ canvas: HTMLCanvasElement, tex: WebGLTexture, fb: WebGLFramebuffer, image: object, size: number } | null}
26 */
27 export function createFluidAtlasTarget (glCtx)
28 {
29 const gl = glCtx?.gl;
30 if (!gl)
31 { return null; }
32 const size = FLUID_ATLAS_PX;
33 const canvas = document.createElement("canvas");
34 canvas.width = size;
35 canvas.height = size;
36
37 const tex = gl.createTexture();
38 gl.bindTexture(gl.TEXTURE_2D, tex);
39 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
40 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
41 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
42 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
43 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
44
45 // Seed WeakMap so Framework getTexture(canvas) returns this FBO color attachment.
46 glCtx.textures.set(canvas, tex);
47
48 const fb = gl.createFramebuffer();
49 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
50 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
51 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
52 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
53 if (status !== gl.FRAMEBUFFER_COMPLETE)
54 {
55 gl.deleteFramebuffer(fb);
56 gl.deleteTexture(tex);
57 glCtx.textures.delete(canvas);
58 return null;
59 }
60
61 return {
62 canvas,
63 tex,
64 fb,
65 image: frameworkImageFromCanvas(canvas),
66 size
67 };
68 }
69
70 export function destroyFluidAtlasTarget (glCtx, target)
71 {
72 if (!target)
73 { return; }
74 const gl = glCtx?.gl;
75 if (gl)
76 {
77 if (target.fb)
78 { gl.deleteFramebuffer(target.fb); }
79 if (target.tex)
80 { gl.deleteTexture(target.tex); }
81 }
82 if (glCtx?.textures && target.canvas)
83 { glCtx.textures.delete(target.canvas); }
84 target.fb = null;
85 target.tex = null;
86 }
87
88 /**
89 * Bind atlas FBO, clear transparent, run drawFn with drawSprite matrix sized to atlas.
90 * Restores framebuffer, viewport, and _lastWidth/_lastHeight.
91 */
92 export function withFluidAtlasPass (glCtx, target, drawFn)
93 {
94 const gl = glCtx?.gl;
95 if (!gl || !target?.fb)
96 { return; }
97 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
98 const prevViewport = gl.getParameter(gl.VIEWPORT);
99 const prevW = glCtx._lastWidth;
100 const prevH = glCtx._lastHeight;
101 const prevBlend = gl.isEnabled(gl.BLEND);
102 try
103 {
104 glCtx._lastWidth = target.size;
105 glCtx._lastHeight = target.size;
106 gl.bindFramebuffer(gl.FRAMEBUFFER, target.fb);
107 gl.viewport(0, 0, target.size, target.size);
108 // Opaque replace — blending onto clear left 1px fringes / grid seams.
109 gl.disable(gl.BLEND);
110 gl.clearColor(0, 0, 0, 0);
111 gl.clear(gl.COLOR_BUFFER_BIT);
112 drawFn();
113 }
114 finally
115 {
116 glCtx._lastWidth = prevW;
117 glCtx._lastHeight = prevH;
118 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
119 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
120 if (!prevBlend)
121 { gl.disable(gl.BLEND); }
122 else
123 { gl.enable(gl.BLEND); }
124 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
125 }
126 }
127
128 /** Pixel-space center of a chunk-local tile inside the FBO (Y-down, same as world). */
129 export function fluidAtlasTileCenter (localX, localY)
130 {
131 return {
132 x: localX * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2,
133 y: localY * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2
134 };
135 }
136
137 /**
138 * Draw one fluid tile into the currently bound atlas pass.
139 * @param {object} glCtx
140 * @param {{
141 * textureHtml: TexImageSource,
142 * secondaryHtml?: TexImageSource | null,
143 * localX: number,
144 * localY: number,
145 * shader: object,
146 * uniforms: object,
147 * uvRect?: { u0: number, v0: number, u1: number, v1: number } | null
148 * }} opts
149 */
150 export function drawFluidAtlasTile (glCtx, {
151 textureHtml,
152 secondaryHtml = null,
153 localX,
154 localY,
155 shader,
156 uniforms,
157 uvRect = null
158 })
159 {
160 if (!textureHtml || !shader)
161 { return; }
162 const center = fluidAtlasTileCenter(localX, localY);
163 const textures = secondaryHtml
164 ? { u_secondary: glCtx.getTexture(secondaryHtml) }
165 : null;
166 glCtx.drawSprite({
167 texture: glCtx.getTexture(textureHtml),
168 x: center.x,
169 y: center.y,
170 w: SPRITE_SIZE_PX,
171 h: SPRITE_SIZE_PX,
172 rotationDeg: 0,
173 mirrorX: false,
174 // Do not mirrorY per tile — inverts puv vs u_tileY and seams the FBM field.
175 mirrorY: false,
176 alpha: 1,
177 uvRect: uvRect ?? { u0: 0, v0: 0, u1: 1, v1: 1 },
178 shader,
179 uniforms,
180 textures,
181 lights: null
182 });
183 }
184
185 function createPackTexture (gl)
186 {
187 const tex = gl.createTexture();
188 gl.bindTexture(gl.TEXTURE_2D, tex);
189 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
190 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
191 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
192 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
193 gl.texImage2D(
194 gl.TEXTURE_2D, 0, gl.RGBA,
195 FLUID_PACK_SIZE, FLUID_PACK_SIZE, 0,
196 gl.RGBA, gl.UNSIGNED_BYTE, null
197 );
198 return tex;
199 }
200
201 /**
202 * CPU+GPU pack set for one chunk (5 × 16×16 RGBA8).
203 * @returns {{
204 * mask: Uint8Array, shore: Uint8Array, lit: Uint8Array, deep: Uint8Array, shoreUv: Uint8Array,
205 * texMask: WebGLTexture, texShore: WebGLTexture, texLit: WebGLTexture, texDeep: WebGLTexture, texShoreUv: WebGLTexture
206 * } | null}
207 */
208 export function createFluidPackSet (glCtx)
209 {
210 const gl = glCtx?.gl;
211 if (!gl)
212 { return null; }
213 const n = FLUID_PACK_SIZE * FLUID_PACK_SIZE * 4;
214 return {
215 mask: new Uint8Array(n),
216 shore: new Uint8Array(n),
217 lit: new Uint8Array(n),
218 deep: new Uint8Array(n),
219 shoreUv: new Uint8Array(n),
220 texMask: createPackTexture(gl),
221 texShore: createPackTexture(gl),
222 texLit: createPackTexture(gl),
223 texDeep: createPackTexture(gl),
224 texShoreUv: createPackTexture(gl)
225 };
226 }
227
228 export function destroyFluidPackSet (glCtx, packs)
229 {
230 if (!packs)
231 { return; }
232 const gl = glCtx?.gl;
233 if (gl)
234 {
235 for (const key of ["texMask", "texShore", "texLit", "texDeep", "texShoreUv"])
236 {
237 if (packs[key])
238 { gl.deleteTexture(packs[key]); }
239 packs[key] = null;
240 }
241 }
242 }
243
244 export function clearFluidPackPixels (packs)
245 {
246 if (!packs)
247 { return; }
248 packs.mask.fill(0);
249 packs.shore.fill(0);
250 packs.lit.fill(0);
251 packs.deep.fill(0);
252 packs.shoreUv.fill(0);
253 }
254
255 function packBits4 (a, b, c, d)
256 {
257 return ((a > 0.5 ? 1 : 0)
258 | ((b > 0.5 ? 1 : 0) << 1)
259 | ((c > 0.5 ? 1 : 0) << 2)
260 | ((d > 0.5 ? 1 : 0) << 3)) & 0xff;
261 }
262
263 function u8 (v)
264 {
265 return Math.max(0, Math.min(255, (v * 255 + 0.5) | 0));
266 }
267
268 /**
269 * Write one tile's uniforms into pack CPU buffers.
270 * @param {object} packs
271 * @param {number} localX
272 * @param {number} localY
273 * @param {number} kind FLUID_KIND_WATER | FLUID_KIND_LAVA
274 * @param {object} uniforms tile shaderUniforms
275 */
276 export function writeFluidPackTile (packs, localX, localY, kind, uniforms)
277 {
278 if (!packs || !uniforms)
279 { return; }
280 const lx = localX | 0;
281 const ly = localY | 0;
282 if (lx < 0 || ly < 0 || lx >= FLUID_PACK_SIZE || ly >= FLUID_PACK_SIZE)
283 { return; }
284 const i = (ly * FLUID_PACK_SIZE + lx) * 4;
285 const u = uniforms;
286
287 packs.mask[i] = kind | 0;
288 packs.mask[i + 1] = packBits4(u.u_edgeN, u.u_edgeE, u.u_edgeS, u.u_edgeW);
289 packs.mask[i + 2] = packBits4(u.u_edgeNE, u.u_edgeNW, u.u_edgeSE, u.u_edgeSW);
290 packs.mask[i + 3] = packBits4(u.u_shoreEdgeN, u.u_shoreEdgeE, u.u_shoreEdgeS, u.u_shoreEdgeW);
291
292 packs.shore[i] = packBits4(u.u_shoreEdgeNE, u.u_shoreEdgeNW, u.u_shoreEdgeSE, u.u_shoreEdgeSW);
293 packs.shore[i + 1] = (u.u_hasShore > 0.5) ? 255 : 0;
294 packs.shore[i + 2] = 0;
295 packs.shore[i + 3] = 0;
296
297 packs.lit[i] = u8(u.u_litNW ?? 1);
298 packs.lit[i + 1] = u8(u.u_litNE ?? 1);
299 packs.lit[i + 2] = u8(u.u_litSW ?? 1);
300 packs.lit[i + 3] = u8(u.u_litSE ?? 1);
301
302 packs.deep[i] = u8(u.u_deepNW ?? 0);
303 packs.deep[i + 1] = u8(u.u_deepNE ?? 0);
304 packs.deep[i + 2] = u8(u.u_deepSW ?? 0);
305 packs.deep[i + 3] = u8(u.u_deepSE ?? 0);
306
307 const shoreUv = u.u_shoreUvRect;
308 const u0 = Array.isArray(shoreUv) ? (shoreUv[0] ?? 0) : 0;
309 const v0 = Array.isArray(shoreUv) ? (shoreUv[1] ?? 0) : 0;
310 const u1 = Array.isArray(shoreUv) ? (shoreUv[2] ?? 1) : 1;
311 const v1 = Array.isArray(shoreUv) ? (shoreUv[3] ?? 1) : 1;
312 packs.shoreUv[i] = u8(u0);
313 packs.shoreUv[i + 1] = u8(v0);
314 packs.shoreUv[i + 2] = u8(u1);
315 packs.shoreUv[i + 3] = u8(v1);
316 }
317
318 function uploadPack (gl, tex, pixels)
319 {
320 gl.bindTexture(gl.TEXTURE_2D, tex);
321 gl.texSubImage2D(
322 gl.TEXTURE_2D, 0, 0, 0,
323 FLUID_PACK_SIZE, FLUID_PACK_SIZE,
324 gl.RGBA, gl.UNSIGNED_BYTE, pixels
325 );
326 }
327
328 export function uploadFluidPacks (glCtx, packs)
329 {
330 const gl = glCtx?.gl;
331 if (!gl || !packs)
332 { return; }
333 uploadPack(gl, packs.texMask, packs.mask);
334 uploadPack(gl, packs.texShore, packs.shore);
335 uploadPack(gl, packs.texLit, packs.lit);
336 uploadPack(gl, packs.texDeep, packs.deep);
337 uploadPack(gl, packs.texShoreUv, packs.shoreUv);
338 }
339
340 /**
341 * One full-atlas draw for a fluid kind (water or lava ground, or lava bloom).
342 * Must run inside withFluidAtlasPass (FBO already bound/cleared as needed).
343 */
344 export function drawFluidAtlasChunkPass (glCtx, {
345 textureHtml,
346 secondaryHtml = null,
347 shader,
348 uniforms,
349 packs,
350 kindFilter,
351 includeShorePacks = true
352 })
353 {
354 if (!textureHtml || !shader || !packs)
355 { return; }
356 const textures = {
357 u_tileMask: packs.texMask
358 };
359 if (includeShorePacks)
360 {
361 textures.u_tileShore = packs.texShore;
362 textures.u_tileLit = packs.texLit;
363 textures.u_tileDeep = packs.texDeep;
364 textures.u_tileShoreUv = packs.texShoreUv;
365 textures.u_secondary = glCtx.getTexture(secondaryHtml || textureHtml);
366 }
367 const half = FLUID_ATLAS_PX / 2;
368 glCtx.drawSprite({
369 texture: glCtx.getTexture(textureHtml),
370 x: half,
371 y: half,
372 w: FLUID_ATLAS_PX,
373 h: FLUID_ATLAS_PX,
374 rotationDeg: 0,
375 mirrorX: false,
376 mirrorY: false,
377 alpha: 1,
378 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
379 shader,
380 uniforms: {
381 ...uniforms,
382 u_kindFilter: kindFilter,
383 u_atlasPx: FLUID_ATLAS_PX,
384 u_tilePx: SPRITE_SIZE_PX
385 },
386 textures,
387 lights: null
388 });
389 }
@@ -0,0 +1,389 @@
1/**
2 * Per-chunk fluid (water / lava) atlas: render procedural shaders at true
3 * SPRITE_SIZE_PX, then nearest-upscale the atlas to chunk world size.
4 *
5 * Tile placement is Y-down (localY), content upright (no per-tile mirrorY —
6 * that breaks world-space noise continuity / seams). FBO↔sprite V mismatch
7 * is corrected only by mirrorY on the atlas GameObject.
8 *
9 * Single-pass bake packs per-tile uniforms into 16×16 RGBA textures and draws
10 * the full atlas with one (or two, water+lava) chunk shader pass.
11 */
12
13import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
14import { frameworkImageFromCanvas } from "./canvasSprite.js";
15
16export const FLUID_ATLAS_PX = CHUNK_SIZE * SPRITE_SIZE_PX;
17export const FLUID_PACK_SIZE = CHUNK_SIZE;
18
19/** Kind bytes stored in pack mask.R (0 = empty). */
20export const FLUID_KIND_WATER = 1;
21export const FLUID_KIND_LAVA = 2;
22
23/**
24 * @param {import("../../frameworkv3/framework/engine/gl/glContext.js").default | object} glCtx
25 * @returns {{ canvas: HTMLCanvasElement, tex: WebGLTexture, fb: WebGLFramebuffer, image: object, size: number } | null}
26 */
27export function createFluidAtlasTarget (glCtx)
28{
29 const gl = glCtx?.gl;
30 if (!gl)
31 { return null; }
32 const size = FLUID_ATLAS_PX;
33 const canvas = document.createElement("canvas");
34 canvas.width = size;
35 canvas.height = size;
36
37 const tex = gl.createTexture();
38 gl.bindTexture(gl.TEXTURE_2D, tex);
39 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
40 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
41 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
42 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
43 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
44
45 // Seed WeakMap so Framework getTexture(canvas) returns this FBO color attachment.
46 glCtx.textures.set(canvas, tex);
47
48 const fb = gl.createFramebuffer();
49 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
50 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
51 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
52 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
53 if (status !== gl.FRAMEBUFFER_COMPLETE)
54 {
55 gl.deleteFramebuffer(fb);
56 gl.deleteTexture(tex);
57 glCtx.textures.delete(canvas);
58 return null;
59 }
60
61 return {
62 canvas,
63 tex,
64 fb,
65 image: frameworkImageFromCanvas(canvas),
66 size
67 };
68}
69
70export function destroyFluidAtlasTarget (glCtx, target)
71{
72 if (!target)
73 { return; }
74 const gl = glCtx?.gl;
75 if (gl)
76 {
77 if (target.fb)
78 { gl.deleteFramebuffer(target.fb); }
79 if (target.tex)
80 { gl.deleteTexture(target.tex); }
81 }
82 if (glCtx?.textures && target.canvas)
83 { glCtx.textures.delete(target.canvas); }
84 target.fb = null;
85 target.tex = null;
86}
87
88/**
89 * Bind atlas FBO, clear transparent, run drawFn with drawSprite matrix sized to atlas.
90 * Restores framebuffer, viewport, and _lastWidth/_lastHeight.
91 */
92export function withFluidAtlasPass (glCtx, target, drawFn)
93{
94 const gl = glCtx?.gl;
95 if (!gl || !target?.fb)
96 { return; }
97 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
98 const prevViewport = gl.getParameter(gl.VIEWPORT);
99 const prevW = glCtx._lastWidth;
100 const prevH = glCtx._lastHeight;
101 const prevBlend = gl.isEnabled(gl.BLEND);
102 try
103 {
104 glCtx._lastWidth = target.size;
105 glCtx._lastHeight = target.size;
106 gl.bindFramebuffer(gl.FRAMEBUFFER, target.fb);
107 gl.viewport(0, 0, target.size, target.size);
108 // Opaque replace — blending onto clear left 1px fringes / grid seams.
109 gl.disable(gl.BLEND);
110 gl.clearColor(0, 0, 0, 0);
111 gl.clear(gl.COLOR_BUFFER_BIT);
112 drawFn();
113 }
114 finally
115 {
116 glCtx._lastWidth = prevW;
117 glCtx._lastHeight = prevH;
118 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
119 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
120 if (!prevBlend)
121 { gl.disable(gl.BLEND); }
122 else
123 { gl.enable(gl.BLEND); }
124 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
125 }
126}
127
128/** Pixel-space center of a chunk-local tile inside the FBO (Y-down, same as world). */
129export function fluidAtlasTileCenter (localX, localY)
130{
131 return {
132 x: localX * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2,
133 y: localY * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2
134 };
135}
136
137/**
138 * Draw one fluid tile into the currently bound atlas pass.
139 * @param {object} glCtx
140 * @param {{
141 * textureHtml: TexImageSource,
142 * secondaryHtml?: TexImageSource | null,
143 * localX: number,
144 * localY: number,
145 * shader: object,
146 * uniforms: object,
147 * uvRect?: { u0: number, v0: number, u1: number, v1: number } | null
148 * }} opts
149 */
150export function drawFluidAtlasTile (glCtx, {
151 textureHtml,
152 secondaryHtml = null,
153 localX,
154 localY,
155 shader,
156 uniforms,
157 uvRect = null
158})
159{
160 if (!textureHtml || !shader)
161 { return; }
162 const center = fluidAtlasTileCenter(localX, localY);
163 const textures = secondaryHtml
164 ? { u_secondary: glCtx.getTexture(secondaryHtml) }
165 : null;
166 glCtx.drawSprite({
167 texture: glCtx.getTexture(textureHtml),
168 x: center.x,
169 y: center.y,
170 w: SPRITE_SIZE_PX,
171 h: SPRITE_SIZE_PX,
172 rotationDeg: 0,
173 mirrorX: false,
174 // Do not mirrorY per tile — inverts puv vs u_tileY and seams the FBM field.
175 mirrorY: false,
176 alpha: 1,
177 uvRect: uvRect ?? { u0: 0, v0: 0, u1: 1, v1: 1 },
178 shader,
179 uniforms,
180 textures,
181 lights: null
182 });
183}
184
185function createPackTexture (gl)
186{
187 const tex = gl.createTexture();
188 gl.bindTexture(gl.TEXTURE_2D, tex);
189 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
190 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
191 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
192 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
193 gl.texImage2D(
194 gl.TEXTURE_2D, 0, gl.RGBA,
195 FLUID_PACK_SIZE, FLUID_PACK_SIZE, 0,
196 gl.RGBA, gl.UNSIGNED_BYTE, null
197 );
198 return tex;
199}
200
201/**
202 * CPU+GPU pack set for one chunk (5 × 16×16 RGBA8).
203 * @returns {{
204 * mask: Uint8Array, shore: Uint8Array, lit: Uint8Array, deep: Uint8Array, shoreUv: Uint8Array,
205 * texMask: WebGLTexture, texShore: WebGLTexture, texLit: WebGLTexture, texDeep: WebGLTexture, texShoreUv: WebGLTexture
206 * } | null}
207 */
208export function createFluidPackSet (glCtx)
209{
210 const gl = glCtx?.gl;
211 if (!gl)
212 { return null; }
213 const n = FLUID_PACK_SIZE * FLUID_PACK_SIZE * 4;
214 return {
215 mask: new Uint8Array(n),
216 shore: new Uint8Array(n),
217 lit: new Uint8Array(n),
218 deep: new Uint8Array(n),
219 shoreUv: new Uint8Array(n),
220 texMask: createPackTexture(gl),
221 texShore: createPackTexture(gl),
222 texLit: createPackTexture(gl),
223 texDeep: createPackTexture(gl),
224 texShoreUv: createPackTexture(gl)
225 };
226}
227
228export function destroyFluidPackSet (glCtx, packs)
229{
230 if (!packs)
231 { return; }
232 const gl = glCtx?.gl;
233 if (gl)
234 {
235 for (const key of ["texMask", "texShore", "texLit", "texDeep", "texShoreUv"])
236 {
237 if (packs[key])
238 { gl.deleteTexture(packs[key]); }
239 packs[key] = null;
240 }
241 }
242}
243
244export function clearFluidPackPixels (packs)
245{
246 if (!packs)
247 { return; }
248 packs.mask.fill(0);
249 packs.shore.fill(0);
250 packs.lit.fill(0);
251 packs.deep.fill(0);
252 packs.shoreUv.fill(0);
253}
254
255function packBits4 (a, b, c, d)
256{
257 return ((a > 0.5 ? 1 : 0)
258 | ((b > 0.5 ? 1 : 0) << 1)
259 | ((c > 0.5 ? 1 : 0) << 2)
260 | ((d > 0.5 ? 1 : 0) << 3)) & 0xff;
261}
262
263function u8 (v)
264{
265 return Math.max(0, Math.min(255, (v * 255 + 0.5) | 0));
266}
267
268/**
269 * Write one tile's uniforms into pack CPU buffers.
270 * @param {object} packs
271 * @param {number} localX
272 * @param {number} localY
273 * @param {number} kind FLUID_KIND_WATER | FLUID_KIND_LAVA
274 * @param {object} uniforms tile shaderUniforms
275 */
276export function writeFluidPackTile (packs, localX, localY, kind, uniforms)
277{
278 if (!packs || !uniforms)
279 { return; }
280 const lx = localX | 0;
281 const ly = localY | 0;
282 if (lx < 0 || ly < 0 || lx >= FLUID_PACK_SIZE || ly >= FLUID_PACK_SIZE)
283 { return; }
284 const i = (ly * FLUID_PACK_SIZE + lx) * 4;
285 const u = uniforms;
286
287 packs.mask[i] = kind | 0;
288 packs.mask[i + 1] = packBits4(u.u_edgeN, u.u_edgeE, u.u_edgeS, u.u_edgeW);
289 packs.mask[i + 2] = packBits4(u.u_edgeNE, u.u_edgeNW, u.u_edgeSE, u.u_edgeSW);
290 packs.mask[i + 3] = packBits4(u.u_shoreEdgeN, u.u_shoreEdgeE, u.u_shoreEdgeS, u.u_shoreEdgeW);
291
292 packs.shore[i] = packBits4(u.u_shoreEdgeNE, u.u_shoreEdgeNW, u.u_shoreEdgeSE, u.u_shoreEdgeSW);
293 packs.shore[i + 1] = (u.u_hasShore > 0.5) ? 255 : 0;
294 packs.shore[i + 2] = 0;
295 packs.shore[i + 3] = 0;
296
297 packs.lit[i] = u8(u.u_litNW ?? 1);
298 packs.lit[i + 1] = u8(u.u_litNE ?? 1);
299 packs.lit[i + 2] = u8(u.u_litSW ?? 1);
300 packs.lit[i + 3] = u8(u.u_litSE ?? 1);
301
302 packs.deep[i] = u8(u.u_deepNW ?? 0);
303 packs.deep[i + 1] = u8(u.u_deepNE ?? 0);
304 packs.deep[i + 2] = u8(u.u_deepSW ?? 0);
305 packs.deep[i + 3] = u8(u.u_deepSE ?? 0);
306
307 const shoreUv = u.u_shoreUvRect;
308 const u0 = Array.isArray(shoreUv) ? (shoreUv[0] ?? 0) : 0;
309 const v0 = Array.isArray(shoreUv) ? (shoreUv[1] ?? 0) : 0;
310 const u1 = Array.isArray(shoreUv) ? (shoreUv[2] ?? 1) : 1;
311 const v1 = Array.isArray(shoreUv) ? (shoreUv[3] ?? 1) : 1;
312 packs.shoreUv[i] = u8(u0);
313 packs.shoreUv[i + 1] = u8(v0);
314 packs.shoreUv[i + 2] = u8(u1);
315 packs.shoreUv[i + 3] = u8(v1);
316}
317
318function uploadPack (gl, tex, pixels)
319{
320 gl.bindTexture(gl.TEXTURE_2D, tex);
321 gl.texSubImage2D(
322 gl.TEXTURE_2D, 0, 0, 0,
323 FLUID_PACK_SIZE, FLUID_PACK_SIZE,
324 gl.RGBA, gl.UNSIGNED_BYTE, pixels
325 );
326}
327
328export function uploadFluidPacks (glCtx, packs)
329{
330 const gl = glCtx?.gl;
331 if (!gl || !packs)
332 { return; }
333 uploadPack(gl, packs.texMask, packs.mask);
334 uploadPack(gl, packs.texShore, packs.shore);
335 uploadPack(gl, packs.texLit, packs.lit);
336 uploadPack(gl, packs.texDeep, packs.deep);
337 uploadPack(gl, packs.texShoreUv, packs.shoreUv);
338}
339
340/**
341 * One full-atlas draw for a fluid kind (water or lava ground, or lava bloom).
342 * Must run inside withFluidAtlasPass (FBO already bound/cleared as needed).
343 */
344export function drawFluidAtlasChunkPass (glCtx, {
345 textureHtml,
346 secondaryHtml = null,
347 shader,
348 uniforms,
349 packs,
350 kindFilter,
351 includeShorePacks = true
352})
353{
354 if (!textureHtml || !shader || !packs)
355 { return; }
356 const textures = {
357 u_tileMask: packs.texMask
358 };
359 if (includeShorePacks)
360 {
361 textures.u_tileShore = packs.texShore;
362 textures.u_tileLit = packs.texLit;
363 textures.u_tileDeep = packs.texDeep;
364 textures.u_tileShoreUv = packs.texShoreUv;
365 textures.u_secondary = glCtx.getTexture(secondaryHtml || textureHtml);
366 }
367 const half = FLUID_ATLAS_PX / 2;
368 glCtx.drawSprite({
369 texture: glCtx.getTexture(textureHtml),
370 x: half,
371 y: half,
372 w: FLUID_ATLAS_PX,
373 h: FLUID_ATLAS_PX,
374 rotationDeg: 0,
375 mirrorX: false,
376 mirrorY: false,
377 alpha: 1,
378 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
379 shader,
380 uniforms: {
381 ...uniforms,
382 u_kindFilter: kindFilter,
383 u_atlasPx: FLUID_ATLAS_PX,
384 u_tilePx: SPRITE_SIZE_PX
385 },
386 textures,
387 lights: null
388 });
389}
client/src/render/worldView.js +736 −48
@@ -19,8 +19,8 @@ import
19 19 import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
20 20 import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
21 21 import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
22 import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23 import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
22 import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23 import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js";
24 24 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
25 25 import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
26 26 import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -31,6 +31,27 @@ import
31 31 uploadCanvasTextureRgba
32 32 } from "./canvasSprite.js";
33 33 import { setNearestFilter } from "./sprites.js";
34 import
35 {
36 createFluidAtlasTarget,
37 destroyFluidAtlasTarget,
38 withFluidAtlasPass,
39 drawFluidAtlasTile,
40 createFluidPackSet,
41 destroyFluidPackSet,
42 clearFluidPackPixels,
43 writeFluidPackTile,
44 uploadFluidPacks,
45 drawFluidAtlasChunkPass,
46 FLUID_KIND_WATER,
47 FLUID_KIND_LAVA
48 } from "./fluidChunkAtlas.js";
49 import
50 {
51 WATER_ATLAS_CHUNK_FRAG,
52 LAVA_ATLAS_CHUNK_FRAG,
53 LAVA_BLOOM_ATLAS_CHUNK_FRAG
54 } from "./fluidAtlasChunkShaders.js";
34 55 import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
35 56 import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js";
36 57 import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
@@ -963,6 +984,9 @@ let cliffGroundTopShader = null;
963 984 let waterGroundShader = null;
964 985 let lavaGroundShader = null;
965 986 let lavaBloomShader = null;
987 let waterAtlasChunkShader = null;
988 let lavaAtlasChunkShader = null;
989 let lavaBloomAtlasChunkShader = null;
966 990 let tintLitSpriteShader = null;
967 991 let dualTintLitSpriteShader = null;
968 992 let tightFitTintLitSpriteShader = null;
@@ -1010,6 +1034,27 @@ function getLavaBloomShader ()
1010 1034 return lavaBloomShader;
1011 1035 }
1012 1036
1037 function getWaterAtlasChunkShader ()
1038 {
1039 if (!waterAtlasChunkShader)
1040 { waterAtlasChunkShader = Shader.fragment(WATER_ATLAS_CHUNK_FRAG); }
1041 return waterAtlasChunkShader;
1042 }
1043
1044 function getLavaAtlasChunkShader ()
1045 {
1046 if (!lavaAtlasChunkShader)
1047 { lavaAtlasChunkShader = Shader.fragment(LAVA_ATLAS_CHUNK_FRAG); }
1048 return lavaAtlasChunkShader;
1049 }
1050
1051 function getLavaBloomAtlasChunkShader ()
1052 {
1053 if (!lavaBloomAtlasChunkShader)
1054 { lavaBloomAtlasChunkShader = Shader.fragment(LAVA_BLOOM_ATLAS_CHUNK_FRAG); }
1055 return lavaBloomAtlasChunkShader;
1056 }
1057
1013 1058 function getTintLitSpriteShader ()
1014 1059 {
1015 1060 if (!tintLitSpriteShader)
@@ -1058,6 +1103,12 @@ export class WorldView
1058 1103 #playerMoveChunkDy = 0;
1059 1104 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1060 1105 #placeSizeScratch = new vector(0, 0);
1106 /** When true, water/lava shade into per-chunk 16×16 atlases (set false if FBO init fails). */
1107 #useFluidAtlas = true;
1108 /** Chunk-wide single-pass fluid atlas bake (pack textures). Set false or window.__QW_FLUID_ATLAS_SINGLE_PASS=false for per-tile fallback. */
1109 #useFluidAtlasSinglePass = true;
1110 /** Bumped on chunk bake / season change — invalidates cached fluid coast topology. */
1111 #fluidCoastEpoch = 0;
1061 1112
1062 1113 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1063 1114 {
@@ -1108,6 +1159,8 @@ export class WorldView
1108 1159 this.worldSeason = seasonIdAt();
1109 1160 this.nightPreview = null;
1110 1161 this.followPlayer = true;
1162 /** Play: only draw world-border segments on walkable tiles. Editor keeps full bars. */
1163 this.worldBorderWalkableOnly = false;
1111 1164 this.dynamicLights = [];
1112 1165 /** Persistent Light-spell tile lights (server-driven). */
1113 1166 this.spellLights = new Map();
@@ -2728,6 +2781,11 @@ export class WorldView
2728 2781 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2729 2782 else
2730 2783 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2784 if (
2785 this.worldBorderWalkableOnly
2786 && (localX === 0 || localY === 0 || localX === CHUNK_SIZE - 1 || localY === CHUNK_SIZE - 1)
2787 )
2788 { this.#scheduleEdgeRebuild(); }
2731 2789 }
2732 2790 const tileX = chunkX * CHUNK_SIZE + localX;
2733 2791 const tileY = chunkY * CHUNK_SIZE + localY;
@@ -3170,6 +3228,8 @@ export class WorldView
3170 3228 this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK));
3171 3229 }
3172 3230 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
3231 this.#layoutFluidAtlasObject(baked, "ground");
3232 this.#layoutFluidAtlasObject(baked, "bloom");
3173 3233 }
3174 3234 // Unbaked tile sprites: tall blocks, doors and animated grounds.
3175 3235 for (const objects of this.tiles.values())
@@ -3257,6 +3317,12 @@ export class WorldView
3257 3317 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
3258 3318 this.#setRendererVisible(baked.groundObject, chunkVisible);
3259 3319 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
3320 // Fluid atlas objects are shown/hidden in #syncFluidAtlases; keep offscreen ones off.
3321 if (!chunkVisible)
3322 {
3323 this.#setRendererVisible(baked.fluidGroundObject, false);
3324 this.#setRendererVisible(baked.fluidBloomObject, false);
3325 }
3260 3326 baked._inViewport = chunkVisible;
3261 3327 for (let row = 0; row < CHUNK_SIZE; row++)
3262 3328 {
@@ -3274,11 +3340,12 @@ export class WorldView
3274 3340 const top = objects.tileY * size;
3275 3341 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
3276 3342 objects._inViewport = visible;
3277 this.#setRendererVisible(objects.ground, visible);
3343 const fluidAtlas = this.#useFluidAtlas && this.#tileUsesFluidAtlas(objects);
3344 this.#setRendererVisible(objects.ground, visible && !fluidAtlas);
3278 3345 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3279 3346 this.#setRendererVisible(objects.block, visible);
3280 3347 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3281 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled);
3348 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled && !fluidAtlas);
3282 3349 }
3283 3350 }
3284 3351
@@ -3667,6 +3734,12 @@ export class WorldView
3667 3734 {
3668 3735 renderer.shaderUniforms = {};
3669 3736 renderer._shaderUniformKind = kind;
3737 renderer._fluidStaticsReady = false;
3738 // Static water/lava tune uniforms — apply once per kind, not every frame.
3739 if (kind === "water")
3740 { Object.assign(renderer.shaderUniforms, waterDebugUniforms()); }
3741 else if (kind === "lava" || kind === "lavaBloom")
3742 { Object.assign(renderer.shaderUniforms, lavaDebugUniforms()); }
3670 3743 }
3671 3744 return renderer.shaderUniforms;
3672 3745 }
@@ -4070,7 +4143,8 @@ export class WorldView
4070 4143 fallbackLit = 1,
4071 4144 tileX = 0,
4072 4145 tileY = 0,
4073 deepCorners = null
4146 deepCorners = null,
4147 staticsDirty = true
4074 4148 } = {})
4075 4149 {
4076 4150 if (!object?.renderer)
@@ -4082,6 +4156,17 @@ export class WorldView
4082 4156 se: fallbackLit
4083 4157 };
4084 4158 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4159 object._lit = true;
4160 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4161 // Dynamic every frame: time + lighting.
4162 uniforms.u_ambientDark = dark;
4163 uniforms.u_litNW = lit.nw;
4164 uniforms.u_litNE = lit.ne;
4165 uniforms.u_litSW = lit.sw;
4166 uniforms.u_litSE = lit.se;
4167 uniforms.u_time = timeSec;
4168 if (!staticsDirty && object.renderer._fluidStaticsReady)
4169 { return; }
4085 4170 const shoreSprite = shore?.sprite ?? null;
4086 4171 const shoreUv = shoreSprite?.getUvRect?.(0)
4087 4172 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
@@ -4089,19 +4174,11 @@ export class WorldView
4089 4174 const dNE = deepCorners?.ne ?? 0;
4090 4175 const dSW = deepCorners?.sw ?? 0;
4091 4176 const dSE = deepCorners?.se ?? 0;
4092 object._lit = true;
4093 4177 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
4094 4178 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
4095 4179 if (sharedNoise)
4096 4180 { object.renderer.sprite = sharedNoise; }
4097 4181 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4098 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4099 uniforms.u_ambientDark = dark;
4100 uniforms.u_litNW = lit.nw;
4101 uniforms.u_litNE = lit.ne;
4102 uniforms.u_litSW = lit.sw;
4103 uniforms.u_litSE = lit.se;
4104 uniforms.u_time = timeSec;
4105 4182 uniforms.u_tileX = tileX | 0;
4106 4183 uniforms.u_tileY = tileY | 0;
4107 4184 uniforms.u_deepNW = dNW;
@@ -4126,7 +4203,7 @@ export class WorldView
4126 4203 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4127 4204 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4128 4205 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4129 Object.assign(uniforms, waterDebugUniforms());
4206 object.renderer._fluidStaticsReady = true;
4130 4207 }
4131 4208
4132 4209 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
@@ -4165,19 +4242,19 @@ export class WorldView
4165 4242 else
4166 4243 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4167 4244 }
4168 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4169 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges);
4170 const deep = objects.groundTypeId === GroundType.deepWater;
4245 const coast = this.#cachedWaterCoast(objects);
4246 objects.waterEdges = coast.edges;
4171 4247 this.#syncWaterGroundSprite(objects.ground, {
4172 4248 corners: litCorners,
4173 4249 ambientDark,
4174 edges: objects.waterEdges,
4175 shore,
4250 edges: coast.edges,
4251 shore: coast.shore,
4176 4252 timeSec,
4177 4253 fallbackLit,
4178 4254 tileX: objects.tileX,
4179 4255 tileY: objects.tileY,
4180 deepCorners: this.#waterDeepCorners(objects.tileX, objects.tileY, deep)
4256 deepCorners: coast.deepCorners,
4257 staticsDirty: coast.staticsDirty
4181 4258 });
4182 4259 }
4183 4260
@@ -4258,26 +4335,27 @@ export class WorldView
4258 4335 else
4259 4336 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4260 4337 }
4261 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4262 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4338 const coast = this.#cachedLavaCoast(objects);
4263 4339 this.#syncLavaGroundSprite(objects.ground, {
4264 4340 corners: litCorners,
4265 4341 ambientDark,
4266 edges,
4267 shore,
4342 edges: coast.edges,
4343 shore: coast.shore,
4268 4344 timeSec,
4269 4345 fallbackLit,
4270 4346 tileX: objects.tileX,
4271 tileY: objects.tileY
4347 tileY: objects.tileY,
4348 staticsDirty: coast.staticsDirty
4272 4349 });
4273 4350 const bloom = this.#ensureLavaBloom(objects);
4274 4351 if (bloom)
4275 4352 {
4276 4353 this.#syncLavaBloomSprite(bloom, {
4277 edges,
4354 edges: coast.edges,
4278 4355 timeSec,
4279 4356 tileX: objects.tileX,
4280 tileY: objects.tileY
4357 tileY: objects.tileY,
4358 staticsDirty: coast.staticsDirty
4281 4359 });
4282 4360 }
4283 4361 }
@@ -4290,7 +4368,8 @@ export class WorldView
4290 4368 timeSec = 0,
4291 4369 fallbackLit = 1,
4292 4370 tileX = 0,
4293 tileY = 0
4371 tileY = 0,
4372 staticsDirty = true
4294 4373 } = {})
4295 4374 {
4296 4375 if (!object?.renderer)
@@ -4302,11 +4381,7 @@ export class WorldView
4302 4381 se: fallbackLit
4303 4382 };
4304 4383 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4305 const shoreSprite = shore?.sprite ?? null;
4306 const shoreUv = shoreSprite?.getUvRect?.(0)
4307 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4308 4384 object._lit = true;
4309 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4310 4385 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4311 4386 uniforms.u_ambientDark = dark;
4312 4387 uniforms.u_litNW = lit.nw;
@@ -4314,6 +4389,12 @@ export class WorldView
4314 4389 uniforms.u_litSW = lit.sw;
4315 4390 uniforms.u_litSE = lit.se;
4316 4391 uniforms.u_time = timeSec;
4392 if (!staticsDirty && object.renderer._fluidStaticsReady)
4393 { return; }
4394 const shoreSprite = shore?.sprite ?? null;
4395 const shoreUv = shoreSprite?.getUvRect?.(0)
4396 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4397 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4317 4398 uniforms.u_tileX = tileX | 0;
4318 4399 uniforms.u_tileY = tileY | 0;
4319 4400 uniforms.u_edgeN = edges?.n ?? 0;
@@ -4334,20 +4415,23 @@ export class WorldView
4334 4415 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4335 4416 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4336 4417 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4337 Object.assign(uniforms, lavaDebugUniforms());
4418 object.renderer._fluidStaticsReady = true;
4338 4419 }
4339 4420
4340 4421 #syncLavaBloomSprite (object, {
4341 4422 edges = null,
4342 4423 timeSec = 0,
4343 4424 tileX = 0,
4344 tileY = 0
4425 tileY = 0,
4426 staticsDirty = true
4345 4427 } = {})
4346 4428 {
4347 4429 if (!object?.renderer)
4348 4430 { return; }
4349 4431 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4350 4432 uniforms.u_time = timeSec;
4433 if (!staticsDirty && object.renderer._fluidStaticsReady)
4434 { return; }
4351 4435 uniforms.u_tileX = tileX | 0;
4352 4436 uniforms.u_tileY = tileY | 0;
4353 4437 uniforms.u_edgeN = edges?.n ?? 0;
@@ -4358,7 +4442,496 @@ export class WorldView
4358 4442 uniforms.u_edgeNW = edges?.nw ?? 0;
4359 4443 uniforms.u_edgeSE = edges?.se ?? 0;
4360 4444 uniforms.u_edgeSW = edges?.sw ?? 0;
4361 Object.assign(uniforms, lavaDebugUniforms());
4445 object.renderer._fluidStaticsReady = true;
4446 }
4447
4448
4449 #cachedWaterCoast (objects)
4450 {
4451 const epoch = this.#fluidCoastEpoch;
4452 const typeId = objects.groundTypeId;
4453 const season = this.worldSeason;
4454 const cache = objects._fluidCoastCache;
4455 if (
4456 cache
4457 && cache.epoch === epoch
4458 && cache.typeId === typeId
4459 && cache.season === season
4460 && cache.kind === "water"
4461 )
4462 { return { edges: cache.edges, shore: cache.shore, deepCorners: cache.deepCorners, staticsDirty: false }; }
4463 const edges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4464 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, edges);
4465 const deep = typeId === GroundType.deepWater;
4466 const deepCorners = this.#waterDeepCorners(objects.tileX, objects.tileY, deep);
4467 objects._fluidCoastCache = { epoch, typeId, season, kind: "water", edges, shore, deepCorners };
4468 if (objects.ground?.renderer)
4469 { objects.ground.renderer._fluidStaticsReady = false; }
4470 return { edges, shore, deepCorners, staticsDirty: true };
4471 }
4472
4473 #cachedLavaCoast (objects)
4474 {
4475 const epoch = this.#fluidCoastEpoch;
4476 const typeId = objects.groundTypeId;
4477 const season = this.worldSeason;
4478 const cache = objects._fluidCoastCache;
4479 if (
4480 cache
4481 && cache.epoch === epoch
4482 && cache.typeId === typeId
4483 && cache.season === season
4484 && cache.kind === "lava"
4485 )
4486 { return { edges: cache.edges, shore: cache.shore, staticsDirty: false }; }
4487 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4488 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4489 objects._fluidCoastCache = { epoch, typeId, season, kind: "lava", edges, shore, deepCorners: null };
4490 if (objects.ground?.renderer)
4491 { objects.ground.renderer._fluidStaticsReady = false; }
4492 if (objects.lavaBloom?.renderer)
4493 { objects.lavaBloom.renderer._fluidStaticsReady = false; }
4494 return { edges, shore, staticsDirty: true };
4495 }
4496
4497 #tileUsesFluidAtlas (objects)
4498 {
4499 if (!objects?.groundTypeId)
4500 { return false; }
4501 if (isLavaGround(objects.groundTypeId))
4502 { return true; }
4503 return isLiquidWaterGround(objects.groundTypeId, this.worldSeason);
4504 }
4505
4506 #ensureFluidAtlasSlot (baked, kind)
4507 {
4508 const glCtx = this.scene?.glContext;
4509 if (!glCtx?.gl || !baked)
4510 { return null; }
4511 const key = kind === "bloom" ? "_fluidBloomTarget" : "_fluidGroundTarget";
4512 const objKey = kind === "bloom" ? "fluidBloomObject" : "fluidGroundObject";
4513 if (!baked[key])
4514 {
4515 const target = createFluidAtlasTarget(glCtx);
4516 if (!target)
4517 {
4518 this.#useFluidAtlas = false;
4519 return null;
4520 }
4521 baked[key] = target;
4522 setNearestFilter(this.scene, target.canvas);
4523 }
4524 const target = baked[key];
4525 if (!baked[objKey])
4526 {
4527 const object = new GameObject(0, 0, target.image, LAYER_GROUND);
4528 if (kind === "bloom")
4529 {
4530 object.renderer.layer = RENDER_LAYER_BLOOM;
4531 }
4532 this.#markUnlit(object);
4533 this.scene.addObject(object);
4534 baked[objKey] = object;
4535 this.#layoutFluidAtlasObject(baked, kind);
4536 }
4537 else if (baked[objKey].renderer)
4538 { baked[objKey].renderer.sprite = target.image; }
4539 return { target, object: baked[objKey] };
4540 }
4541
4542 #layoutFluidAtlasObject (baked, kind = "ground")
4543 {
4544 const object = kind === "bloom" ? baked.fluidBloomObject : baked.fluidGroundObject;
4545 if (!object || baked.chunkX == null || baked.chunkY == null)
4546 { return; }
4547 const size = this.tileSize();
4548 const layoutKey = `${baked.chunkX},${baked.chunkY},${size},${kind}`;
4549 if (baked._fluidLayoutKey === layoutKey && object.renderer?.mirrorY)
4550 { return; }
4551 baked._fluidLayoutKey = layoutKey;
4552 const left = baked.chunkX * CHUNK_SIZE * size;
4553 const top = baked.chunkY * CHUNK_SIZE * size;
4554 const chunkPx = CHUNK_SIZE * size;
4555 // Pixel-snap: subpixel atlas placement + NEAREST causes grid cracks.
4556 object.transform.position.x = Math.round(left + chunkPx / 2);
4557 object.transform.position.y = Math.round(top + chunkPx / 2);
4558 object.transform.size = new vector(chunkPx, chunkPx);
4559 // FBO color attachment is V-flipped vs Framework sprite UVs — one atlas
4560 // mirrorY restores N/S hole placement without breaking noise continuity.
4561 if (object.renderer)
4562 { object.renderer.mirrorY = true; }
4563 if (kind === "bloom")
4564 {
4565 this.#setLayer(object, this.#depthLayer(top + chunkPx, SORT_BLOCK));
4566 object.renderer.layer = RENDER_LAYER_BLOOM;
4567 }
4568 else
4569 { this.#setLayer(object, LAYER_GROUND); }
4570 }
4571
4572 #destroyFluidAtlasSlot (baked)
4573 {
4574 const glCtx = this.scene?.glContext;
4575 if (!baked)
4576 { return; }
4577 baked.fluidGroundObject?.destroy();
4578 baked.fluidGroundObject = null;
4579 baked.fluidBloomObject?.destroy();
4580 baked.fluidBloomObject = null;
4581 destroyFluidAtlasTarget(glCtx, baked._fluidGroundTarget);
4582 destroyFluidAtlasTarget(glCtx, baked._fluidBloomTarget);
4583 destroyFluidPackSet(glCtx, baked._fluidPacks);
4584 baked._fluidGroundTarget = null;
4585 baked._fluidBloomTarget = null;
4586 baked._fluidPacks = null;
4587 }
4588
4589 #ensureFluidPacks (baked)
4590 {
4591 const glCtx = this.scene?.glContext;
4592 if (!glCtx?.gl || !baked)
4593 { return null; }
4594 if (!baked._fluidPacks)
4595 {
4596 const packs = createFluidPackSet(glCtx);
4597 if (!packs)
4598 { return null; }
4599 baked._fluidPacks = packs;
4600 }
4601 return baked._fluidPacks;
4602 }
4603
4604 #fluidAtlasSinglePassEnabled ()
4605 {
4606 if (!this.#useFluidAtlasSinglePass)
4607 { return false; }
4608 if (globalThis.__QW_FLUID_ATLAS_SINGLE_PASS === false)
4609 { return false; }
4610 return true;
4611 }
4612
4613 /**
4614 * Render liquid water + lava into per-chunk 16×16 atlases; hide per-tile fluid sprites.
4615 * Lighting/time uniforms stay on the (hidden) tile renderers and are sampled here.
4616 */
4617 #syncFluidAtlases ()
4618 {
4619 if (!this.#useFluidAtlas)
4620 { return; }
4621 const glCtx = this.scene?.glContext;
4622 if (!glCtx?.gl)
4623 { return; }
4624
4625 const byChunk = new Map();
4626 for (const objects of this.tiles.values())
4627 {
4628 if (!objects.ground)
4629 { continue; }
4630 if (!this.#tileUsesFluidAtlas(objects))
4631 { continue; }
4632 // Hide per-tile fluid sprites (keep objects + uniforms for atlas + lighting data).
4633 if (!objects._fluidAtlasHidden)
4634 {
4635 this.#setRendererVisible(objects.ground, false);
4636 this.#setRendererVisible(objects.lavaBloom, false);
4637 objects._fluidAtlasHidden = true;
4638 }
4639 if (objects._inViewport === false)
4640 { continue; }
4641 const key = `${objects.chunkX},${objects.chunkY}`;
4642 let list = byChunk.get(key);
4643 if (!list)
4644 {
4645 list = [];
4646 byChunk.set(key, list);
4647 }
4648 list.push(objects);
4649 }
4650
4651 const active = new Set();
4652 for (const [key, list] of byChunk)
4653 {
4654 const baked = this.bakedChunks.get(key);
4655 if (!baked || baked._inViewport === false)
4656 { continue; }
4657 active.add(key);
4658 this.#renderFluidAtlasChunk(baked, list);
4659 }
4660
4661 for (const baked of this.bakedChunks.values())
4662 {
4663 const key = `${baked.chunkX},${baked.chunkY}`;
4664 if (active.has(key))
4665 { continue; }
4666 this.#setRendererVisible(baked.fluidGroundObject, false);
4667 this.#setRendererVisible(baked.fluidBloomObject, false);
4668 }
4669 }
4670
4671 #showFluidTilesFallback (tileObjects)
4672 {
4673 for (const objects of tileObjects)
4674 {
4675 const vis = objects._inViewport !== false;
4676 objects._fluidAtlasHidden = false;
4677 this.#setRendererVisible(objects.ground, vis);
4678 this.#setRendererVisible(objects.lavaBloom, vis && this.bloomEnabled);
4679 }
4680 }
4681
4682 #renderFluidAtlasChunk (baked, tileObjects)
4683 {
4684 const glCtx = this.scene?.glContext;
4685 const groundSlot = this.#ensureFluidAtlasSlot(baked, "ground");
4686 if (!groundSlot || !this.#useFluidAtlas)
4687 {
4688 this.#showFluidTilesFallback(tileObjects);
4689 return;
4690 }
4691
4692 const usedSingle = this.#fluidAtlasSinglePassEnabled()
4693 && this.#renderFluidAtlasChunkSinglePass(baked, tileObjects, groundSlot);
4694 if (!usedSingle)
4695 { this.#renderFluidAtlasChunkPerTile(baked, tileObjects, groundSlot); }
4696 }
4697
4698 #renderFluidAtlasChunkPerTile (baked, tileObjects, groundSlot)
4699 {
4700 const glCtx = this.scene?.glContext;
4701 const bloomTiles = [];
4702 withFluidAtlasPass(glCtx, groundSlot.target, () =>
4703 {
4704 for (const objects of tileObjects)
4705 {
4706 const renderer = objects.ground?.renderer;
4707 if (!renderer?.shader || !renderer.shaderUniforms || !renderer.sprite?.g_image)
4708 { continue; }
4709 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4710 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4711 drawFluidAtlasTile(glCtx, {
4712 textureHtml: renderer.sprite.g_image,
4713 secondaryHtml: renderer.secondaryMap ?? null,
4714 localX,
4715 localY,
4716 shader: renderer.shader,
4717 uniforms: renderer.shaderUniforms,
4718 uvRect: renderer.sprite.getUvRect?.(renderer.subImage | 0) ?? null
4719 });
4720 if (objects.lavaBloom?.renderer?.shader)
4721 { bloomTiles.push(objects); }
4722 }
4723 });
4724 this.#layoutFluidAtlasObject(baked, "ground");
4725 this.#setRendererVisible(groundSlot.object, true);
4726
4727 if (!bloomTiles.length || !this.bloomEnabled)
4728 {
4729 this.#setRendererVisible(baked.fluidBloomObject, false);
4730 return;
4731 }
4732
4733 const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom");
4734 if (!bloomSlot || !this.#useFluidAtlas)
4735 { return; }
4736 withFluidAtlasPass(glCtx, bloomSlot.target, () =>
4737 {
4738 for (const objects of bloomTiles)
4739 {
4740 const renderer = objects.lavaBloom?.renderer;
4741 if (!renderer?.shader || !renderer.shaderUniforms)
4742 { continue; }
4743 const tex = renderer.sprite?.g_image ?? objects.ground?.renderer?.sprite?.g_image;
4744 if (!tex)
4745 { continue; }
4746 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4747 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4748 drawFluidAtlasTile(glCtx, {
4749 textureHtml: tex,
4750 secondaryHtml: null,
4751 localX,
4752 localY,
4753 shader: renderer.shader,
4754 uniforms: renderer.shaderUniforms,
4755 uvRect: renderer.sprite?.getUvRect?.(renderer.subImage | 0) ?? null
4756 });
4757 }
4758 });
4759 this.#layoutFluidAtlasObject(baked, "bloom");
4760 this.#setRendererVisible(bloomSlot.object, true);
4761 }
4762
4763 /**
4764 * Pack per-tile uniforms into 16×16 textures and bake with 1–2 chunk draws.
4765 * @returns {boolean} true when single-pass succeeded
4766 */
4767 #renderFluidAtlasChunkSinglePass (baked, tileObjects, groundSlot)
4768 {
4769 const glCtx = this.scene?.glContext;
4770 const packs = this.#ensureFluidPacks(baked);
4771 if (!packs || !glCtx?.gl)
4772 { return false; }
4773
4774 const waterShader = getWaterAtlasChunkShader();
4775 const lavaShader = getLavaAtlasChunkShader();
4776 const bloomShader = getLavaBloomAtlasChunkShader();
4777 if (!waterShader?.getProgramInfo(glCtx.gl)
4778 || !lavaShader?.getProgramInfo(glCtx.gl)
4779 || !bloomShader?.getProgramInfo(glCtx.gl))
4780 { return false; }
4781
4782 clearFluidPackPixels(packs);
4783 const waterTiles = [];
4784 const lavaTiles = [];
4785 const bloomTiles = [];
4786 let waterNoise = null;
4787 let lavaNoise = null;
4788 let waterSecondary = null;
4789 let lavaSecondary = null;
4790 let waterUniforms = null;
4791 let lavaUniforms = null;
4792 let bloomUniforms = null;
4793 let ambientDark = 0;
4794 let timeSec = 0;
4795
4796 for (const objects of tileObjects)
4797 {
4798 const renderer = objects.ground?.renderer;
4799 if (!renderer?.shaderUniforms || !renderer.sprite?.g_image)
4800 { continue; }
4801 const kindName = renderer._shaderUniformKind;
4802 const kind = kindName === "lava" ? FLUID_KIND_LAVA
4803 : kindName === "water" ? FLUID_KIND_WATER
4804 : null;
4805 if (!kind)
4806 { continue; }
4807 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4808 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4809 writeFluidPackTile(packs, localX, localY, kind, renderer.shaderUniforms);
4810 const noise = renderer.sprite.g_image;
4811 const secondary = renderer.secondaryMap ?? null;
4812 const u = renderer.shaderUniforms;
4813 ambientDark = u.u_ambientDark ?? ambientDark;
4814 timeSec = u.u_time ?? timeSec;
4815 if (kind === FLUID_KIND_WATER)
4816 {
4817 waterTiles.push(objects);
4818 if (!waterNoise)
4819 { waterNoise = noise; }
4820 else if (waterNoise !== noise)
4821 { return false; }
4822 if (secondary)
4823 {
4824 if (!waterSecondary)
4825 { waterSecondary = secondary; }
4826 else if (waterSecondary !== secondary)
4827 { return false; }
4828 }
4829 if (!waterUniforms)
4830 { waterUniforms = u; }
4831 }
4832 else
4833 {
4834 lavaTiles.push(objects);
4835 if (!lavaNoise)
4836 { lavaNoise = noise; }
4837 else if (lavaNoise !== noise)
4838 { return false; }
4839 if (secondary)
4840 {
4841 if (!lavaSecondary)
4842 { lavaSecondary = secondary; }
4843 else if (lavaSecondary !== secondary)
4844 { return false; }
4845 }
4846 if (!lavaUniforms)
4847 { lavaUniforms = u; }
4848 if (objects.lavaBloom?.renderer?.shaderUniforms)
4849 {
4850 bloomTiles.push(objects);
4851 if (!bloomUniforms)
4852 { bloomUniforms = objects.lavaBloom.renderer.shaderUniforms; }
4853 }
4854 }
4855 }
4856
4857 if (!waterTiles.length && !lavaTiles.length)
4858 { return false; }
4859
4860 uploadFluidPacks(glCtx, packs);
4861 const chunkOriginX = baked.chunkX * CHUNK_SIZE;
4862 const chunkOriginY = baked.chunkY * CHUNK_SIZE;
4863
4864 withFluidAtlasPass(glCtx, groundSlot.target, () =>
4865 {
4866 if (waterTiles.length && waterNoise && waterUniforms)
4867 {
4868 drawFluidAtlasChunkPass(glCtx, {
4869 textureHtml: waterNoise,
4870 secondaryHtml: waterSecondary,
4871 shader: waterShader,
4872 uniforms: {
4873 ...waterDebugUniforms(),
4874 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4875 u_time: timeSec,
4876 u_ambientDark: ambientDark,
4877 u_alpha: 1
4878 },
4879 packs,
4880 kindFilter: FLUID_KIND_WATER,
4881 includeShorePacks: true
4882 });
4883 }
4884 if (lavaTiles.length && lavaNoise && lavaUniforms)
4885 {
4886 drawFluidAtlasChunkPass(glCtx, {
4887 textureHtml: lavaNoise,
4888 secondaryHtml: lavaSecondary,
4889 shader: lavaShader,
4890 uniforms: {
4891 ...lavaDebugUniforms(),
4892 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4893 u_time: timeSec,
4894 u_ambientDark: ambientDark,
4895 u_alpha: 1
4896 },
4897 packs,
4898 kindFilter: FLUID_KIND_LAVA,
4899 includeShorePacks: true
4900 });
4901 }
4902 });
4903 this.#layoutFluidAtlasObject(baked, "ground");
4904 this.#setRendererVisible(groundSlot.object, true);
4905
4906 if (!bloomTiles.length || !this.bloomEnabled || !bloomUniforms || !lavaNoise)
4907 {
4908 this.#setRendererVisible(baked.fluidBloomObject, false);
4909 return true;
4910 }
4911
4912 const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom");
4913 if (!bloomSlot || !this.#useFluidAtlas)
4914 { return true; }
4915 withFluidAtlasPass(glCtx, bloomSlot.target, () =>
4916 {
4917 drawFluidAtlasChunkPass(glCtx, {
4918 textureHtml: lavaNoise,
4919 secondaryHtml: null,
4920 shader: bloomShader,
4921 uniforms: {
4922 ...lavaDebugUniforms(),
4923 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4924 u_time: bloomUniforms.u_time ?? timeSec,
4925 u_alpha: 1
4926 },
4927 packs,
4928 kindFilter: FLUID_KIND_LAVA,
4929 includeShorePacks: false
4930 });
4931 });
4932 this.#layoutFluidAtlasObject(baked, "bloom");
4933 this.#setRendererVisible(bloomSlot.object, true);
4934 return true;
4362 4935 }
4363 4936
4364 4937 #ambientDarkness ()
@@ -4940,6 +5513,7 @@ export class WorldView
4940 5513
4941 5514 #bakeAndPlaceChunk (snapshot)
4942 5515 {
5516 this.#fluidCoastEpoch = (this.#fluidCoastEpoch + 1) | 0;
4943 5517 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4944 5518 const atlases = bakeChunkAtlases({
4945 5519 snapshot,
@@ -5359,6 +5933,8 @@ export class WorldView
5359 5933 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
5360 5934 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
5361 5935 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
5936 this.#layoutFluidAtlasObject(baked, "ground");
5937 this.#layoutFluidAtlasObject(baked, "bloom");
5362 5938 }
5363 5939
5364 5940 #destroyBakedChunk (key)
@@ -5367,6 +5943,7 @@ export class WorldView
5367 5943 if (!baked)
5368 5944 { return; }
5369 5945 this.#releaseBakedAtlasRefs(baked);
5946 this.#destroyFluidAtlasSlot(baked);
5370 5947 baked.groundObject?.destroy();
5371 5948 for (const object of baked.blockObjects ?? [])
5372 5949 { object.destroy(); }
@@ -5457,6 +6034,8 @@ export class WorldView
5457 6034 this.#clearLavaBloom(objects);
5458 6035 objects.groundTypeId = null;
5459 6036 objects.waterEdges = null;
6037 objects._fluidCoastCache = null;
6038 objects._fluidAtlasHidden = false;
5460 6039 }
5461 6040
5462 6041 let blockSource = snapshot.blocks[index];
@@ -5626,9 +6205,21 @@ export class WorldView
5626 6205 let bars = this.edges.get(key);
5627 6206 if (!bars)
5628 6207 {
5629 bars = {};
6208 bars = { north: [], south: [], west: [], east: [], full: {} };
5630 6209 this.edges.set(key, bars);
5631 6210 }
6211 if (!Array.isArray(bars.north))
6212 {
6213 // Migrate legacy single-bar shape from earlier sessions.
6214 for (const dir of ["north", "south", "west", "east"])
6215 {
6216 const legacy = bars[dir];
6217 if (legacy && !Array.isArray(legacy))
6218 { legacy.destroy?.(); }
6219 bars[dir] = [];
6220 }
6221 bars.full = bars.full ?? {};
6222 }
5632 6223
5633 6224 const size = this.tileSize();
5634 6225 const chunkPx = CHUNK_SIZE * size;
@@ -5638,15 +6229,103 @@ export class WorldView
5638 6229 const centerY = top + chunkPx / 2;
5639 6230 const thickness = Math.max(2, Math.round(2 * this.zoom));
5640 6231 const draw = snapshot.open === true;
6232 const walkableOnly = this.worldBorderWalkableOnly === true;
6233
6234 const northClosed = draw && this.#neighborClosed(snapshot, "north", 0, -1);
6235 const southClosed = draw && this.#neighborClosed(snapshot, "south", 0, 1);
6236 const westClosed = draw && this.#neighborClosed(snapshot, "west", -1, 0);
6237 const eastClosed = draw && this.#neighborClosed(snapshot, "east", 1, 0);
6238
6239 if (!walkableOnly)
6240 {
6241 this.#hideEdgeList(bars.north);
6242 this.#hideEdgeList(bars.south);
6243 this.#hideEdgeList(bars.west);
6244 this.#hideEdgeList(bars.east);
6245 bars.full.north = this.#edgeBar(bars.full.north, northClosed,
6246 centerX, top, chunkPx, thickness, true);
6247 bars.full.south = this.#edgeBar(bars.full.south, southClosed,
6248 centerX, top + chunkPx, chunkPx, thickness, true);
6249 bars.full.west = this.#edgeBar(bars.full.west, westClosed,
6250 left, centerY, chunkPx, thickness, false);
6251 bars.full.east = this.#edgeBar(bars.full.east, eastClosed,
6252 left + chunkPx, centerY, chunkPx, thickness, false);
6253 return;
6254 }
5641 6255
5642 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
5643 centerX, top, chunkPx, thickness, true);
5644 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
5645 centerX, top + chunkPx, chunkPx, thickness, true);
5646 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
5647 left, centerY, chunkPx, thickness, false);
5648 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
5649 left + chunkPx, centerY, chunkPx, thickness, false);
6256 for (const dir of ["north", "south", "west", "east"])
6257 {
6258 if (bars.full?.[dir])
6259 {
6260 bars.full[dir].renderer.visible = false;
6261 }
6262 }
6263
6264 bars.north = this.#edgeTileBars(bars.north, northClosed, snapshot, "north", left, top, size, thickness);
6265 bars.south = this.#edgeTileBars(bars.south, southClosed, snapshot, "south", left, top, size, thickness);
6266 bars.west = this.#edgeTileBars(bars.west, westClosed, snapshot, "west", left, top, size, thickness);
6267 bars.east = this.#edgeTileBars(bars.east, eastClosed, snapshot, "east", left, top, size, thickness);
6268 }
6269
6270 /** True when a player can walk the authored tile (doors closed = blocked). */
6271 #tileWalkableOnSnapshot (snapshot, localX, localY)
6272 {
6273 const index = localY * CHUNK_SIZE + localX;
6274 const ground = normalizeGround(snapshot.grounds?.[index]);
6275 if (!isGroundPassable(ground.typeId))
6276 { return false; }
6277 const block = snapshot.blocks?.[index];
6278 if (!block)
6279 { return true; }
6280 const def = blockDefinition(block.typeId);
6281 if (def?.door)
6282 { return isDoorTraversable(block, { canOpenDoors: false, requirementsAllow: true }); }
6283 return isBlockPassable(block.typeId, block.state);
6284 }
6285
6286 #edgeTileBars (list, active, snapshot, dir, left, top, size, thickness)
6287 {
6288 const out = Array.isArray(list) ? list : [];
6289 if (!active)
6290 {
6291 this.#hideEdgeList(out);
6292 return out;
6293 }
6294 let used = 0;
6295 for (let i = 0; i < CHUNK_SIZE; i++)
6296 {
6297 const localX = (dir === "north" || dir === "south") ? i : (dir === "west" ? 0 : CHUNK_SIZE - 1);
6298 const localY = (dir === "west" || dir === "east") ? i : (dir === "north" ? 0 : CHUNK_SIZE - 1);
6299 if (!this.#tileWalkableOnSnapshot(snapshot, localX, localY))
6300 { continue; }
6301 const horizontal = dir === "north" || dir === "south";
6302 const x = horizontal
6303 ? left + (localX + 0.5) * size
6304 : (dir === "west" ? left : left + CHUNK_SIZE * size);
6305 const y = horizontal
6306 ? (dir === "north" ? top : top + CHUNK_SIZE * size)
6307 : top + (localY + 0.5) * size;
6308 out[used] = this.#edgeBar(out[used], true, x, y, size, thickness, horizontal);
6309 used += 1;
6310 }
6311 for (let i = used; i < out.length; i++)
6312 {
6313 if (out[i])
6314 { out[i].renderer.visible = false; }
6315 }
6316 out.length = Math.max(used, out.length);
6317 return out;
6318 }
6319
6320 #hideEdgeList (list)
6321 {
6322 if (!Array.isArray(list))
6323 { return; }
6324 for (const bar of list)
6325 {
6326 if (bar)
6327 { bar.renderer.visible = false; }
6328 }
5650 6329 }
5651 6330
5652 6331 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
@@ -5675,10 +6354,18 @@ export class WorldView
5675 6354 const bars = this.edges.get(key);
5676 6355 if (!bars)
5677 6356 { return; }
5678 bars.north?.destroy();
5679 bars.east?.destroy();
5680 bars.south?.destroy();
5681 bars.west?.destroy();
6357 for (const dir of ["north", "south", "west", "east"])
6358 {
6359 const entry = bars[dir];
6360 if (Array.isArray(entry))
6361 {
6362 for (const bar of entry)
6363 { bar?.destroy?.(); }
6364 }
6365 else
6366 { entry?.destroy?.(); }
6367 bars.full?.[dir]?.destroy?.();
6368 }
5682 6369 this.edges.delete(key);
5683 6370 }
5684 6371
@@ -6012,6 +6699,7 @@ export class WorldView
6012 6699 this.#syncLitSprite(objects.ground, objects.shadeAlpha);
6013 6700 }
6014 6701 }
6702 this.#syncFluidAtlases();
6015 6703
6016 6704 for (const item of this.groundItems.values())
6017 6705 {
@@ -19,8 +19,8 @@ import
19import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
19import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
20import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
20import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
21import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
21import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
22import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
22import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
23import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
23import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js";
24import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
24import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
25import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
25import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
26import { createChunkAtlasCache } from "./chunkAtlasCache.js";
26import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -31,6 +31,27 @@ import
31 uploadCanvasTextureRgba
31 uploadCanvasTextureRgba
32} from "./canvasSprite.js";
32} from "./canvasSprite.js";
33import { setNearestFilter } from "./sprites.js";
33import { setNearestFilter } from "./sprites.js";
34import
35{
36 createFluidAtlasTarget,
37 destroyFluidAtlasTarget,
38 withFluidAtlasPass,
39 drawFluidAtlasTile,
40 createFluidPackSet,
41 destroyFluidPackSet,
42 clearFluidPackPixels,
43 writeFluidPackTile,
44 uploadFluidPacks,
45 drawFluidAtlasChunkPass,
46 FLUID_KIND_WATER,
47 FLUID_KIND_LAVA
48} from "./fluidChunkAtlas.js";
49import
50{
51 WATER_ATLAS_CHUNK_FRAG,
52 LAVA_ATLAS_CHUNK_FRAG,
53 LAVA_BLOOM_ATLAS_CHUNK_FRAG
54} from "./fluidAtlasChunkShaders.js";
34import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
55import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
35import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js";
56import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js";
36import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
57import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
@@ -963,6 +984,9 @@ let cliffGroundTopShader = null;
963let waterGroundShader = null;
984let waterGroundShader = null;
964let lavaGroundShader = null;
985let lavaGroundShader = null;
965let lavaBloomShader = null;
986let lavaBloomShader = null;
987let waterAtlasChunkShader = null;
988let lavaAtlasChunkShader = null;
989let lavaBloomAtlasChunkShader = null;
966let tintLitSpriteShader = null;
990let tintLitSpriteShader = null;
967let dualTintLitSpriteShader = null;
991let dualTintLitSpriteShader = null;
968let tightFitTintLitSpriteShader = null;
992let tightFitTintLitSpriteShader = null;
@@ -1010,6 +1034,27 @@ function getLavaBloomShader ()
1010 return lavaBloomShader;
1034 return lavaBloomShader;
1011}
1035}
1012
1036
1037function getWaterAtlasChunkShader ()
1038{
1039 if (!waterAtlasChunkShader)
1040 { waterAtlasChunkShader = Shader.fragment(WATER_ATLAS_CHUNK_FRAG); }
1041 return waterAtlasChunkShader;
1042}
1043
1044function getLavaAtlasChunkShader ()
1045{
1046 if (!lavaAtlasChunkShader)
1047 { lavaAtlasChunkShader = Shader.fragment(LAVA_ATLAS_CHUNK_FRAG); }
1048 return lavaAtlasChunkShader;
1049}
1050
1051function getLavaBloomAtlasChunkShader ()
1052{
1053 if (!lavaBloomAtlasChunkShader)
1054 { lavaBloomAtlasChunkShader = Shader.fragment(LAVA_BLOOM_ATLAS_CHUNK_FRAG); }
1055 return lavaBloomAtlasChunkShader;
1056}
1057
1013function getTintLitSpriteShader ()
1058function getTintLitSpriteShader ()
1014{
1059{
1015 if (!tintLitSpriteShader)
1060 if (!tintLitSpriteShader)
@@ -1058,6 +1103,12 @@ export class WorldView
1058 #playerMoveChunkDy = 0;
1103 #playerMoveChunkDy = 0;
1059 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1104 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1060 #placeSizeScratch = new vector(0, 0);
1105 #placeSizeScratch = new vector(0, 0);
1106 /** When true, water/lava shade into per-chunk 16×16 atlases (set false if FBO init fails). */
1107 #useFluidAtlas = true;
1108 /** Chunk-wide single-pass fluid atlas bake (pack textures). Set false or window.__QW_FLUID_ATLAS_SINGLE_PASS=false for per-tile fallback. */
1109 #useFluidAtlasSinglePass = true;
1110 /** Bumped on chunk bake / season change — invalidates cached fluid coast topology. */
1111 #fluidCoastEpoch = 0;
1061
1112
1062 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1113 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1063 {
1114 {
@@ -1108,6 +1159,8 @@ export class WorldView
1108 this.worldSeason = seasonIdAt();
1159 this.worldSeason = seasonIdAt();
1109 this.nightPreview = null;
1160 this.nightPreview = null;
1110 this.followPlayer = true;
1161 this.followPlayer = true;
1162 /** Play: only draw world-border segments on walkable tiles. Editor keeps full bars. */
1163 this.worldBorderWalkableOnly = false;
1111 this.dynamicLights = [];
1164 this.dynamicLights = [];
1112 /** Persistent Light-spell tile lights (server-driven). */
1165 /** Persistent Light-spell tile lights (server-driven). */
1113 this.spellLights = new Map();
1166 this.spellLights = new Map();
@@ -2728,6 +2781,11 @@ export class WorldView
2728 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2781 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2729 else
2782 else
2730 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2783 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2784 if (
2785 this.worldBorderWalkableOnly
2786 && (localX === 0 || localY === 0 || localX === CHUNK_SIZE - 1 || localY === CHUNK_SIZE - 1)
2787 )
2788 { this.#scheduleEdgeRebuild(); }
2731 }
2789 }
2732 const tileX = chunkX * CHUNK_SIZE + localX;
2790 const tileX = chunkX * CHUNK_SIZE + localX;
2733 const tileY = chunkY * CHUNK_SIZE + localY;
2791 const tileY = chunkY * CHUNK_SIZE + localY;
@@ -3170,6 +3228,8 @@ export class WorldView
3170 this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK));
3228 this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK));
3171 }
3229 }
3172 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
3230 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
3231 this.#layoutFluidAtlasObject(baked, "ground");
3232 this.#layoutFluidAtlasObject(baked, "bloom");
3173 }
3233 }
3174 // Unbaked tile sprites: tall blocks, doors and animated grounds.
3234 // Unbaked tile sprites: tall blocks, doors and animated grounds.
3175 for (const objects of this.tiles.values())
3235 for (const objects of this.tiles.values())
@@ -3257,6 +3317,12 @@ export class WorldView
3257 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
3317 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
3258 this.#setRendererVisible(baked.groundObject, chunkVisible);
3318 this.#setRendererVisible(baked.groundObject, chunkVisible);
3259 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
3319 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
3320 // Fluid atlas objects are shown/hidden in #syncFluidAtlases; keep offscreen ones off.
3321 if (!chunkVisible)
3322 {
3323 this.#setRendererVisible(baked.fluidGroundObject, false);
3324 this.#setRendererVisible(baked.fluidBloomObject, false);
3325 }
3260 baked._inViewport = chunkVisible;
3326 baked._inViewport = chunkVisible;
3261 for (let row = 0; row < CHUNK_SIZE; row++)
3327 for (let row = 0; row < CHUNK_SIZE; row++)
3262 {
3328 {
@@ -3274,11 +3340,12 @@ export class WorldView
3274 const top = objects.tileY * size;
3340 const top = objects.tileY * size;
3275 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
3341 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
3276 objects._inViewport = visible;
3342 objects._inViewport = visible;
3277 this.#setRendererVisible(objects.ground, visible);
3343 const fluidAtlas = this.#useFluidAtlas && this.#tileUsesFluidAtlas(objects);
3344 this.#setRendererVisible(objects.ground, visible && !fluidAtlas);
3278 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3345 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3279 this.#setRendererVisible(objects.block, visible);
3346 this.#setRendererVisible(objects.block, visible);
3280 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3347 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3281 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled);
3348 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled && !fluidAtlas);
3282 }
3349 }
3283 }
3350 }
3284
3351
@@ -3667,6 +3734,12 @@ export class WorldView
3667 {
3734 {
3668 renderer.shaderUniforms = {};
3735 renderer.shaderUniforms = {};
3669 renderer._shaderUniformKind = kind;
3736 renderer._shaderUniformKind = kind;
3737 renderer._fluidStaticsReady = false;
3738 // Static water/lava tune uniforms — apply once per kind, not every frame.
3739 if (kind === "water")
3740 { Object.assign(renderer.shaderUniforms, waterDebugUniforms()); }
3741 else if (kind === "lava" || kind === "lavaBloom")
3742 { Object.assign(renderer.shaderUniforms, lavaDebugUniforms()); }
3670 }
3743 }
3671 return renderer.shaderUniforms;
3744 return renderer.shaderUniforms;
3672 }
3745 }
@@ -4070,7 +4143,8 @@ export class WorldView
4070 fallbackLit = 1,
4143 fallbackLit = 1,
4071 tileX = 0,
4144 tileX = 0,
4072 tileY = 0,
4145 tileY = 0,
4073 deepCorners = null
4146 deepCorners = null,
4147 staticsDirty = true
4074 } = {})
4148 } = {})
4075 {
4149 {
4076 if (!object?.renderer)
4150 if (!object?.renderer)
@@ -4082,6 +4156,17 @@ export class WorldView
4082 se: fallbackLit
4156 se: fallbackLit
4083 };
4157 };
4084 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4158 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4159 object._lit = true;
4160 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4161 // Dynamic every frame: time + lighting.
4162 uniforms.u_ambientDark = dark;
4163 uniforms.u_litNW = lit.nw;
4164 uniforms.u_litNE = lit.ne;
4165 uniforms.u_litSW = lit.sw;
4166 uniforms.u_litSE = lit.se;
4167 uniforms.u_time = timeSec;
4168 if (!staticsDirty && object.renderer._fluidStaticsReady)
4169 { return; }
4085 const shoreSprite = shore?.sprite ?? null;
4170 const shoreSprite = shore?.sprite ?? null;
4086 const shoreUv = shoreSprite?.getUvRect?.(0)
4171 const shoreUv = shoreSprite?.getUvRect?.(0)
4087 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4172 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
@@ -4089,19 +4174,11 @@ export class WorldView
4089 const dNE = deepCorners?.ne ?? 0;
4174 const dNE = deepCorners?.ne ?? 0;
4090 const dSW = deepCorners?.sw ?? 0;
4175 const dSW = deepCorners?.sw ?? 0;
4091 const dSE = deepCorners?.se ?? 0;
4176 const dSE = deepCorners?.se ?? 0;
4092 object._lit = true;
4093 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
4177 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
4094 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
4178 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
4095 if (sharedNoise)
4179 if (sharedNoise)
4096 { object.renderer.sprite = sharedNoise; }
4180 { object.renderer.sprite = sharedNoise; }
4097 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4181 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4098 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4099 uniforms.u_ambientDark = dark;
4100 uniforms.u_litNW = lit.nw;
4101 uniforms.u_litNE = lit.ne;
4102 uniforms.u_litSW = lit.sw;
4103 uniforms.u_litSE = lit.se;
4104 uniforms.u_time = timeSec;
4105 uniforms.u_tileX = tileX | 0;
4182 uniforms.u_tileX = tileX | 0;
4106 uniforms.u_tileY = tileY | 0;
4183 uniforms.u_tileY = tileY | 0;
4107 uniforms.u_deepNW = dNW;
4184 uniforms.u_deepNW = dNW;
@@ -4126,7 +4203,7 @@ export class WorldView
4126 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4203 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4127 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4204 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4128 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4205 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4129 Object.assign(uniforms, waterDebugUniforms());
4206 object.renderer._fluidStaticsReady = true;
4130 }
4207 }
4131
4208
4132 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
4209 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
@@ -4165,19 +4242,19 @@ export class WorldView
4165 else
4242 else
4166 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4243 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4167 }
4244 }
4168 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4245 const coast = this.#cachedWaterCoast(objects);
4169 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges);
4246 objects.waterEdges = coast.edges;
4170 const deep = objects.groundTypeId === GroundType.deepWater;
4171 this.#syncWaterGroundSprite(objects.ground, {
4247 this.#syncWaterGroundSprite(objects.ground, {
4172 corners: litCorners,
4248 corners: litCorners,
4173 ambientDark,
4249 ambientDark,
4174 edges: objects.waterEdges,
4250 edges: coast.edges,
4175 shore,
4251 shore: coast.shore,
4176 timeSec,
4252 timeSec,
4177 fallbackLit,
4253 fallbackLit,
4178 tileX: objects.tileX,
4254 tileX: objects.tileX,
4179 tileY: objects.tileY,
4255 tileY: objects.tileY,
4180 deepCorners: this.#waterDeepCorners(objects.tileX, objects.tileY, deep)
4256 deepCorners: coast.deepCorners,
4257 staticsDirty: coast.staticsDirty
4181 });
4258 });
4182 }
4259 }
4183
4260
@@ -4258,26 +4335,27 @@ export class WorldView
4258 else
4335 else
4259 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4336 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4260 }
4337 }
4261 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4338 const coast = this.#cachedLavaCoast(objects);
4262 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4263 this.#syncLavaGroundSprite(objects.ground, {
4339 this.#syncLavaGroundSprite(objects.ground, {
4264 corners: litCorners,
4340 corners: litCorners,
4265 ambientDark,
4341 ambientDark,
4266 edges,
4342 edges: coast.edges,
4267 shore,
4343 shore: coast.shore,
4268 timeSec,
4344 timeSec,
4269 fallbackLit,
4345 fallbackLit,
4270 tileX: objects.tileX,
4346 tileX: objects.tileX,
4271 tileY: objects.tileY
4347 tileY: objects.tileY,
4348 staticsDirty: coast.staticsDirty
4272 });
4349 });
4273 const bloom = this.#ensureLavaBloom(objects);
4350 const bloom = this.#ensureLavaBloom(objects);
4274 if (bloom)
4351 if (bloom)
4275 {
4352 {
4276 this.#syncLavaBloomSprite(bloom, {
4353 this.#syncLavaBloomSprite(bloom, {
4277 edges,
4354 edges: coast.edges,
4278 timeSec,
4355 timeSec,
4279 tileX: objects.tileX,
4356 tileX: objects.tileX,
4280 tileY: objects.tileY
4357 tileY: objects.tileY,
4358 staticsDirty: coast.staticsDirty
4281 });
4359 });
4282 }
4360 }
4283 }
4361 }
@@ -4290,7 +4368,8 @@ export class WorldView
4290 timeSec = 0,
4368 timeSec = 0,
4291 fallbackLit = 1,
4369 fallbackLit = 1,
4292 tileX = 0,
4370 tileX = 0,
4293 tileY = 0
4371 tileY = 0,
4372 staticsDirty = true
4294 } = {})
4373 } = {})
4295 {
4374 {
4296 if (!object?.renderer)
4375 if (!object?.renderer)
@@ -4302,11 +4381,7 @@ export class WorldView
4302 se: fallbackLit
4381 se: fallbackLit
4303 };
4382 };
4304 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4383 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4305 const shoreSprite = shore?.sprite ?? null;
4306 const shoreUv = shoreSprite?.getUvRect?.(0)
4307 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4308 object._lit = true;
4384 object._lit = true;
4309 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4310 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4385 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4311 uniforms.u_ambientDark = dark;
4386 uniforms.u_ambientDark = dark;
4312 uniforms.u_litNW = lit.nw;
4387 uniforms.u_litNW = lit.nw;
@@ -4314,6 +4389,12 @@ export class WorldView
4314 uniforms.u_litSW = lit.sw;
4389 uniforms.u_litSW = lit.sw;
4315 uniforms.u_litSE = lit.se;
4390 uniforms.u_litSE = lit.se;
4316 uniforms.u_time = timeSec;
4391 uniforms.u_time = timeSec;
4392 if (!staticsDirty && object.renderer._fluidStaticsReady)
4393 { return; }
4394 const shoreSprite = shore?.sprite ?? null;
4395 const shoreUv = shoreSprite?.getUvRect?.(0)
4396 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4397 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4317 uniforms.u_tileX = tileX | 0;
4398 uniforms.u_tileX = tileX | 0;
4318 uniforms.u_tileY = tileY | 0;
4399 uniforms.u_tileY = tileY | 0;
4319 uniforms.u_edgeN = edges?.n ?? 0;
4400 uniforms.u_edgeN = edges?.n ?? 0;
@@ -4334,20 +4415,23 @@ export class WorldView
4334 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4415 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4335 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4416 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4336 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4417 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4337 Object.assign(uniforms, lavaDebugUniforms());
4418 object.renderer._fluidStaticsReady = true;
4338 }
4419 }
4339
4420
4340 #syncLavaBloomSprite (object, {
4421 #syncLavaBloomSprite (object, {
4341 edges = null,
4422 edges = null,
4342 timeSec = 0,
4423 timeSec = 0,
4343 tileX = 0,
4424 tileX = 0,
4344 tileY = 0
4425 tileY = 0,
4426 staticsDirty = true
4345 } = {})
4427 } = {})
4346 {
4428 {
4347 if (!object?.renderer)
4429 if (!object?.renderer)
4348 { return; }
4430 { return; }
4349 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4431 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4350 uniforms.u_time = timeSec;
4432 uniforms.u_time = timeSec;
4433 if (!staticsDirty && object.renderer._fluidStaticsReady)
4434 { return; }
4351 uniforms.u_tileX = tileX | 0;
4435 uniforms.u_tileX = tileX | 0;
4352 uniforms.u_tileY = tileY | 0;
4436 uniforms.u_tileY = tileY | 0;
4353 uniforms.u_edgeN = edges?.n ?? 0;
4437 uniforms.u_edgeN = edges?.n ?? 0;
@@ -4358,7 +4442,496 @@ export class WorldView
4358 uniforms.u_edgeNW = edges?.nw ?? 0;
4442 uniforms.u_edgeNW = edges?.nw ?? 0;
4359 uniforms.u_edgeSE = edges?.se ?? 0;
4443 uniforms.u_edgeSE = edges?.se ?? 0;
4360 uniforms.u_edgeSW = edges?.sw ?? 0;
4444 uniforms.u_edgeSW = edges?.sw ?? 0;
4361 Object.assign(uniforms, lavaDebugUniforms());
4445 object.renderer._fluidStaticsReady = true;
4446 }
4447
4448
4449 #cachedWaterCoast (objects)
4450 {
4451 const epoch = this.#fluidCoastEpoch;
4452 const typeId = objects.groundTypeId;
4453 const season = this.worldSeason;
4454 const cache = objects._fluidCoastCache;
4455 if (
4456 cache
4457 && cache.epoch === epoch
4458 && cache.typeId === typeId
4459 && cache.season === season
4460 && cache.kind === "water"
4461 )
4462 { return { edges: cache.edges, shore: cache.shore, deepCorners: cache.deepCorners, staticsDirty: false }; }
4463 const edges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4464 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, edges);
4465 const deep = typeId === GroundType.deepWater;
4466 const deepCorners = this.#waterDeepCorners(objects.tileX, objects.tileY, deep);
4467 objects._fluidCoastCache = { epoch, typeId, season, kind: "water", edges, shore, deepCorners };
4468 if (objects.ground?.renderer)
4469 { objects.ground.renderer._fluidStaticsReady = false; }
4470 return { edges, shore, deepCorners, staticsDirty: true };
4471 }
4472
4473 #cachedLavaCoast (objects)
4474 {
4475 const epoch = this.#fluidCoastEpoch;
4476 const typeId = objects.groundTypeId;
4477 const season = this.worldSeason;
4478 const cache = objects._fluidCoastCache;
4479 if (
4480 cache
4481 && cache.epoch === epoch
4482 && cache.typeId === typeId
4483 && cache.season === season
4484 && cache.kind === "lava"
4485 )
4486 { return { edges: cache.edges, shore: cache.shore, staticsDirty: false }; }
4487 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4488 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4489 objects._fluidCoastCache = { epoch, typeId, season, kind: "lava", edges, shore, deepCorners: null };
4490 if (objects.ground?.renderer)
4491 { objects.ground.renderer._fluidStaticsReady = false; }
4492 if (objects.lavaBloom?.renderer)
4493 { objects.lavaBloom.renderer._fluidStaticsReady = false; }
4494 return { edges, shore, staticsDirty: true };
4495 }
4496
4497 #tileUsesFluidAtlas (objects)
4498 {
4499 if (!objects?.groundTypeId)
4500 { return false; }
4501 if (isLavaGround(objects.groundTypeId))
4502 { return true; }
4503 return isLiquidWaterGround(objects.groundTypeId, this.worldSeason);
4504 }
4505
4506 #ensureFluidAtlasSlot (baked, kind)
4507 {
4508 const glCtx = this.scene?.glContext;
4509 if (!glCtx?.gl || !baked)
4510 { return null; }
4511 const key = kind === "bloom" ? "_fluidBloomTarget" : "_fluidGroundTarget";
4512 const objKey = kind === "bloom" ? "fluidBloomObject" : "fluidGroundObject";
4513 if (!baked[key])
4514 {
4515 const target = createFluidAtlasTarget(glCtx);
4516 if (!target)
4517 {
4518 this.#useFluidAtlas = false;
4519 return null;
4520 }
4521 baked[key] = target;
4522 setNearestFilter(this.scene, target.canvas);
4523 }
4524 const target = baked[key];
4525 if (!baked[objKey])
4526 {
4527 const object = new GameObject(0, 0, target.image, LAYER_GROUND);
4528 if (kind === "bloom")
4529 {
4530 object.renderer.layer = RENDER_LAYER_BLOOM;
4531 }
4532 this.#markUnlit(object);
4533 this.scene.addObject(object);
4534 baked[objKey] = object;
4535 this.#layoutFluidAtlasObject(baked, kind);
4536 }
4537 else if (baked[objKey].renderer)
4538 { baked[objKey].renderer.sprite = target.image; }
4539 return { target, object: baked[objKey] };
4540 }
4541
4542 #layoutFluidAtlasObject (baked, kind = "ground")
4543 {
4544 const object = kind === "bloom" ? baked.fluidBloomObject : baked.fluidGroundObject;
4545 if (!object || baked.chunkX == null || baked.chunkY == null)
4546 { return; }
4547 const size = this.tileSize();
4548 const layoutKey = `${baked.chunkX},${baked.chunkY},${size},${kind}`;
4549 if (baked._fluidLayoutKey === layoutKey && object.renderer?.mirrorY)
4550 { return; }
4551 baked._fluidLayoutKey = layoutKey;
4552 const left = baked.chunkX * CHUNK_SIZE * size;
4553 const top = baked.chunkY * CHUNK_SIZE * size;
4554 const chunkPx = CHUNK_SIZE * size;
4555 // Pixel-snap: subpixel atlas placement + NEAREST causes grid cracks.
4556 object.transform.position.x = Math.round(left + chunkPx / 2);
4557 object.transform.position.y = Math.round(top + chunkPx / 2);
4558 object.transform.size = new vector(chunkPx, chunkPx);
4559 // FBO color attachment is V-flipped vs Framework sprite UVs — one atlas
4560 // mirrorY restores N/S hole placement without breaking noise continuity.
4561 if (object.renderer)
4562 { object.renderer.mirrorY = true; }
4563 if (kind === "bloom")
4564 {
4565 this.#setLayer(object, this.#depthLayer(top + chunkPx, SORT_BLOCK));
4566 object.renderer.layer = RENDER_LAYER_BLOOM;
4567 }
4568 else
4569 { this.#setLayer(object, LAYER_GROUND); }
4570 }
4571
4572 #destroyFluidAtlasSlot (baked)
4573 {
4574 const glCtx = this.scene?.glContext;
4575 if (!baked)
4576 { return; }
4577 baked.fluidGroundObject?.destroy();
4578 baked.fluidGroundObject = null;
4579 baked.fluidBloomObject?.destroy();
4580 baked.fluidBloomObject = null;
4581 destroyFluidAtlasTarget(glCtx, baked._fluidGroundTarget);
4582 destroyFluidAtlasTarget(glCtx, baked._fluidBloomTarget);
4583 destroyFluidPackSet(glCtx, baked._fluidPacks);
4584 baked._fluidGroundTarget = null;
4585 baked._fluidBloomTarget = null;
4586 baked._fluidPacks = null;
4587 }
4588
4589 #ensureFluidPacks (baked)
4590 {
4591 const glCtx = this.scene?.glContext;
4592 if (!glCtx?.gl || !baked)
4593 { return null; }
4594 if (!baked._fluidPacks)
4595 {
4596 const packs = createFluidPackSet(glCtx);
4597 if (!packs)
4598 { return null; }
4599 baked._fluidPacks = packs;
4600 }
4601 return baked._fluidPacks;
4602 }
4603
4604 #fluidAtlasSinglePassEnabled ()
4605 {
4606 if (!this.#useFluidAtlasSinglePass)
4607 { return false; }
4608 if (globalThis.__QW_FLUID_ATLAS_SINGLE_PASS === false)
4609 { return false; }
4610 return true;
4611 }
4612
4613 /**
4614 * Render liquid water + lava into per-chunk 16×16 atlases; hide per-tile fluid sprites.
4615 * Lighting/time uniforms stay on the (hidden) tile renderers and are sampled here.
4616 */
4617 #syncFluidAtlases ()
4618 {
4619 if (!this.#useFluidAtlas)
4620 { return; }
4621 const glCtx = this.scene?.glContext;
4622 if (!glCtx?.gl)
4623 { return; }
4624
4625 const byChunk = new Map();
4626 for (const objects of this.tiles.values())
4627 {
4628 if (!objects.ground)
4629 { continue; }
4630 if (!this.#tileUsesFluidAtlas(objects))
4631 { continue; }
4632 // Hide per-tile fluid sprites (keep objects + uniforms for atlas + lighting data).
4633 if (!objects._fluidAtlasHidden)
4634 {
4635 this.#setRendererVisible(objects.ground, false);
4636 this.#setRendererVisible(objects.lavaBloom, false);
4637 objects._fluidAtlasHidden = true;
4638 }
4639 if (objects._inViewport === false)
4640 { continue; }
4641 const key = `${objects.chunkX},${objects.chunkY}`;
4642 let list = byChunk.get(key);
4643 if (!list)
4644 {
4645 list = [];
4646 byChunk.set(key, list);
4647 }
4648 list.push(objects);
4649 }
4650
4651 const active = new Set();
4652 for (const [key, list] of byChunk)
4653 {
4654 const baked = this.bakedChunks.get(key);
4655 if (!baked || baked._inViewport === false)
4656 { continue; }
4657 active.add(key);
4658 this.#renderFluidAtlasChunk(baked, list);
4659 }
4660
4661 for (const baked of this.bakedChunks.values())
4662 {
4663 const key = `${baked.chunkX},${baked.chunkY}`;
4664 if (active.has(key))
4665 { continue; }
4666 this.#setRendererVisible(baked.fluidGroundObject, false);
4667 this.#setRendererVisible(baked.fluidBloomObject, false);
4668 }
4669 }
4670
4671 #showFluidTilesFallback (tileObjects)
4672 {
4673 for (const objects of tileObjects)
4674 {
4675 const vis = objects._inViewport !== false;
4676 objects._fluidAtlasHidden = false;
4677 this.#setRendererVisible(objects.ground, vis);
4678 this.#setRendererVisible(objects.lavaBloom, vis && this.bloomEnabled);
4679 }
4680 }
4681
4682 #renderFluidAtlasChunk (baked, tileObjects)
4683 {
4684 const glCtx = this.scene?.glContext;
4685 const groundSlot = this.#ensureFluidAtlasSlot(baked, "ground");
4686 if (!groundSlot || !this.#useFluidAtlas)
4687 {
4688 this.#showFluidTilesFallback(tileObjects);
4689 return;
4690 }
4691
4692 const usedSingle = this.#fluidAtlasSinglePassEnabled()
4693 && this.#renderFluidAtlasChunkSinglePass(baked, tileObjects, groundSlot);
4694 if (!usedSingle)
4695 { this.#renderFluidAtlasChunkPerTile(baked, tileObjects, groundSlot); }
4696 }
4697
4698 #renderFluidAtlasChunkPerTile (baked, tileObjects, groundSlot)
4699 {
4700 const glCtx = this.scene?.glContext;
4701 const bloomTiles = [];
4702 withFluidAtlasPass(glCtx, groundSlot.target, () =>
4703 {
4704 for (const objects of tileObjects)
4705 {
4706 const renderer = objects.ground?.renderer;
4707 if (!renderer?.shader || !renderer.shaderUniforms || !renderer.sprite?.g_image)
4708 { continue; }
4709 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4710 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4711 drawFluidAtlasTile(glCtx, {
4712 textureHtml: renderer.sprite.g_image,
4713 secondaryHtml: renderer.secondaryMap ?? null,
4714 localX,
4715 localY,
4716 shader: renderer.shader,
4717 uniforms: renderer.shaderUniforms,
4718 uvRect: renderer.sprite.getUvRect?.(renderer.subImage | 0) ?? null
4719 });
4720 if (objects.lavaBloom?.renderer?.shader)
4721 { bloomTiles.push(objects); }
4722 }
4723 });
4724 this.#layoutFluidAtlasObject(baked, "ground");
4725 this.#setRendererVisible(groundSlot.object, true);
4726
4727 if (!bloomTiles.length || !this.bloomEnabled)
4728 {
4729 this.#setRendererVisible(baked.fluidBloomObject, false);
4730 return;
4731 }
4732
4733 const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom");
4734 if (!bloomSlot || !this.#useFluidAtlas)
4735 { return; }
4736 withFluidAtlasPass(glCtx, bloomSlot.target, () =>
4737 {
4738 for (const objects of bloomTiles)
4739 {
4740 const renderer = objects.lavaBloom?.renderer;
4741 if (!renderer?.shader || !renderer.shaderUniforms)
4742 { continue; }
4743 const tex = renderer.sprite?.g_image ?? objects.ground?.renderer?.sprite?.g_image;
4744 if (!tex)
4745 { continue; }
4746 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4747 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4748 drawFluidAtlasTile(glCtx, {
4749 textureHtml: tex,
4750 secondaryHtml: null,
4751 localX,
4752 localY,
4753 shader: renderer.shader,
4754 uniforms: renderer.shaderUniforms,
4755 uvRect: renderer.sprite?.getUvRect?.(renderer.subImage | 0) ?? null
4756 });
4757 }
4758 });
4759 this.#layoutFluidAtlasObject(baked, "bloom");
4760 this.#setRendererVisible(bloomSlot.object, true);
4761 }
4762
4763 /**
4764 * Pack per-tile uniforms into 16×16 textures and bake with 1–2 chunk draws.
4765 * @returns {boolean} true when single-pass succeeded
4766 */
4767 #renderFluidAtlasChunkSinglePass (baked, tileObjects, groundSlot)
4768 {
4769 const glCtx = this.scene?.glContext;
4770 const packs = this.#ensureFluidPacks(baked);
4771 if (!packs || !glCtx?.gl)
4772 { return false; }
4773
4774 const waterShader = getWaterAtlasChunkShader();
4775 const lavaShader = getLavaAtlasChunkShader();
4776 const bloomShader = getLavaBloomAtlasChunkShader();
4777 if (!waterShader?.getProgramInfo(glCtx.gl)
4778 || !lavaShader?.getProgramInfo(glCtx.gl)
4779 || !bloomShader?.getProgramInfo(glCtx.gl))
4780 { return false; }
4781
4782 clearFluidPackPixels(packs);
4783 const waterTiles = [];
4784 const lavaTiles = [];
4785 const bloomTiles = [];
4786 let waterNoise = null;
4787 let lavaNoise = null;
4788 let waterSecondary = null;
4789 let lavaSecondary = null;
4790 let waterUniforms = null;
4791 let lavaUniforms = null;
4792 let bloomUniforms = null;
4793 let ambientDark = 0;
4794 let timeSec = 0;
4795
4796 for (const objects of tileObjects)
4797 {
4798 const renderer = objects.ground?.renderer;
4799 if (!renderer?.shaderUniforms || !renderer.sprite?.g_image)
4800 { continue; }
4801 const kindName = renderer._shaderUniformKind;
4802 const kind = kindName === "lava" ? FLUID_KIND_LAVA
4803 : kindName === "water" ? FLUID_KIND_WATER
4804 : null;
4805 if (!kind)
4806 { continue; }
4807 const localX = objects.tileX - baked.chunkX * CHUNK_SIZE;
4808 const localY = objects.tileY - baked.chunkY * CHUNK_SIZE;
4809 writeFluidPackTile(packs, localX, localY, kind, renderer.shaderUniforms);
4810 const noise = renderer.sprite.g_image;
4811 const secondary = renderer.secondaryMap ?? null;
4812 const u = renderer.shaderUniforms;
4813 ambientDark = u.u_ambientDark ?? ambientDark;
4814 timeSec = u.u_time ?? timeSec;
4815 if (kind === FLUID_KIND_WATER)
4816 {
4817 waterTiles.push(objects);
4818 if (!waterNoise)
4819 { waterNoise = noise; }
4820 else if (waterNoise !== noise)
4821 { return false; }
4822 if (secondary)
4823 {
4824 if (!waterSecondary)
4825 { waterSecondary = secondary; }
4826 else if (waterSecondary !== secondary)
4827 { return false; }
4828 }
4829 if (!waterUniforms)
4830 { waterUniforms = u; }
4831 }
4832 else
4833 {
4834 lavaTiles.push(objects);
4835 if (!lavaNoise)
4836 { lavaNoise = noise; }
4837 else if (lavaNoise !== noise)
4838 { return false; }
4839 if (secondary)
4840 {
4841 if (!lavaSecondary)
4842 { lavaSecondary = secondary; }
4843 else if (lavaSecondary !== secondary)
4844 { return false; }
4845 }
4846 if (!lavaUniforms)
4847 { lavaUniforms = u; }
4848 if (objects.lavaBloom?.renderer?.shaderUniforms)
4849 {
4850 bloomTiles.push(objects);
4851 if (!bloomUniforms)
4852 { bloomUniforms = objects.lavaBloom.renderer.shaderUniforms; }
4853 }
4854 }
4855 }
4856
4857 if (!waterTiles.length && !lavaTiles.length)
4858 { return false; }
4859
4860 uploadFluidPacks(glCtx, packs);
4861 const chunkOriginX = baked.chunkX * CHUNK_SIZE;
4862 const chunkOriginY = baked.chunkY * CHUNK_SIZE;
4863
4864 withFluidAtlasPass(glCtx, groundSlot.target, () =>
4865 {
4866 if (waterTiles.length && waterNoise && waterUniforms)
4867 {
4868 drawFluidAtlasChunkPass(glCtx, {
4869 textureHtml: waterNoise,
4870 secondaryHtml: waterSecondary,
4871 shader: waterShader,
4872 uniforms: {
4873 ...waterDebugUniforms(),
4874 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4875 u_time: timeSec,
4876 u_ambientDark: ambientDark,
4877 u_alpha: 1
4878 },
4879 packs,
4880 kindFilter: FLUID_KIND_WATER,
4881 includeShorePacks: true
4882 });
4883 }
4884 if (lavaTiles.length && lavaNoise && lavaUniforms)
4885 {
4886 drawFluidAtlasChunkPass(glCtx, {
4887 textureHtml: lavaNoise,
4888 secondaryHtml: lavaSecondary,
4889 shader: lavaShader,
4890 uniforms: {
4891 ...lavaDebugUniforms(),
4892 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4893 u_time: timeSec,
4894 u_ambientDark: ambientDark,
4895 u_alpha: 1
4896 },
4897 packs,
4898 kindFilter: FLUID_KIND_LAVA,
4899 includeShorePacks: true
4900 });
4901 }
4902 });
4903 this.#layoutFluidAtlasObject(baked, "ground");
4904 this.#setRendererVisible(groundSlot.object, true);
4905
4906 if (!bloomTiles.length || !this.bloomEnabled || !bloomUniforms || !lavaNoise)
4907 {
4908 this.#setRendererVisible(baked.fluidBloomObject, false);
4909 return true;
4910 }
4911
4912 const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom");
4913 if (!bloomSlot || !this.#useFluidAtlas)
4914 { return true; }
4915 withFluidAtlasPass(glCtx, bloomSlot.target, () =>
4916 {
4917 drawFluidAtlasChunkPass(glCtx, {
4918 textureHtml: lavaNoise,
4919 secondaryHtml: null,
4920 shader: bloomShader,
4921 uniforms: {
4922 ...lavaDebugUniforms(),
4923 u_chunkOrigin: [chunkOriginX, chunkOriginY],
4924 u_time: bloomUniforms.u_time ?? timeSec,
4925 u_alpha: 1
4926 },
4927 packs,
4928 kindFilter: FLUID_KIND_LAVA,
4929 includeShorePacks: false
4930 });
4931 });
4932 this.#layoutFluidAtlasObject(baked, "bloom");
4933 this.#setRendererVisible(bloomSlot.object, true);
4934 return true;
4362 }
4935 }
4363
4936
4364 #ambientDarkness ()
4937 #ambientDarkness ()
@@ -4940,6 +5513,7 @@ export class WorldView
4940
5513
4941 #bakeAndPlaceChunk (snapshot)
5514 #bakeAndPlaceChunk (snapshot)
4942 {
5515 {
5516 this.#fluidCoastEpoch = (this.#fluidCoastEpoch + 1) | 0;
4943 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5517 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4944 const atlases = bakeChunkAtlases({
5518 const atlases = bakeChunkAtlases({
4945 snapshot,
5519 snapshot,
@@ -5359,6 +5933,8 @@ export class WorldView
5359 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
5933 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
5360 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
5934 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
5361 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
5935 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
5936 this.#layoutFluidAtlasObject(baked, "ground");
5937 this.#layoutFluidAtlasObject(baked, "bloom");
5362 }
5938 }
5363
5939
5364 #destroyBakedChunk (key)
5940 #destroyBakedChunk (key)
@@ -5367,6 +5943,7 @@ export class WorldView
5367 if (!baked)
5943 if (!baked)
5368 { return; }
5944 { return; }
5369 this.#releaseBakedAtlasRefs(baked);
5945 this.#releaseBakedAtlasRefs(baked);
5946 this.#destroyFluidAtlasSlot(baked);
5370 baked.groundObject?.destroy();
5947 baked.groundObject?.destroy();
5371 for (const object of baked.blockObjects ?? [])
5948 for (const object of baked.blockObjects ?? [])
5372 { object.destroy(); }
5949 { object.destroy(); }
@@ -5457,6 +6034,8 @@ export class WorldView
5457 this.#clearLavaBloom(objects);
6034 this.#clearLavaBloom(objects);
5458 objects.groundTypeId = null;
6035 objects.groundTypeId = null;
5459 objects.waterEdges = null;
6036 objects.waterEdges = null;
6037 objects._fluidCoastCache = null;
6038 objects._fluidAtlasHidden = false;
5460 }
6039 }
5461
6040
5462 let blockSource = snapshot.blocks[index];
6041 let blockSource = snapshot.blocks[index];
@@ -5626,9 +6205,21 @@ export class WorldView
5626 let bars = this.edges.get(key);
6205 let bars = this.edges.get(key);
5627 if (!bars)
6206 if (!bars)
5628 {
6207 {
5629 bars = {};
6208 bars = { north: [], south: [], west: [], east: [], full: {} };
5630 this.edges.set(key, bars);
6209 this.edges.set(key, bars);
5631 }
6210 }
6211 if (!Array.isArray(bars.north))
6212 {
6213 // Migrate legacy single-bar shape from earlier sessions.
6214 for (const dir of ["north", "south", "west", "east"])
6215 {
6216 const legacy = bars[dir];
6217 if (legacy && !Array.isArray(legacy))
6218 { legacy.destroy?.(); }
6219 bars[dir] = [];
6220 }
6221 bars.full = bars.full ?? {};
6222 }
5632
6223
5633 const size = this.tileSize();
6224 const size = this.tileSize();
5634 const chunkPx = CHUNK_SIZE * size;
6225 const chunkPx = CHUNK_SIZE * size;
@@ -5638,15 +6229,103 @@ export class WorldView
5638 const centerY = top + chunkPx / 2;
6229 const centerY = top + chunkPx / 2;
5639 const thickness = Math.max(2, Math.round(2 * this.zoom));
6230 const thickness = Math.max(2, Math.round(2 * this.zoom));
5640 const draw = snapshot.open === true;
6231 const draw = snapshot.open === true;
6232 const walkableOnly = this.worldBorderWalkableOnly === true;
6233
6234 const northClosed = draw && this.#neighborClosed(snapshot, "north", 0, -1);
6235 const southClosed = draw && this.#neighborClosed(snapshot, "south", 0, 1);
6236 const westClosed = draw && this.#neighborClosed(snapshot, "west", -1, 0);
6237 const eastClosed = draw && this.#neighborClosed(snapshot, "east", 1, 0);
6238
6239 if (!walkableOnly)
6240 {
6241 this.#hideEdgeList(bars.north);
6242 this.#hideEdgeList(bars.south);
6243 this.#hideEdgeList(bars.west);
6244 this.#hideEdgeList(bars.east);
6245 bars.full.north = this.#edgeBar(bars.full.north, northClosed,
6246 centerX, top, chunkPx, thickness, true);
6247 bars.full.south = this.#edgeBar(bars.full.south, southClosed,
6248 centerX, top + chunkPx, chunkPx, thickness, true);
6249 bars.full.west = this.#edgeBar(bars.full.west, westClosed,
6250 left, centerY, chunkPx, thickness, false);
6251 bars.full.east = this.#edgeBar(bars.full.east, eastClosed,
6252 left + chunkPx, centerY, chunkPx, thickness, false);
6253 return;
6254 }
5641
6255
5642 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
6256 for (const dir of ["north", "south", "west", "east"])
5643 centerX, top, chunkPx, thickness, true);
6257 {
5644 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
6258 if (bars.full?.[dir])
5645 centerX, top + chunkPx, chunkPx, thickness, true);
6259 {
5646 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
6260 bars.full[dir].renderer.visible = false;
5647 left, centerY, chunkPx, thickness, false);
6261 }
5648 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
6262 }
5649 left + chunkPx, centerY, chunkPx, thickness, false);
6263
6264 bars.north = this.#edgeTileBars(bars.north, northClosed, snapshot, "north", left, top, size, thickness);
6265 bars.south = this.#edgeTileBars(bars.south, southClosed, snapshot, "south", left, top, size, thickness);
6266 bars.west = this.#edgeTileBars(bars.west, westClosed, snapshot, "west", left, top, size, thickness);
6267 bars.east = this.#edgeTileBars(bars.east, eastClosed, snapshot, "east", left, top, size, thickness);
6268 }
6269
6270 /** True when a player can walk the authored tile (doors closed = blocked). */
6271 #tileWalkableOnSnapshot (snapshot, localX, localY)
6272 {
6273 const index = localY * CHUNK_SIZE + localX;
6274 const ground = normalizeGround(snapshot.grounds?.[index]);
6275 if (!isGroundPassable(ground.typeId))
6276 { return false; }
6277 const block = snapshot.blocks?.[index];
6278 if (!block)
6279 { return true; }
6280 const def = blockDefinition(block.typeId);
6281 if (def?.door)
6282 { return isDoorTraversable(block, { canOpenDoors: false, requirementsAllow: true }); }
6283 return isBlockPassable(block.typeId, block.state);
6284 }
6285
6286 #edgeTileBars (list, active, snapshot, dir, left, top, size, thickness)
6287 {
6288 const out = Array.isArray(list) ? list : [];
6289 if (!active)
6290 {
6291 this.#hideEdgeList(out);
6292 return out;
6293 }
6294 let used = 0;
6295 for (let i = 0; i < CHUNK_SIZE; i++)
6296 {
6297 const localX = (dir === "north" || dir === "south") ? i : (dir === "west" ? 0 : CHUNK_SIZE - 1);
6298 const localY = (dir === "west" || dir === "east") ? i : (dir === "north" ? 0 : CHUNK_SIZE - 1);
6299 if (!this.#tileWalkableOnSnapshot(snapshot, localX, localY))
6300 { continue; }
6301 const horizontal = dir === "north" || dir === "south";
6302 const x = horizontal
6303 ? left + (localX + 0.5) * size
6304 : (dir === "west" ? left : left + CHUNK_SIZE * size);
6305 const y = horizontal
6306 ? (dir === "north" ? top : top + CHUNK_SIZE * size)
6307 : top + (localY + 0.5) * size;
6308 out[used] = this.#edgeBar(out[used], true, x, y, size, thickness, horizontal);
6309 used += 1;
6310 }
6311 for (let i = used; i < out.length; i++)
6312 {
6313 if (out[i])
6314 { out[i].renderer.visible = false; }
6315 }
6316 out.length = Math.max(used, out.length);
6317 return out;
6318 }
6319
6320 #hideEdgeList (list)
6321 {
6322 if (!Array.isArray(list))
6323 { return; }
6324 for (const bar of list)
6325 {
6326 if (bar)
6327 { bar.renderer.visible = false; }
6328 }
5650 }
6329 }
5651
6330
5652 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
6331 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
@@ -5675,10 +6354,18 @@ export class WorldView
5675 const bars = this.edges.get(key);
6354 const bars = this.edges.get(key);
5676 if (!bars)
6355 if (!bars)
5677 { return; }
6356 { return; }
5678 bars.north?.destroy();
6357 for (const dir of ["north", "south", "west", "east"])
5679 bars.east?.destroy();
6358 {
5680 bars.south?.destroy();
6359 const entry = bars[dir];
5681 bars.west?.destroy();
6360 if (Array.isArray(entry))
6361 {
6362 for (const bar of entry)
6363 { bar?.destroy?.(); }
6364 }
6365 else
6366 { entry?.destroy?.(); }
6367 bars.full?.[dir]?.destroy?.();
6368 }
5682 this.edges.delete(key);
6369 this.edges.delete(key);
5683 }
6370 }
5684
6371
@@ -6012,6 +6699,7 @@ export class WorldView
6012 this.#syncLitSprite(objects.ground, objects.shadeAlpha);
6699 this.#syncLitSprite(objects.ground, objects.shadeAlpha);
6013 }
6700 }
6014 }
6701 }
6702 this.#syncFluidAtlases();
6015
6703
6016 for (const item of this.groundItems.values())
6704 for (const item of this.groundItems.values())
6017 {
6705 {
client/ui/editor.css +14 −0
@@ -365,6 +365,20 @@ body>aside {
365 365 color: #9aa3b2;
366 366 }
367 367
368 .dim-combo-invalid .dim-combo-input,
369 .dim-combo-invalid .dim-combo-toggle {
370 border-color: #c62828;
371 }
372
373 .dim-combo-invalid-pulse .dim-combo-input {
374 animation: dim-combo-invalid-blink 0.85s ease-in-out 2;
375 }
376
377 @keyframes dim-combo-invalid-blink {
378 0%, 100% { box-shadow: 0 0 0 0 rgba(198, 40, 40, 0); }
379 50% { box-shadow: 0 0 0 2px rgba(198, 40, 40, 0.85); }
380 }
381
368 382 .dimension-settings {
369 383 display: flex;
370 384 flex-direction: column;
@@ -365,6 +365,20 @@ body>aside {
365 color: #9aa3b2;
365 color: #9aa3b2;
366}
366}
367
367
368.dim-combo-invalid .dim-combo-input,
369.dim-combo-invalid .dim-combo-toggle {
370 border-color: #c62828;
371}
372
373.dim-combo-invalid-pulse .dim-combo-input {
374 animation: dim-combo-invalid-blink 0.85s ease-in-out 2;
375}
376
377@keyframes dim-combo-invalid-blink {
378 0%, 100% { box-shadow: 0 0 0 0 rgba(198, 40, 40, 0); }
379 50% { box-shadow: 0 0 0 2px rgba(198, 40, 40, 0.85); }
380}
381
368.dimension-settings {
382.dimension-settings {
369 display: flex;
383 display: flex;
370 flex-direction: column;
384 flex-direction: column;
server/src/bounty/service.js +7 −5
@@ -232,7 +232,7 @@ export class BountyService
232 232 * Friend / same-account / mob kills leave the bounty untouched.
233 233 * @returns {{ paidCopper: number, victimName: string } | null}
234 234 */
235 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
235 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY, deathDimensionId = null)
236 236 {
237 237 const attackerId = attackerEntityId | 0;
238 238 if (!attackerId)
@@ -275,7 +275,8 @@ export class BountyService
275 275 victimName,
276 276 paidCopper,
277 277 deathTileX,
278 deathTileY
278 deathTileY,
279 deathDimensionId
279 280 });
280 281
281 282 this.simulation.pendingPrivate.push({
@@ -309,10 +310,10 @@ export class BountyService
309 310 };
310 311 }
311 312
312 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
313 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY, deathDimensionId = null })
313 314 {
314 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
315 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
315 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0, deathDimensionId)
316 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0, dimensionId: deathDimensionId };
316 317 const body = bountyPayoutLetterBody({
317 318 killerName,
318 319 victimName,
@@ -324,6 +325,7 @@ export class BountyService
324 325 characterId: killerCharacterId,
325 326 originTileX: office.tileX,
326 327 originTileY: office.tileY,
328 originDimensionId: office.dimensionId,
327 329 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
328 330 body
329 331 });
@@ -232,7 +232,7 @@ export class BountyService
232 * Friend / same-account / mob kills leave the bounty untouched.
232 * Friend / same-account / mob kills leave the bounty untouched.
233 * @returns {{ paidCopper: number, victimName: string } | null}
233 * @returns {{ paidCopper: number, victimName: string } | null}
234 */
234 */
235 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY)
235 settleKill (victimCharacterId, attackerEntityId, deathTileX, deathTileY, deathDimensionId = null)
236 {
236 {
237 const attackerId = attackerEntityId | 0;
237 const attackerId = attackerEntityId | 0;
238 if (!attackerId)
238 if (!attackerId)
@@ -275,7 +275,8 @@ export class BountyService
275 victimName,
275 victimName,
276 paidCopper,
276 paidCopper,
277 deathTileX,
277 deathTileX,
278 deathTileY
278 deathTileY,
279 deathDimensionId
279 });
280 });
280
281
281 this.simulation.pendingPrivate.push({
282 this.simulation.pendingPrivate.push({
@@ -309,10 +310,10 @@ export class BountyService
309 };
310 };
310 }
311 }
311
312
312 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY })
313 #dispatchPayoutLetter ({ killerCharacterId, killerName, victimName, paidCopper, deathTileX, deathTileY, deathDimensionId = null })
313 {
314 {
314 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0)
315 const office = this.courier?.nearestBountyOffice?.(deathTileX | 0, deathTileY | 0, deathDimensionId)
315 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0 };
316 ?? { tileX: deathTileX | 0, tileY: deathTileY | 0, dimensionId: deathDimensionId };
316 const body = bountyPayoutLetterBody({
317 const body = bountyPayoutLetterBody({
317 killerName,
318 killerName,
318 victimName,
319 victimName,
@@ -324,6 +325,7 @@ export class BountyService
324 characterId: killerCharacterId,
325 characterId: killerCharacterId,
325 originTileX: office.tileX,
326 originTileX: office.tileX,
326 originTileY: office.tileY,
327 originTileY: office.tileY,
328 originDimensionId: office.dimensionId,
327 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
329 authorDisplayName: BOUNTY_OFFICE_AUTHOR,
328 body
330 body
329 });
331 });
server/src/combat/combatLogout.js +4 −1
@@ -59,11 +59,13 @@ export function dispatchCombatLogoutBankLetter (simulation, characterId)
59 59 { return; }
60 60 const originTileX = row.tile_x | 0;
61 61 const originTileY = row.tile_y | 0;
62 const bank = simulation.courier.nearestBank?.(originTileX, originTileY);
62 const originDim = row.dimension_id ?? undefined;
63 const bank = simulation.courier.nearestBank?.(originTileX, originTileY, originDim);
63 64 simulation.courier.enqueueSystemLetter({
64 65 characterId,
65 66 originTileX: bank?.tileX ?? originTileX,
66 67 originTileY: bank?.tileY ?? originTileY,
68 originDimensionId: bank?.dimensionId ?? originDim,
67 69 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
68 70 authorOrganization: QUESTWARD_GIFT_ORG,
69 71 body: formatCombatLogoutCowardiceBody()
@@ -79,6 +81,7 @@ export function dispatchChurchOfflineResurrectionLetter (simulation, characterId
79 81 characterId,
80 82 originTileX: altar?.tileX ?? (tileX | 0),
81 83 originTileY: altar?.tileY ?? (tileY | 0),
84 originDimensionId: altar?.dimensionId,
82 85 authorDisplayName: CHURCH_LETTER_AUTHOR,
83 86 body: formatChurchOfflineResurrectionBody()
84 87 });
@@ -59,11 +59,13 @@ export function dispatchCombatLogoutBankLetter (simulation, characterId)
59 { return; }
59 { return; }
60 const originTileX = row.tile_x | 0;
60 const originTileX = row.tile_x | 0;
61 const originTileY = row.tile_y | 0;
61 const originTileY = row.tile_y | 0;
62 const bank = simulation.courier.nearestBank?.(originTileX, originTileY);
62 const originDim = row.dimension_id ?? undefined;
63 const bank = simulation.courier.nearestBank?.(originTileX, originTileY, originDim);
63 simulation.courier.enqueueSystemLetter({
64 simulation.courier.enqueueSystemLetter({
64 characterId,
65 characterId,
65 originTileX: bank?.tileX ?? originTileX,
66 originTileX: bank?.tileX ?? originTileX,
66 originTileY: bank?.tileY ?? originTileY,
67 originTileY: bank?.tileY ?? originTileY,
68 originDimensionId: bank?.dimensionId ?? originDim,
67 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
69 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
68 authorOrganization: QUESTWARD_GIFT_ORG,
70 authorOrganization: QUESTWARD_GIFT_ORG,
69 body: formatCombatLogoutCowardiceBody()
71 body: formatCombatLogoutCowardiceBody()
@@ -79,6 +81,7 @@ export function dispatchChurchOfflineResurrectionLetter (simulation, characterId
79 characterId,
81 characterId,
80 originTileX: altar?.tileX ?? (tileX | 0),
82 originTileX: altar?.tileX ?? (tileX | 0),
81 originTileY: altar?.tileY ?? (tileY | 0),
83 originTileY: altar?.tileY ?? (tileY | 0),
84 originDimensionId: altar?.dimensionId,
82 authorDisplayName: CHURCH_LETTER_AUTHOR,
85 authorDisplayName: CHURCH_LETTER_AUTHOR,
83 body: formatChurchOfflineResurrectionBody()
86 body: formatChurchOfflineResurrectionBody()
84 });
87 });
server/src/combat/service.js +27 −3
@@ -299,6 +299,17 @@ export function ensureMobCombat (ecs, entityId)
299 299 return true;
300 300 }
301 301
302 /** Spawner Passive: take hits but do not enter combat / retaliate. Aggressive overrides. */
303 export function entityIsPassive (ecs, handle)
304 {
305 const origin = ecs.get(handle, Component.spawnOrigin);
306 if (!origin?.passive)
307 { return false; }
308 if (origin.aggressive)
309 { return false; }
310 return true;
311 }
312
302 313 function attackerSkillLevel (skills, profile, skillId)
303 314 {
304 315 if (profile.mobAttackSkill != null)
@@ -2264,7 +2275,12 @@ function applyLocalMeleeHit (
2264 2275 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
2265 2276
2266 2277 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
2267 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
2278 // Passive spawners take hits but do not fight back.
2279 if (
2280 attackerIsPlayer === true
2281 && !entityIsPassive(world.ecs, targetHandle)
2282 && ensureMobCombat(world.ecs, targetId)
2283 )
2268 2284 {
2269 2285 engageTarget(world.ecs, targetId, attackerId, now);
2270 2286 if (profile?.mode === "ranged")
@@ -2517,6 +2533,8 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2517 2533 const origin = world.ecs.get(handle, Component.spawnOrigin);
2518 2534 const appearance = world.ecs.get(handle, Component.appearance);
2519 2535 const summon = world.ecs.get(handle, Component.summon);
2536 const position = world.ecs.get(handle, Component.position);
2537 const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2520 2538 if (summon?.kind === "jadeite-fairy")
2521 2539 {
2522 2540 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
@@ -2549,7 +2567,8 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2549 2567 townGuard: !!origin?.townGuard,
2550 2568 displayName: appearance?.firstName ?? null,
2551 2569 tileX,
2552 tileY
2570 tileY,
2571 dimensionId
2553 2572 });
2554 2573 if (origin?.spawnerId)
2555 2574 {
@@ -2568,6 +2587,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2568 2587 entityId: targetId,
2569 2588 tileX: view.tileX,
2570 2589 tileY: view.tileY,
2590 dimensionId: view.dimensionId,
2571 2591 cause: "death"
2572 2592 });
2573 2593 }
@@ -2603,7 +2623,11 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2603 2623 });
2604 2624
2605 2625 const attackerHandle = world.ecs.handleOf(attackerId);
2606 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
2626 if (
2627 attackerHandle != null
2628 && !entityIsPassive(world.ecs, targetHandle)
2629 && ensureMobCombat(world.ecs, targetId)
2630 )
2607 2631 {
2608 2632 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2609 2633 const targetCombat = world.ecs.get(targetHandle, Component.combat);
@@ -299,6 +299,17 @@ export function ensureMobCombat (ecs, entityId)
299 return true;
299 return true;
300}
300}
301
301
302/** Spawner Passive: take hits but do not enter combat / retaliate. Aggressive overrides. */
303export function entityIsPassive (ecs, handle)
304{
305 const origin = ecs.get(handle, Component.spawnOrigin);
306 if (!origin?.passive)
307 { return false; }
308 if (origin.aggressive)
309 { return false; }
310 return true;
311}
312
302function attackerSkillLevel (skills, profile, skillId)
313function attackerSkillLevel (skills, profile, skillId)
303{
314{
304 if (profile.mobAttackSkill != null)
315 if (profile.mobAttackSkill != null)
@@ -2264,7 +2275,12 @@ function applyLocalMeleeHit (
2264 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
2275 : (attackerHandle != null ? !!world.ecs.get(attackerHandle, Component.character) : null);
2265
2276
2266 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
2277 // Retaliate on the first resolved swing (hit or miss), not on Attack-click engage.
2267 if (attackerIsPlayer === true && ensureMobCombat(world.ecs, targetId))
2278 // Passive spawners take hits but do not fight back.
2279 if (
2280 attackerIsPlayer === true
2281 && !entityIsPassive(world.ecs, targetHandle)
2282 && ensureMobCombat(world.ecs, targetId)
2283 )
2268 {
2284 {
2269 engageTarget(world.ecs, targetId, attackerId, now);
2285 engageTarget(world.ecs, targetId, attackerId, now);
2270 if (profile?.mode === "ranged")
2286 if (profile?.mode === "ranged")
@@ -2517,6 +2533,8 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2517 const origin = world.ecs.get(handle, Component.spawnOrigin);
2533 const origin = world.ecs.get(handle, Component.spawnOrigin);
2518 const appearance = world.ecs.get(handle, Component.appearance);
2534 const appearance = world.ecs.get(handle, Component.appearance);
2519 const summon = world.ecs.get(handle, Component.summon);
2535 const summon = world.ecs.get(handle, Component.summon);
2536 const position = world.ecs.get(handle, Component.position);
2537 const dimensionId = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
2520 if (summon?.kind === "jadeite-fairy")
2538 if (summon?.kind === "jadeite-fairy")
2521 {
2539 {
2522 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
2540 const respawnAt = now + JADEITE_FAIRY_RESPAWN_MS;
@@ -2549,7 +2567,8 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2549 townGuard: !!origin?.townGuard,
2567 townGuard: !!origin?.townGuard,
2550 displayName: appearance?.firstName ?? null,
2568 displayName: appearance?.firstName ?? null,
2551 tileX,
2569 tileX,
2552 tileY
2570 tileY,
2571 dimensionId
2553 });
2572 });
2554 if (origin?.spawnerId)
2573 if (origin?.spawnerId)
2555 {
2574 {
@@ -2568,6 +2587,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
2568 entityId: targetId,
2587 entityId: targetId,
2569 tileX: view.tileX,
2588 tileX: view.tileX,
2570 tileY: view.tileY,
2589 tileY: view.tileY,
2590 dimensionId: view.dimensionId,
2571 cause: "death"
2591 cause: "death"
2572 });
2592 });
2573 }
2593 }
@@ -2603,7 +2623,11 @@ export function applyDamageAndKill (world, attackerId, targetId, damage, now = D
2603 });
2623 });
2604
2624
2605 const attackerHandle = world.ecs.handleOf(attackerId);
2625 const attackerHandle = world.ecs.handleOf(attackerId);
2606 if (attackerHandle != null && ensureMobCombat(world.ecs, targetId))
2626 if (
2627 attackerHandle != null
2628 && !entityIsPassive(world.ecs, targetHandle)
2629 && ensureMobCombat(world.ecs, targetId)
2630 )
2607 {
2631 {
2608 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2632 const attackerIsPlayer = !!world.ecs.get(attackerHandle, Component.character);
2609 const targetCombat = world.ecs.get(targetHandle, Component.combat);
2633 const targetCombat = world.ecs.get(targetHandle, Component.combat);
server/src/courier/service.js +459 −76
@@ -3,9 +3,17 @@ import { BlockType } from "../../../shared/definitions/tiles.js";
3 3 import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4 4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 5 import { isLetterWrittenBy } from "../../../shared/items/letters.js";
6 import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6 import { insertStack, insertStackGrowable, takeFromSlot, normalizeVault } from "../../../shared/items/inventory.js";
7 7 import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
8 8 import { advanceCourierFlight } from "../../../shared/courier/flight.js";
9 import {
10 buildDoorwayGraph,
11 planPortalLegs,
12 buildFallbackLegs,
13 advanceAbstractTravel,
14 poseOnCourierLeg,
15 ensureCourierLegs
16 } from "../../../shared/courier/doorwayGraph.js";
9 17 import { GAIT } from "../../../shared/protocol/constants.js";
10 18 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
11 19 import { decodeChunkBlob } from "../world/chunkData.js";
@@ -30,8 +38,11 @@ export class CourierService
30 38 this.simulation = simulation;
31 39 this.bankTiles = [];
32 40 this.bountyOfficeTiles = [];
41 this.doorwayTiles = [];
42 this.doorwayGraph = buildDoorwayGraph([]);
33 43 this.refreshBankIndex();
34 44 this.refreshBountyOfficeIndex();
45 this.refreshDoorwayIndex();
35 46 }
36 47
37 48 refreshBankIndex ()
@@ -44,6 +55,12 @@ export class CourierService
44 55 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
45 56 }
46 57
58 refreshDoorwayIndex ()
59 {
60 this.doorwayTiles = this.#listDoorwayTiles();
61 this.doorwayGraph = buildDoorwayGraph(this.doorwayTiles);
62 }
63
47 64 #listBlockTiles (typeId)
48 65 {
49 66 const revisionId = this.worldDb.getActiveRevisionId();
@@ -73,6 +90,39 @@ export class CourierService
73 90 return tiles;
74 91 }
75 92
93 #listDoorwayTiles ()
94 {
95 const revisionId = this.worldDb.getActiveRevisionId();
96 const tiles = [];
97 for (const coord of this.worldDb.listChunkCoords(revisionId))
98 {
99 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
100 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
101 if (!row)
102 { continue; }
103 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
104 for (let localY = 0; localY < CHUNK_SIZE; localY++)
105 {
106 for (let localX = 0; localX < CHUNK_SIZE; localX++)
107 {
108 const block = data.blocks[localY * CHUNK_SIZE + localX];
109 if (block?.typeId !== BlockType.doorway)
110 { continue; }
111 const config = block.config && typeof block.config === "object" ? block.config : null;
112 tiles.push({
113 tileX: coord.chunk_x * CHUNK_SIZE + localX,
114 tileY: coord.chunk_y * CHUNK_SIZE + localY,
115 dimensionId: dim,
116 targetDimensionId: config?.targetDimensionId,
117 targetTileX: config?.tileX,
118 targetTileY: config?.tileY
119 });
120 }
121 }
122 }
123 return tiles;
124 }
125
76 126 nearestBank (tileX, tileY, dimensionId = null)
77 127 {
78 128 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
@@ -94,32 +144,42 @@ export class CourierService
94 144 });
95 145 }
96 146
147 /**
148 * Prefer same-dimension tiles when dimensionId is set; otherwise / as fallback, nearest overall.
149 */
97 150 #nearestTile (tiles, tileX, tileY, dimensionId = null)
98 151 {
99 152 if (!tiles.length)
100 153 { return null; }
101 154 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
102 let best = null;
103 let bestDist = Infinity;
155 let bestSame = null;
156 let bestSameDist = Infinity;
157 let bestAny = null;
158 let bestAnyDist = Infinity;
104 159 for (const tile of tiles)
105 160 {
106 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
107 { continue; }
108 161 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
109 if (dist < bestDist)
162 if (dist < bestAnyDist)
110 163 {
111 bestDist = dist;
112 best = tile;
164 bestAnyDist = dist;
165 bestAny = tile;
166 }
167 if (dim != null
168 && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
169 && dist < bestSameDist)
170 {
171 bestSameDist = dist;
172 bestSame = tile;
113 173 }
114 174 }
115 return best;
175 return bestSame ?? bestAny;
116 176 }
117 177
118 178 /**
119 179 * Player dispatch: cargo is money or one inventory stack.
120 180 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
121 181 */
122 dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })
182 dispatchFromPlayer ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, destination, cargo })
123 183 {
124 184 const onlineId = this.simulation.characterEntities.get(characterId);
125 185 const bag = onlineId
@@ -168,21 +228,21 @@ export class CourierService
168 228 throw error;
169 229 }
170 230
171 const dest = this.#resolveDestination(destination, originTileX, originTileY);
231 const originDim = normalizeDimensionId(originDimensionId);
232 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
172 233 this.#persistBag(characterId, bag);
173 const transit = this.stateDb.insertCourierTransit({
234 const transit = this.#insertRoutedTransit({
174 235 senderCharacterId: characterId,
175 236 destinationKind: dest.kind,
176 237 destinationCharacterId: dest.characterId ?? null,
177 238 vaultCharacterId: dest.vaultCharacterId ?? null,
178 239 cargo: takenCargo,
179 originX: originTileX + 0.5,
180 originY: originTileY + 0.5,
181 destX: dest.tileX + 0.5,
182 destY: dest.tileY + 0.5,
183 traveled: 0,
184 status: "in_transit",
185 entityId: null
240 originTileX,
241 originTileY,
242 originDimensionId: originDim,
243 destTileX: dest.tileX,
244 destTileY: dest.tileY,
245 destDimensionId: dest.dimensionId
186 246 });
187 247 return { transit, bag };
188 248 }
@@ -196,6 +256,7 @@ export class CourierService
196 256 characterId,
197 257 originTileX,
198 258 originTileY,
259 originDimensionId = OVERWORLD_ID,
199 260 authorDisplayName,
200 261 authorOrganization = null,
201 262 body,
@@ -214,6 +275,7 @@ export class CourierService
214 275 characterId,
215 276 originTileX,
216 277 originTileY,
278 originDimensionId,
217 279 stack
218 280 });
219 281 }
@@ -224,7 +286,7 @@ export class CourierService
224 286 * — never deposit the letter straight into the vault.
225 287 * Prefer enqueueSystemLetter when building a new system letter from author/body fields.
226 288 */
227 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
289 dispatchSystemLetter ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, stack })
228 290 {
229 291 const recipientId = characterId | 0;
230 292 const cargo = { kind: "item", stack };
@@ -233,6 +295,7 @@ export class CourierService
233 295 senderCharacterId: recipientId,
234 296 originTileX,
235 297 originTileY,
298 originDimensionId,
236 299 destination: {
237 300 kind: "player",
238 301 firstName: row?.first_name ?? "Unknown",
@@ -249,18 +312,28 @@ export class CourierService
249 312 * Player-bound holds keep destinationKind "player" even though resolve would route to bank
250 313 * while offline — on login the pigeon then delivers to the character, not the vault.
251 314 */
252 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
315 dispatchHeldCargo ({
316 senderCharacterId,
317 originTileX,
318 originTileY,
319 originDimensionId = OVERWORLD_ID,
320 destination,
321 cargo,
322 vaultCharacterId = null
323 })
253 324 {
325 const originDim = normalizeDimensionId(originDimensionId);
254 326 const recipientId = vaultCharacterId ?? senderCharacterId;
255 327 if (!this.simulation.isCharacterOnline(recipientId))
256 328 {
257 const dest = this.#resolveDestination(destination, originTileX, originTileY);
329 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
258 330 const intendedKind = destination?.kind === "player" ? "player" : dest.kind;
259 331 this.stateDb.insertHeldCourierDelivery({
260 332 characterId: recipientId,
261 333 senderCharacterId,
262 334 originTileX,
263 335 originTileY,
336 originDimensionId: originDim,
264 337 destinationKind: intendedKind,
265 338 destinationCharacterId: dest.characterId ?? recipientId,
266 339 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
@@ -268,26 +341,26 @@ export class CourierService
268 341 });
269 342 return null;
270 343 }
271 const dest = this.#resolveDestination(destination, originTileX, originTileY);
272 return this.stateDb.insertCourierTransit({
344 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
345 return this.#insertRoutedTransit({
273 346 senderCharacterId,
274 347 destinationKind: dest.kind,
275 348 destinationCharacterId: dest.characterId ?? null,
276 349 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
277 350 cargo,
278 originX: originTileX + 0.5,
279 originY: originTileY + 0.5,
280 destX: dest.tileX + 0.5,
281 destY: dest.tileY + 0.5,
282 traveled: 0,
283 status: "in_transit",
284 entityId: null
351 originTileX,
352 originTileY,
353 originDimensionId: originDim,
354 destTileX: dest.tileX,
355 destTileY: dest.tileY,
356 destDimensionId: dest.dimensionId
285 357 });
286 358 }
287 359
288 360 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
289 onCharacterEnteredWorld (characterId, tileX, tileY)
361 onCharacterEnteredWorld (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
290 362 {
363 const enterDim = normalizeDimensionId(dimensionId);
291 364 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
292 365 {
293 366 this.stateDb.deleteHeldCourierDelivery(held.holdId);
@@ -296,6 +369,7 @@ export class CourierService
296 369 senderCharacterId: held.senderCharacterId,
297 370 originTileX: held.originTileX,
298 371 originTileY: held.originTileY,
372 originDimensionId: held.originDimensionId ?? OVERWORLD_ID,
299 373 destination: held.destinationKind === "bank"
300 374 ? { kind: "bank" }
301 375 : {
@@ -307,7 +381,7 @@ export class CourierService
307 381 vaultCharacterId: held.vaultCharacterId ?? characterId
308 382 });
309 383 }
310 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
384 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY, enterDim);
311 385 void noticeTransit;
312 386 }
313 387
@@ -317,28 +391,256 @@ export class CourierService
317 391 const settings = this.simulation.settings;
318 392 for (const transit of this.stateDb.listActiveCourierTransits())
319 393 {
394 ensureCourierLegs(transit);
320 395 this.#retargetPlayerDest(transit);
396 ensureCourierLegs(transit);
397 const advancedEvents = this.#advanceTransit(transit, now, dt, settings);
398 events.push(...advancedEvents);
399 }
400 return events;
401 }
402
403 #insertRoutedTransit ({
404 senderCharacterId,
405 destinationKind,
406 destinationCharacterId,
407 vaultCharacterId,
408 cargo,
409 originTileX,
410 originTileY,
411 originDimensionId,
412 destTileX,
413 destTileY,
414 destDimensionId
415 })
416 {
417 const originDim = normalizeDimensionId(originDimensionId);
418 const destDim = normalizeDimensionId(destDimensionId ?? OVERWORLD_ID);
419 const originX = originTileX + 0.5;
420 const originY = originTileY + 0.5;
421 const destX = destTileX + 0.5;
422 const destY = destTileY + 0.5;
423 const legs = this.#planLegs({
424 fromX: originX,
425 fromY: originY,
426 fromDimensionId: originDim,
427 toX: destX,
428 toY: destY,
429 toDimensionId: destDim
430 });
431 return this.stateDb.insertCourierTransit({
432 senderCharacterId,
433 destinationKind,
434 destinationCharacterId,
435 vaultCharacterId,
436 cargo,
437 originX,
438 originY,
439 destX,
440 destY,
441 originDimensionId: originDim,
442 destDimensionId: destDim,
443 legs,
444 legIndex: 0,
445 traveled: 0,
446 status: "in_transit",
447 entityId: null
448 });
449 }
450
451 #planLegs ({ fromX, fromY, fromDimensionId, toX, toY, toDimensionId })
452 {
453 const planned = planPortalLegs({
454 fromX,
455 fromY,
456 fromDimensionId,
457 toX,
458 toY,
459 toDimensionId,
460 graph: this.doorwayGraph
461 });
462 if (planned.mode !== "fallback")
463 { return planned.legs; }
464 return buildFallbackLegs({
465 fromX,
466 fromY,
467 fromDimensionId,
468 toX,
469 toY,
470 toDimensionId,
471 isSimulating: (tileX, tileY, dimensionId) =>
472 this.simulation.chunkIsSimulating(tileX, tileY, dimensionId),
473 settings: this.simulation.settings
474 }).legs;
475 }
476
477 #repathTransit (transit, fromX, fromY, fromDimensionId, toX, toY, toDimensionId)
478 {
479 if (transit.entityId)
480 {
481 this.simulation.despawnEntity(transit.entityId);
482 transit.entityId = null;
483 }
484 transit.originX = fromX;
485 transit.originY = fromY;
486 transit.originDimensionId = normalizeDimensionId(fromDimensionId);
487 transit.destX = toX;
488 transit.destY = toY;
489 transit.destDimensionId = normalizeDimensionId(toDimensionId);
490 transit.legs = this.#planLegs({
491 fromX,
492 fromY,
493 fromDimensionId: transit.originDimensionId,
494 toX,
495 toY,
496 toDimensionId: transit.destDimensionId
497 });
498 transit.legIndex = 0;
499 transit.traveled = 0;
500 }
501
502 #currentPose (transit)
503 {
504 ensureCourierLegs(transit);
505 const leg = transit.legs[transit.legIndex | 0];
506 const pose = poseOnCourierLeg(leg, transit.traveled);
507 if (pose)
508 { return pose; }
509 if (leg?.kind === "abstract")
510 {
511 return {
512 x: leg.fromX,
513 y: leg.fromY,
514 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID)
515 };
516 }
517 return {
518 x: transit.originX,
519 y: transit.originY,
520 dimensionId: normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID)
521 };
522 }
523
524 #advanceTransit (transit, now, dt, settings)
525 {
526 const events = [];
527 ensureCourierLegs(transit);
528 let remainingDt = Math.max(0, dt);
529 let guard = 0;
530 while (remainingDt > 0 && guard++ < 16)
531 {
532 const leg = transit.legs[transit.legIndex | 0];
533 if (!leg)
534 {
535 events.push(...this.#deliver(transit, now));
536 return events;
537 }
538
539 if (leg.kind === "portal")
540 {
541 transit.traveled = 0;
542 transit.legIndex = (transit.legIndex | 0) + 1;
543 if (transit.entityId)
544 {
545 this.simulation.despawnEntity(transit.entityId);
546 events.push({
547 type: "entity-despawn",
548 entityId: transit.entityId,
549 tileX: Math.floor(leg.fromX),
550 tileY: Math.floor(leg.fromY),
551 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
552 });
553 transit.entityId = null;
554 }
555 if ((transit.legIndex | 0) >= transit.legs.length)
556 {
557 events.push(...this.#deliver(transit, now));
558 return events;
559 }
560 continue;
561 }
562
563 if (leg.kind === "abstract")
564 {
565 if (transit.entityId)
566 {
567 const pose = this.#currentPose(transit);
568 this.simulation.despawnEntity(transit.entityId);
569 events.push({
570 type: "entity-despawn",
571 entityId: transit.entityId,
572 tileX: Math.floor(pose.x),
573 tileY: Math.floor(pose.y),
574 dimensionId: pose.dimensionId
575 });
576 transit.entityId = null;
577 }
578 const advanced = advanceAbstractTravel({
579 traveled: transit.traveled,
580 distance: leg.distance ?? 0,
581 dt: remainingDt,
582 settings
583 });
584 transit.traveled = advanced.traveled;
585 transit.updatedAt = now;
586 if (!advanced.arrived)
587 {
588 this.stateDb.updateCourierTransit(transit);
589 return events;
590 }
591 remainingDt = 0;
592 transit.traveled = 0;
593 transit.legIndex = (transit.legIndex | 0) + 1;
594 if ((transit.legIndex | 0) >= transit.legs.length)
595 {
596 events.push(...this.#deliver(transit, now));
597 return events;
598 }
599 continue;
600 }
601
602 // fly leg
321 603 const advanced = advanceCourierFlight({
322 originX: transit.originX,
323 originY: transit.originY,
324 destX: transit.destX,
325 destY: transit.destY,
604 originX: leg.fromX,
605 originY: leg.fromY,
606 destX: leg.toX,
607 destY: leg.toY,
326 608 traveled: transit.traveled,
327 dt,
609 dt: remainingDt,
328 610 settings
329 611 });
330 612 transit.traveled = advanced.traveled;
331 613 transit.updatedAt = now;
614 if (!advanced.arrived)
615 {
616 events.push(...this.#syncVisiblePigeon(transit, advanced, now, leg));
617 this.stateDb.updateCourierTransit(transit);
618 return events;
619 }
332 620
333 if (advanced.arrived)
621 remainingDt = 0;
622 transit.traveled = 0;
623 transit.legIndex = (transit.legIndex | 0) + 1;
624 if ((transit.legIndex | 0) >= transit.legs.length)
334 625 {
335 626 events.push(...this.#deliver(transit, now));
336 continue;
627 return events;
628 }
629 // Despawn at portal approach so next portal/fly starts clean.
630 if (transit.entityId)
631 {
632 this.simulation.despawnEntity(transit.entityId);
633 events.push({
634 type: "entity-despawn",
635 entityId: transit.entityId,
636 tileX: Math.floor(advanced.x),
637 tileY: Math.floor(advanced.y),
638 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
639 });
640 transit.entityId = null;
337 641 }
338
339 events.push(...this.#syncVisiblePigeon(transit, advanced, now));
340 this.stateDb.updateCourierTransit(transit);
341 642 }
643 this.stateDb.updateCourierTransit(transit);
342 644 return events;
343 645 }
344 646
@@ -350,10 +652,45 @@ export class CourierService
350 652 if (onlineId)
351 653 {
352 654 const pos = this.simulation.positionOf(onlineId);
353 if (pos)
655 if (!pos)
656 { return; }
657 const destDim = normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID);
658 const destX = pos.tileX + 0.5;
659 const destY = pos.tileY + 0.5;
660 const prevDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
661 if (destDim !== prevDim)
354 662 {
355 transit.destX = pos.tileX + 0.5;
356 transit.destY = pos.tileY + 0.5;
663 const pose = this.#currentPose(transit);
664 this.#repathTransit(
665 transit,
666 pose.x,
667 pose.y,
668 pose.dimensionId,
669 destX,
670 destY,
671 destDim
672 );
673 return;
674 }
675 transit.destX = destX;
676 transit.destY = destY;
677 transit.destDimensionId = destDim;
678 const lastIdx = transit.legs.length - 1;
679 const last = transit.legs[lastIdx];
680 if (last?.kind === "fly"
681 && normalizeDimensionId(last.toDimensionId ?? destDim) === destDim)
682 {
683 const oldToX = last.toX;
684 const oldToY = last.toY;
685 last.toX = destX;
686 last.toY = destY;
687 if ((transit.legIndex | 0) === lastIdx)
688 {
689 const oldTotal = Math.hypot(oldToX - last.fromX, oldToY - last.fromY);
690 const newTotal = Math.hypot(destX - last.fromX, destY - last.fromY);
691 if (oldTotal > 1e-6)
692 { transit.traveled = Math.min(newTotal, (transit.traveled || 0) * (newTotal / oldTotal)); }
693 }
357 694 }
358 695 return;
359 696 }
@@ -362,18 +699,28 @@ export class CourierService
362 699
363 700 #routeTransitToBank (transit, vaultCharacterId)
364 701 {
365 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
366 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
702 const pose = this.#currentPose(transit);
703 const bank = this.nearestBank(Math.floor(pose.x), Math.floor(pose.y), pose.dimensionId)
704 ?? this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), transit.destDimensionId)
705 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
367 706 if (!bank)
368 707 { return; }
369 708 transit.destinationKind = "bank";
370 709 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
371 transit.destX = bank.tileX + 0.5;
372 transit.destY = bank.tileY + 0.5;
710 this.#repathTransit(
711 transit,
712 pose.x,
713 pose.y,
714 pose.dimensionId,
715 bank.tileX + 0.5,
716 bank.tileY + 0.5,
717 bank.dimensionId ?? OVERWORLD_ID
718 );
373 719 }
374 720
375 #resolveDestination (destination, originTileX, originTileY)
721 #resolveDestination (destination, originTileX, originTileY, originDimensionId = OVERWORLD_ID)
376 722 {
723 const originDim = normalizeDimensionId(originDimensionId);
377 724 if (destination?.kind === "player")
378 725 {
379 726 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
@@ -386,8 +733,9 @@ export class CourierService
386 733 const onlineId = this.simulation.characterEntities.get(character.character_id);
387 734 if (!onlineId)
388 735 {
389 const bank = this.nearestBank(originTileX, originTileY)
390 ?? this.nearestBank(character.tile_x, character.tile_y);
736 const charDim = normalizeDimensionId(character.dimension_id ?? OVERWORLD_ID);
737 const bank = this.nearestBank(originTileX, originTileY, originDim)
738 ?? this.nearestBank(character.tile_x, character.tile_y, charDim);
391 739 if (!bank)
392 740 {
393 741 const error = new Error("No bank exists in the world yet.");
@@ -399,7 +747,8 @@ export class CourierService
399 747 characterId: character.character_id,
400 748 vaultCharacterId: character.character_id,
401 749 tileX: bank.tileX,
402 tileY: bank.tileY
750 tileY: bank.tileY,
751 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
403 752 };
404 753 }
405 754 const pos = this.simulation.positionOf(onlineId);
@@ -407,36 +756,51 @@ export class CourierService
407 756 kind: "player",
408 757 characterId: character.character_id,
409 758 tileX: pos.tileX,
410 tileY: pos.tileY
759 tileY: pos.tileY,
760 dimensionId: normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID)
411 761 };
412 762 }
413 763 if (destination?.kind === "bank")
414 764 {
415 const bank = this.nearestBank(originTileX, originTileY);
765 const bank = this.nearestBank(originTileX, originTileY, originDim);
416 766 if (!bank)
417 767 {
418 768 const error = new Error("No bank exists in the world yet.");
419 769 error.userFacing = true;
420 770 throw error;
421 771 }
422 return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
772 return {
773 kind: "bank",
774 tileX: bank.tileX,
775 tileY: bank.tileY,
776 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
777 };
423 778 }
424 779 const error = new Error("Pigeon destination must be bank or player.");
425 780 error.userFacing = true;
426 781 throw error;
427 782 }
428 783
429 #syncVisiblePigeon (transit, advanced, now)
784 #syncVisiblePigeon (transit, advanced, now, leg)
430 785 {
431 786 const events = [];
432 787 const tileX = Math.floor(advanced.x);
433 788 const tileY = Math.floor(advanced.y);
434 if (!this.simulation.chunkIsSimulating(tileX, tileY))
789 const dimensionId = normalizeDimensionId(
790 leg?.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID
791 );
792 if (!this.simulation.chunkIsSimulating(tileX, tileY, dimensionId))
435 793 {
436 794 if (transit.entityId)
437 795 {
438 796 this.simulation.despawnEntity(transit.entityId);
439 events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
797 events.push({
798 type: "entity-despawn",
799 entityId: transit.entityId,
800 tileX,
801 tileY,
802 dimensionId
803 });
440 804 transit.entityId = null;
441 805 }
442 806 return events;
@@ -447,14 +811,14 @@ export class CourierService
447 811 transit.entityId = null;
448 812 const def = mobDefinition(MobId.pigeon);
449 813 const entityId = this.simulation.spawnEntity({
450 position: { tileX, tileY },
814 position: { tileX, tileY, dimensionId },
451 815 movement: { gait: GAIT.walk, walkCarry: 0 },
452 816 path: { tiles: [] },
453 817 flight: {
454 818 x: advanced.x,
455 819 y: advanced.y,
456 targetX: transit.destX,
457 targetY: transit.destY,
820 targetX: leg?.toX ?? transit.destX,
821 targetY: leg?.toY ?? transit.destY,
458 822 speed: advanced.speed,
459 823 nextPickAt: now + 60_000,
460 824 lastAt: now,
@@ -477,8 +841,8 @@ export class CourierService
477 841 const moved = this.simulation.updateCourierFlight(transit.entityId, {
478 842 x: advanced.x,
479 843 y: advanced.y,
480 targetX: transit.destX,
481 targetY: transit.destY,
844 targetX: leg?.toX ?? transit.destX,
845 targetY: leg?.toY ?? transit.destY,
482 846 speed: advanced.speed,
483 847 lastAt: now,
484 848 courierId: transit.courierId
@@ -486,7 +850,13 @@ export class CourierService
486 850 if (moved?.despawned)
487 851 {
488 852 transit.entityId = null;
489 events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
853 events.push({
854 type: "entity-despawn",
855 entityId: moved.entityId,
856 tileX,
857 tileY,
858 dimensionId
859 });
490 860 }
491 861 else if (moved?.event)
492 862 { events.push(moved.event); }
@@ -496,6 +866,7 @@ export class CourierService
496 866 #deliver (transit, now)
497 867 {
498 868 const events = [];
869 const destDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
499 870 if (transit.entityId)
500 871 {
501 872 this.simulation.despawnEntity(transit.entityId);
@@ -503,7 +874,8 @@ export class CourierService
503 874 type: "entity-despawn",
504 875 entityId: transit.entityId,
505 876 tileX: Math.floor(transit.destX),
506 tileY: Math.floor(transit.destY)
877 tileY: Math.floor(transit.destY),
878 dimensionId: destDim
507 879 });
508 880 transit.entityId = null;
509 881 }
@@ -524,17 +896,26 @@ export class CourierService
524 896 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
525 897 if (!delivered)
526 898 {
527 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
528 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
899 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), destDim)
900 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
529 901 if (bank)
530 902 {
531 transit.originX = transit.destX;
532 transit.originY = transit.destY;
533 transit.destX = bank.tileX + 0.5;
534 transit.destY = bank.tileY + 0.5;
535 transit.traveled = 0;
903 const pose = {
904 x: transit.destX,
905 y: transit.destY,
906 dimensionId: destDim
907 };
536 908 transit.destinationKind = "bank";
537 909 transit.vaultCharacterId = transit.destinationCharacterId;
910 this.#repathTransit(
911 transit,
912 pose.x,
913 pose.y,
914 pose.dimensionId,
915 bank.tileX + 0.5,
916 bank.tileY + 0.5,
917 bank.dimensionId ?? OVERWORLD_ID
918 );
538 919 transit.updatedAt = now;
539 920 this.stateDb.updateCourierTransit(transit);
540 921 events.push({
@@ -772,12 +1153,13 @@ export class CourierService
772 1153 };
773 1154 }
774 1155
775 #dispatchBankRestNotice (characterId, tileX, tileY)
1156 #dispatchBankRestNotice (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
776 1157 {
777 1158 const entries = this.stateDb.listBankRestNotices(characterId);
778 1159 if (!entries.length)
779 1160 { return null; }
780 const bank = this.nearestBank(tileX, tileY);
1161 const dim = normalizeDimensionId(dimensionId);
1162 const bank = this.nearestBank(tileX, tileY, dim);
781 1163 if (!bank)
782 1164 { return null; }
783 1165
@@ -798,6 +1180,7 @@ export class CourierService
798 1180 characterId,
799 1181 originTileX: bank.tileX,
800 1182 originTileY: bank.tileY,
1183 originDimensionId: bank.dimensionId ?? OVERWORLD_ID,
801 1184 stack
802 1185 });
803 1186 }
@@ -3,9 +3,17 @@ import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { isLetterWrittenBy } from "../../../shared/items/letters.js";
5import { isLetterWrittenBy } from "../../../shared/items/letters.js";
6import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { insertStack, insertStackGrowable, takeFromSlot, normalizeVault } from "../../../shared/items/inventory.js";
7import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
7import { attachOrigins, normalizeOrigins } from "../../../shared/items/origin.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
8import { advanceCourierFlight } from "../../../shared/courier/flight.js";
9import {
10 buildDoorwayGraph,
11 planPortalLegs,
12 buildFallbackLegs,
13 advanceAbstractTravel,
14 poseOnCourierLeg,
15 ensureCourierLegs
16} from "../../../shared/courier/doorwayGraph.js";
9import { GAIT } from "../../../shared/protocol/constants.js";
17import { GAIT } from "../../../shared/protocol/constants.js";
10import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
18import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
11import { decodeChunkBlob } from "../world/chunkData.js";
19import { decodeChunkBlob } from "../world/chunkData.js";
@@ -30,8 +38,11 @@ export class CourierService
30 this.simulation = simulation;
38 this.simulation = simulation;
31 this.bankTiles = [];
39 this.bankTiles = [];
32 this.bountyOfficeTiles = [];
40 this.bountyOfficeTiles = [];
41 this.doorwayTiles = [];
42 this.doorwayGraph = buildDoorwayGraph([]);
33 this.refreshBankIndex();
43 this.refreshBankIndex();
34 this.refreshBountyOfficeIndex();
44 this.refreshBountyOfficeIndex();
45 this.refreshDoorwayIndex();
35 }
46 }
36
47
37 refreshBankIndex ()
48 refreshBankIndex ()
@@ -44,6 +55,12 @@ export class CourierService
44 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
55 this.bountyOfficeTiles = this.#listBlockTiles(BlockType.bountyOffice);
45 }
56 }
46
57
58 refreshDoorwayIndex ()
59 {
60 this.doorwayTiles = this.#listDoorwayTiles();
61 this.doorwayGraph = buildDoorwayGraph(this.doorwayTiles);
62 }
63
47 #listBlockTiles (typeId)
64 #listBlockTiles (typeId)
48 {
65 {
49 const revisionId = this.worldDb.getActiveRevisionId();
66 const revisionId = this.worldDb.getActiveRevisionId();
@@ -73,6 +90,39 @@ export class CourierService
73 return tiles;
90 return tiles;
74 }
91 }
75
92
93 #listDoorwayTiles ()
94 {
95 const revisionId = this.worldDb.getActiveRevisionId();
96 const tiles = [];
97 for (const coord of this.worldDb.listChunkCoords(revisionId))
98 {
99 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
100 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim);
101 if (!row)
102 { continue; }
103 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
104 for (let localY = 0; localY < CHUNK_SIZE; localY++)
105 {
106 for (let localX = 0; localX < CHUNK_SIZE; localX++)
107 {
108 const block = data.blocks[localY * CHUNK_SIZE + localX];
109 if (block?.typeId !== BlockType.doorway)
110 { continue; }
111 const config = block.config && typeof block.config === "object" ? block.config : null;
112 tiles.push({
113 tileX: coord.chunk_x * CHUNK_SIZE + localX,
114 tileY: coord.chunk_y * CHUNK_SIZE + localY,
115 dimensionId: dim,
116 targetDimensionId: config?.targetDimensionId,
117 targetTileX: config?.tileX,
118 targetTileY: config?.tileY
119 });
120 }
121 }
122 }
123 return tiles;
124 }
125
76 nearestBank (tileX, tileY, dimensionId = null)
126 nearestBank (tileX, tileY, dimensionId = null)
77 {
127 {
78 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
128 return this.#nearestTile(this.bankTiles, tileX, tileY, dimensionId);
@@ -94,32 +144,42 @@ export class CourierService
94 });
144 });
95 }
145 }
96
146
147 /**
148 * Prefer same-dimension tiles when dimensionId is set; otherwise / as fallback, nearest overall.
149 */
97 #nearestTile (tiles, tileX, tileY, dimensionId = null)
150 #nearestTile (tiles, tileX, tileY, dimensionId = null)
98 {
151 {
99 if (!tiles.length)
152 if (!tiles.length)
100 { return null; }
153 { return null; }
101 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
154 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null;
102 let best = null;
155 let bestSame = null;
103 let bestDist = Infinity;
156 let bestSameDist = Infinity;
157 let bestAny = null;
158 let bestAnyDist = Infinity;
104 for (const tile of tiles)
159 for (const tile of tiles)
105 {
160 {
106 if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
107 { continue; }
108 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
161 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
109 if (dist < bestDist)
162 if (dist < bestAnyDist)
110 {
163 {
111 bestDist = dist;
164 bestAnyDist = dist;
112 best = tile;
165 bestAny = tile;
166 }
167 if (dim != null
168 && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
169 && dist < bestSameDist)
170 {
171 bestSameDist = dist;
172 bestSame = tile;
113 }
173 }
114 }
174 }
115 return best;
175 return bestSame ?? bestAny;
116 }
176 }
117
177
118 /**
178 /**
119 * Player dispatch: cargo is money or one inventory stack.
179 * Player dispatch: cargo is money or one inventory stack.
120 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
180 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
121 */
181 */
122 dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })
182 dispatchFromPlayer ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, destination, cargo })
123 {
183 {
124 const onlineId = this.simulation.characterEntities.get(characterId);
184 const onlineId = this.simulation.characterEntities.get(characterId);
125 const bag = onlineId
185 const bag = onlineId
@@ -168,21 +228,21 @@ export class CourierService
168 throw error;
228 throw error;
169 }
229 }
170
230
171 const dest = this.#resolveDestination(destination, originTileX, originTileY);
231 const originDim = normalizeDimensionId(originDimensionId);
232 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
172 this.#persistBag(characterId, bag);
233 this.#persistBag(characterId, bag);
173 const transit = this.stateDb.insertCourierTransit({
234 const transit = this.#insertRoutedTransit({
174 senderCharacterId: characterId,
235 senderCharacterId: characterId,
175 destinationKind: dest.kind,
236 destinationKind: dest.kind,
176 destinationCharacterId: dest.characterId ?? null,
237 destinationCharacterId: dest.characterId ?? null,
177 vaultCharacterId: dest.vaultCharacterId ?? null,
238 vaultCharacterId: dest.vaultCharacterId ?? null,
178 cargo: takenCargo,
239 cargo: takenCargo,
179 originX: originTileX + 0.5,
240 originTileX,
180 originY: originTileY + 0.5,
241 originTileY,
181 destX: dest.tileX + 0.5,
242 originDimensionId: originDim,
182 destY: dest.tileY + 0.5,
243 destTileX: dest.tileX,
183 traveled: 0,
244 destTileY: dest.tileY,
184 status: "in_transit",
245 destDimensionId: dest.dimensionId
185 entityId: null
186 });
246 });
187 return { transit, bag };
247 return { transit, bag };
188 }
248 }
@@ -196,6 +256,7 @@ export class CourierService
196 characterId,
256 characterId,
197 originTileX,
257 originTileX,
198 originTileY,
258 originTileY,
259 originDimensionId = OVERWORLD_ID,
199 authorDisplayName,
260 authorDisplayName,
200 authorOrganization = null,
261 authorOrganization = null,
201 body,
262 body,
@@ -214,6 +275,7 @@ export class CourierService
214 characterId,
275 characterId,
215 originTileX,
276 originTileX,
216 originTileY,
277 originTileY,
278 originDimensionId,
217 stack
279 stack
218 });
280 });
219 }
281 }
@@ -224,7 +286,7 @@ export class CourierService
224 * — never deposit the letter straight into the vault.
286 * — never deposit the letter straight into the vault.
225 * Prefer enqueueSystemLetter when building a new system letter from author/body fields.
287 * Prefer enqueueSystemLetter when building a new system letter from author/body fields.
226 */
288 */
227 dispatchSystemLetter ({ characterId, originTileX, originTileY, stack })
289 dispatchSystemLetter ({ characterId, originTileX, originTileY, originDimensionId = OVERWORLD_ID, stack })
228 {
290 {
229 const recipientId = characterId | 0;
291 const recipientId = characterId | 0;
230 const cargo = { kind: "item", stack };
292 const cargo = { kind: "item", stack };
@@ -233,6 +295,7 @@ export class CourierService
233 senderCharacterId: recipientId,
295 senderCharacterId: recipientId,
234 originTileX,
296 originTileX,
235 originTileY,
297 originTileY,
298 originDimensionId,
236 destination: {
299 destination: {
237 kind: "player",
300 kind: "player",
238 firstName: row?.first_name ?? "Unknown",
301 firstName: row?.first_name ?? "Unknown",
@@ -249,18 +312,28 @@ export class CourierService
249 * Player-bound holds keep destinationKind "player" even though resolve would route to bank
312 * Player-bound holds keep destinationKind "player" even though resolve would route to bank
250 * while offline — on login the pigeon then delivers to the character, not the vault.
313 * while offline — on login the pigeon then delivers to the character, not the vault.
251 */
314 */
252 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
315 dispatchHeldCargo ({
316 senderCharacterId,
317 originTileX,
318 originTileY,
319 originDimensionId = OVERWORLD_ID,
320 destination,
321 cargo,
322 vaultCharacterId = null
323 })
253 {
324 {
325 const originDim = normalizeDimensionId(originDimensionId);
254 const recipientId = vaultCharacterId ?? senderCharacterId;
326 const recipientId = vaultCharacterId ?? senderCharacterId;
255 if (!this.simulation.isCharacterOnline(recipientId))
327 if (!this.simulation.isCharacterOnline(recipientId))
256 {
328 {
257 const dest = this.#resolveDestination(destination, originTileX, originTileY);
329 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
258 const intendedKind = destination?.kind === "player" ? "player" : dest.kind;
330 const intendedKind = destination?.kind === "player" ? "player" : dest.kind;
259 this.stateDb.insertHeldCourierDelivery({
331 this.stateDb.insertHeldCourierDelivery({
260 characterId: recipientId,
332 characterId: recipientId,
261 senderCharacterId,
333 senderCharacterId,
262 originTileX,
334 originTileX,
263 originTileY,
335 originTileY,
336 originDimensionId: originDim,
264 destinationKind: intendedKind,
337 destinationKind: intendedKind,
265 destinationCharacterId: dest.characterId ?? recipientId,
338 destinationCharacterId: dest.characterId ?? recipientId,
266 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
339 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
@@ -268,26 +341,26 @@ export class CourierService
268 });
341 });
269 return null;
342 return null;
270 }
343 }
271 const dest = this.#resolveDestination(destination, originTileX, originTileY);
344 const dest = this.#resolveDestination(destination, originTileX, originTileY, originDim);
272 return this.stateDb.insertCourierTransit({
345 return this.#insertRoutedTransit({
273 senderCharacterId,
346 senderCharacterId,
274 destinationKind: dest.kind,
347 destinationKind: dest.kind,
275 destinationCharacterId: dest.characterId ?? null,
348 destinationCharacterId: dest.characterId ?? null,
276 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
349 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
277 cargo,
350 cargo,
278 originX: originTileX + 0.5,
351 originTileX,
279 originY: originTileY + 0.5,
352 originTileY,
280 destX: dest.tileX + 0.5,
353 originDimensionId: originDim,
281 destY: dest.tileY + 0.5,
354 destTileX: dest.tileX,
282 traveled: 0,
355 destTileY: dest.tileY,
283 status: "in_transit",
356 destDimensionId: dest.dimensionId
284 entityId: null
285 });
357 });
286 }
358 }
287
359
288 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
360 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
289 onCharacterEnteredWorld (characterId, tileX, tileY)
361 onCharacterEnteredWorld (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
290 {
362 {
363 const enterDim = normalizeDimensionId(dimensionId);
291 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
364 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
292 {
365 {
293 this.stateDb.deleteHeldCourierDelivery(held.holdId);
366 this.stateDb.deleteHeldCourierDelivery(held.holdId);
@@ -296,6 +369,7 @@ export class CourierService
296 senderCharacterId: held.senderCharacterId,
369 senderCharacterId: held.senderCharacterId,
297 originTileX: held.originTileX,
370 originTileX: held.originTileX,
298 originTileY: held.originTileY,
371 originTileY: held.originTileY,
372 originDimensionId: held.originDimensionId ?? OVERWORLD_ID,
299 destination: held.destinationKind === "bank"
373 destination: held.destinationKind === "bank"
300 ? { kind: "bank" }
374 ? { kind: "bank" }
301 : {
375 : {
@@ -307,7 +381,7 @@ export class CourierService
307 vaultCharacterId: held.vaultCharacterId ?? characterId
381 vaultCharacterId: held.vaultCharacterId ?? characterId
308 });
382 });
309 }
383 }
310 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
384 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY, enterDim);
311 void noticeTransit;
385 void noticeTransit;
312 }
386 }
313
387
@@ -317,28 +391,256 @@ export class CourierService
317 const settings = this.simulation.settings;
391 const settings = this.simulation.settings;
318 for (const transit of this.stateDb.listActiveCourierTransits())
392 for (const transit of this.stateDb.listActiveCourierTransits())
319 {
393 {
394 ensureCourierLegs(transit);
320 this.#retargetPlayerDest(transit);
395 this.#retargetPlayerDest(transit);
396 ensureCourierLegs(transit);
397 const advancedEvents = this.#advanceTransit(transit, now, dt, settings);
398 events.push(...advancedEvents);
399 }
400 return events;
401 }
402
403 #insertRoutedTransit ({
404 senderCharacterId,
405 destinationKind,
406 destinationCharacterId,
407 vaultCharacterId,
408 cargo,
409 originTileX,
410 originTileY,
411 originDimensionId,
412 destTileX,
413 destTileY,
414 destDimensionId
415 })
416 {
417 const originDim = normalizeDimensionId(originDimensionId);
418 const destDim = normalizeDimensionId(destDimensionId ?? OVERWORLD_ID);
419 const originX = originTileX + 0.5;
420 const originY = originTileY + 0.5;
421 const destX = destTileX + 0.5;
422 const destY = destTileY + 0.5;
423 const legs = this.#planLegs({
424 fromX: originX,
425 fromY: originY,
426 fromDimensionId: originDim,
427 toX: destX,
428 toY: destY,
429 toDimensionId: destDim
430 });
431 return this.stateDb.insertCourierTransit({
432 senderCharacterId,
433 destinationKind,
434 destinationCharacterId,
435 vaultCharacterId,
436 cargo,
437 originX,
438 originY,
439 destX,
440 destY,
441 originDimensionId: originDim,
442 destDimensionId: destDim,
443 legs,
444 legIndex: 0,
445 traveled: 0,
446 status: "in_transit",
447 entityId: null
448 });
449 }
450
451 #planLegs ({ fromX, fromY, fromDimensionId, toX, toY, toDimensionId })
452 {
453 const planned = planPortalLegs({
454 fromX,
455 fromY,
456 fromDimensionId,
457 toX,
458 toY,
459 toDimensionId,
460 graph: this.doorwayGraph
461 });
462 if (planned.mode !== "fallback")
463 { return planned.legs; }
464 return buildFallbackLegs({
465 fromX,
466 fromY,
467 fromDimensionId,
468 toX,
469 toY,
470 toDimensionId,
471 isSimulating: (tileX, tileY, dimensionId) =>
472 this.simulation.chunkIsSimulating(tileX, tileY, dimensionId),
473 settings: this.simulation.settings
474 }).legs;
475 }
476
477 #repathTransit (transit, fromX, fromY, fromDimensionId, toX, toY, toDimensionId)
478 {
479 if (transit.entityId)
480 {
481 this.simulation.despawnEntity(transit.entityId);
482 transit.entityId = null;
483 }
484 transit.originX = fromX;
485 transit.originY = fromY;
486 transit.originDimensionId = normalizeDimensionId(fromDimensionId);
487 transit.destX = toX;
488 transit.destY = toY;
489 transit.destDimensionId = normalizeDimensionId(toDimensionId);
490 transit.legs = this.#planLegs({
491 fromX,
492 fromY,
493 fromDimensionId: transit.originDimensionId,
494 toX,
495 toY,
496 toDimensionId: transit.destDimensionId
497 });
498 transit.legIndex = 0;
499 transit.traveled = 0;
500 }
501
502 #currentPose (transit)
503 {
504 ensureCourierLegs(transit);
505 const leg = transit.legs[transit.legIndex | 0];
506 const pose = poseOnCourierLeg(leg, transit.traveled);
507 if (pose)
508 { return pose; }
509 if (leg?.kind === "abstract")
510 {
511 return {
512 x: leg.fromX,
513 y: leg.fromY,
514 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID)
515 };
516 }
517 return {
518 x: transit.originX,
519 y: transit.originY,
520 dimensionId: normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID)
521 };
522 }
523
524 #advanceTransit (transit, now, dt, settings)
525 {
526 const events = [];
527 ensureCourierLegs(transit);
528 let remainingDt = Math.max(0, dt);
529 let guard = 0;
530 while (remainingDt > 0 && guard++ < 16)
531 {
532 const leg = transit.legs[transit.legIndex | 0];
533 if (!leg)
534 {
535 events.push(...this.#deliver(transit, now));
536 return events;
537 }
538
539 if (leg.kind === "portal")
540 {
541 transit.traveled = 0;
542 transit.legIndex = (transit.legIndex | 0) + 1;
543 if (transit.entityId)
544 {
545 this.simulation.despawnEntity(transit.entityId);
546 events.push({
547 type: "entity-despawn",
548 entityId: transit.entityId,
549 tileX: Math.floor(leg.fromX),
550 tileY: Math.floor(leg.fromY),
551 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
552 });
553 transit.entityId = null;
554 }
555 if ((transit.legIndex | 0) >= transit.legs.length)
556 {
557 events.push(...this.#deliver(transit, now));
558 return events;
559 }
560 continue;
561 }
562
563 if (leg.kind === "abstract")
564 {
565 if (transit.entityId)
566 {
567 const pose = this.#currentPose(transit);
568 this.simulation.despawnEntity(transit.entityId);
569 events.push({
570 type: "entity-despawn",
571 entityId: transit.entityId,
572 tileX: Math.floor(pose.x),
573 tileY: Math.floor(pose.y),
574 dimensionId: pose.dimensionId
575 });
576 transit.entityId = null;
577 }
578 const advanced = advanceAbstractTravel({
579 traveled: transit.traveled,
580 distance: leg.distance ?? 0,
581 dt: remainingDt,
582 settings
583 });
584 transit.traveled = advanced.traveled;
585 transit.updatedAt = now;
586 if (!advanced.arrived)
587 {
588 this.stateDb.updateCourierTransit(transit);
589 return events;
590 }
591 remainingDt = 0;
592 transit.traveled = 0;
593 transit.legIndex = (transit.legIndex | 0) + 1;
594 if ((transit.legIndex | 0) >= transit.legs.length)
595 {
596 events.push(...this.#deliver(transit, now));
597 return events;
598 }
599 continue;
600 }
601
602 // fly leg
321 const advanced = advanceCourierFlight({
603 const advanced = advanceCourierFlight({
322 originX: transit.originX,
604 originX: leg.fromX,
323 originY: transit.originY,
605 originY: leg.fromY,
324 destX: transit.destX,
606 destX: leg.toX,
325 destY: transit.destY,
607 destY: leg.toY,
326 traveled: transit.traveled,
608 traveled: transit.traveled,
327 dt,
609 dt: remainingDt,
328 settings
610 settings
329 });
611 });
330 transit.traveled = advanced.traveled;
612 transit.traveled = advanced.traveled;
331 transit.updatedAt = now;
613 transit.updatedAt = now;
614 if (!advanced.arrived)
615 {
616 events.push(...this.#syncVisiblePigeon(transit, advanced, now, leg));
617 this.stateDb.updateCourierTransit(transit);
618 return events;
619 }
332
620
333 if (advanced.arrived)
621 remainingDt = 0;
622 transit.traveled = 0;
623 transit.legIndex = (transit.legIndex | 0) + 1;
624 if ((transit.legIndex | 0) >= transit.legs.length)
334 {
625 {
335 events.push(...this.#deliver(transit, now));
626 events.push(...this.#deliver(transit, now));
336 continue;
627 return events;
628 }
629 // Despawn at portal approach so next portal/fly starts clean.
630 if (transit.entityId)
631 {
632 this.simulation.despawnEntity(transit.entityId);
633 events.push({
634 type: "entity-despawn",
635 entityId: transit.entityId,
636 tileX: Math.floor(advanced.x),
637 tileY: Math.floor(advanced.y),
638 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
639 });
640 transit.entityId = null;
337 }
641 }
338
339 events.push(...this.#syncVisiblePigeon(transit, advanced, now));
340 this.stateDb.updateCourierTransit(transit);
341 }
642 }
643 this.stateDb.updateCourierTransit(transit);
342 return events;
644 return events;
343 }
645 }
344
646
@@ -350,10 +652,45 @@ export class CourierService
350 if (onlineId)
652 if (onlineId)
351 {
653 {
352 const pos = this.simulation.positionOf(onlineId);
654 const pos = this.simulation.positionOf(onlineId);
353 if (pos)
655 if (!pos)
656 { return; }
657 const destDim = normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID);
658 const destX = pos.tileX + 0.5;
659 const destY = pos.tileY + 0.5;
660 const prevDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
661 if (destDim !== prevDim)
354 {
662 {
355 transit.destX = pos.tileX + 0.5;
663 const pose = this.#currentPose(transit);
356 transit.destY = pos.tileY + 0.5;
664 this.#repathTransit(
665 transit,
666 pose.x,
667 pose.y,
668 pose.dimensionId,
669 destX,
670 destY,
671 destDim
672 );
673 return;
674 }
675 transit.destX = destX;
676 transit.destY = destY;
677 transit.destDimensionId = destDim;
678 const lastIdx = transit.legs.length - 1;
679 const last = transit.legs[lastIdx];
680 if (last?.kind === "fly"
681 && normalizeDimensionId(last.toDimensionId ?? destDim) === destDim)
682 {
683 const oldToX = last.toX;
684 const oldToY = last.toY;
685 last.toX = destX;
686 last.toY = destY;
687 if ((transit.legIndex | 0) === lastIdx)
688 {
689 const oldTotal = Math.hypot(oldToX - last.fromX, oldToY - last.fromY);
690 const newTotal = Math.hypot(destX - last.fromX, destY - last.fromY);
691 if (oldTotal > 1e-6)
692 { transit.traveled = Math.min(newTotal, (transit.traveled || 0) * (newTotal / oldTotal)); }
693 }
357 }
694 }
358 return;
695 return;
359 }
696 }
@@ -362,18 +699,28 @@ export class CourierService
362
699
363 #routeTransitToBank (transit, vaultCharacterId)
700 #routeTransitToBank (transit, vaultCharacterId)
364 {
701 {
365 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
702 const pose = this.#currentPose(transit);
366 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
703 const bank = this.nearestBank(Math.floor(pose.x), Math.floor(pose.y), pose.dimensionId)
704 ?? this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), transit.destDimensionId)
705 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
367 if (!bank)
706 if (!bank)
368 { return; }
707 { return; }
369 transit.destinationKind = "bank";
708 transit.destinationKind = "bank";
370 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
709 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
371 transit.destX = bank.tileX + 0.5;
710 this.#repathTransit(
372 transit.destY = bank.tileY + 0.5;
711 transit,
712 pose.x,
713 pose.y,
714 pose.dimensionId,
715 bank.tileX + 0.5,
716 bank.tileY + 0.5,
717 bank.dimensionId ?? OVERWORLD_ID
718 );
373 }
719 }
374
720
375 #resolveDestination (destination, originTileX, originTileY)
721 #resolveDestination (destination, originTileX, originTileY, originDimensionId = OVERWORLD_ID)
376 {
722 {
723 const originDim = normalizeDimensionId(originDimensionId);
377 if (destination?.kind === "player")
724 if (destination?.kind === "player")
378 {
725 {
379 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
726 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
@@ -386,8 +733,9 @@ export class CourierService
386 const onlineId = this.simulation.characterEntities.get(character.character_id);
733 const onlineId = this.simulation.characterEntities.get(character.character_id);
387 if (!onlineId)
734 if (!onlineId)
388 {
735 {
389 const bank = this.nearestBank(originTileX, originTileY)
736 const charDim = normalizeDimensionId(character.dimension_id ?? OVERWORLD_ID);
390 ?? this.nearestBank(character.tile_x, character.tile_y);
737 const bank = this.nearestBank(originTileX, originTileY, originDim)
738 ?? this.nearestBank(character.tile_x, character.tile_y, charDim);
391 if (!bank)
739 if (!bank)
392 {
740 {
393 const error = new Error("No bank exists in the world yet.");
741 const error = new Error("No bank exists in the world yet.");
@@ -399,7 +747,8 @@ export class CourierService
399 characterId: character.character_id,
747 characterId: character.character_id,
400 vaultCharacterId: character.character_id,
748 vaultCharacterId: character.character_id,
401 tileX: bank.tileX,
749 tileX: bank.tileX,
402 tileY: bank.tileY
750 tileY: bank.tileY,
751 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
403 };
752 };
404 }
753 }
405 const pos = this.simulation.positionOf(onlineId);
754 const pos = this.simulation.positionOf(onlineId);
@@ -407,36 +756,51 @@ export class CourierService
407 kind: "player",
756 kind: "player",
408 characterId: character.character_id,
757 characterId: character.character_id,
409 tileX: pos.tileX,
758 tileX: pos.tileX,
410 tileY: pos.tileY
759 tileY: pos.tileY,
760 dimensionId: normalizeDimensionId(pos.dimensionId ?? OVERWORLD_ID)
411 };
761 };
412 }
762 }
413 if (destination?.kind === "bank")
763 if (destination?.kind === "bank")
414 {
764 {
415 const bank = this.nearestBank(originTileX, originTileY);
765 const bank = this.nearestBank(originTileX, originTileY, originDim);
416 if (!bank)
766 if (!bank)
417 {
767 {
418 const error = new Error("No bank exists in the world yet.");
768 const error = new Error("No bank exists in the world yet.");
419 error.userFacing = true;
769 error.userFacing = true;
420 throw error;
770 throw error;
421 }
771 }
422 return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
772 return {
773 kind: "bank",
774 tileX: bank.tileX,
775 tileY: bank.tileY,
776 dimensionId: normalizeDimensionId(bank.dimensionId ?? OVERWORLD_ID)
777 };
423 }
778 }
424 const error = new Error("Pigeon destination must be bank or player.");
779 const error = new Error("Pigeon destination must be bank or player.");
425 error.userFacing = true;
780 error.userFacing = true;
426 throw error;
781 throw error;
427 }
782 }
428
783
429 #syncVisiblePigeon (transit, advanced, now)
784 #syncVisiblePigeon (transit, advanced, now, leg)
430 {
785 {
431 const events = [];
786 const events = [];
432 const tileX = Math.floor(advanced.x);
787 const tileX = Math.floor(advanced.x);
433 const tileY = Math.floor(advanced.y);
788 const tileY = Math.floor(advanced.y);
434 if (!this.simulation.chunkIsSimulating(tileX, tileY))
789 const dimensionId = normalizeDimensionId(
790 leg?.fromDimensionId ?? transit.originDimensionId ?? OVERWORLD_ID
791 );
792 if (!this.simulation.chunkIsSimulating(tileX, tileY, dimensionId))
435 {
793 {
436 if (transit.entityId)
794 if (transit.entityId)
437 {
795 {
438 this.simulation.despawnEntity(transit.entityId);
796 this.simulation.despawnEntity(transit.entityId);
439 events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
797 events.push({
798 type: "entity-despawn",
799 entityId: transit.entityId,
800 tileX,
801 tileY,
802 dimensionId
803 });
440 transit.entityId = null;
804 transit.entityId = null;
441 }
805 }
442 return events;
806 return events;
@@ -447,14 +811,14 @@ export class CourierService
447 transit.entityId = null;
811 transit.entityId = null;
448 const def = mobDefinition(MobId.pigeon);
812 const def = mobDefinition(MobId.pigeon);
449 const entityId = this.simulation.spawnEntity({
813 const entityId = this.simulation.spawnEntity({
450 position: { tileX, tileY },
814 position: { tileX, tileY, dimensionId },
451 movement: { gait: GAIT.walk, walkCarry: 0 },
815 movement: { gait: GAIT.walk, walkCarry: 0 },
452 path: { tiles: [] },
816 path: { tiles: [] },
453 flight: {
817 flight: {
454 x: advanced.x,
818 x: advanced.x,
455 y: advanced.y,
819 y: advanced.y,
456 targetX: transit.destX,
820 targetX: leg?.toX ?? transit.destX,
457 targetY: transit.destY,
821 targetY: leg?.toY ?? transit.destY,
458 speed: advanced.speed,
822 speed: advanced.speed,
459 nextPickAt: now + 60_000,
823 nextPickAt: now + 60_000,
460 lastAt: now,
824 lastAt: now,
@@ -477,8 +841,8 @@ export class CourierService
477 const moved = this.simulation.updateCourierFlight(transit.entityId, {
841 const moved = this.simulation.updateCourierFlight(transit.entityId, {
478 x: advanced.x,
842 x: advanced.x,
479 y: advanced.y,
843 y: advanced.y,
480 targetX: transit.destX,
844 targetX: leg?.toX ?? transit.destX,
481 targetY: transit.destY,
845 targetY: leg?.toY ?? transit.destY,
482 speed: advanced.speed,
846 speed: advanced.speed,
483 lastAt: now,
847 lastAt: now,
484 courierId: transit.courierId
848 courierId: transit.courierId
@@ -486,7 +850,13 @@ export class CourierService
486 if (moved?.despawned)
850 if (moved?.despawned)
487 {
851 {
488 transit.entityId = null;
852 transit.entityId = null;
489 events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
853 events.push({
854 type: "entity-despawn",
855 entityId: moved.entityId,
856 tileX,
857 tileY,
858 dimensionId
859 });
490 }
860 }
491 else if (moved?.event)
861 else if (moved?.event)
492 { events.push(moved.event); }
862 { events.push(moved.event); }
@@ -496,6 +866,7 @@ export class CourierService
496 #deliver (transit, now)
866 #deliver (transit, now)
497 {
867 {
498 const events = [];
868 const events = [];
869 const destDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
499 if (transit.entityId)
870 if (transit.entityId)
500 {
871 {
501 this.simulation.despawnEntity(transit.entityId);
872 this.simulation.despawnEntity(transit.entityId);
@@ -503,7 +874,8 @@ export class CourierService
503 type: "entity-despawn",
874 type: "entity-despawn",
504 entityId: transit.entityId,
875 entityId: transit.entityId,
505 tileX: Math.floor(transit.destX),
876 tileX: Math.floor(transit.destX),
506 tileY: Math.floor(transit.destY)
877 tileY: Math.floor(transit.destY),
878 dimensionId: destDim
507 });
879 });
508 transit.entityId = null;
880 transit.entityId = null;
509 }
881 }
@@ -524,17 +896,26 @@ export class CourierService
524 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
896 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
525 if (!delivered)
897 if (!delivered)
526 {
898 {
527 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
899 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY), destDim)
528 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
900 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY), transit.originDimensionId);
529 if (bank)
901 if (bank)
530 {
902 {
531 transit.originX = transit.destX;
903 const pose = {
532 transit.originY = transit.destY;
904 x: transit.destX,
533 transit.destX = bank.tileX + 0.5;
905 y: transit.destY,
534 transit.destY = bank.tileY + 0.5;
906 dimensionId: destDim
535 transit.traveled = 0;
907 };
536 transit.destinationKind = "bank";
908 transit.destinationKind = "bank";
537 transit.vaultCharacterId = transit.destinationCharacterId;
909 transit.vaultCharacterId = transit.destinationCharacterId;
910 this.#repathTransit(
911 transit,
912 pose.x,
913 pose.y,
914 pose.dimensionId,
915 bank.tileX + 0.5,
916 bank.tileY + 0.5,
917 bank.dimensionId ?? OVERWORLD_ID
918 );
538 transit.updatedAt = now;
919 transit.updatedAt = now;
539 this.stateDb.updateCourierTransit(transit);
920 this.stateDb.updateCourierTransit(transit);
540 events.push({
921 events.push({
@@ -772,12 +1153,13 @@ export class CourierService
772 };
1153 };
773 }
1154 }
774
1155
775 #dispatchBankRestNotice (characterId, tileX, tileY)
1156 #dispatchBankRestNotice (characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
776 {
1157 {
777 const entries = this.stateDb.listBankRestNotices(characterId);
1158 const entries = this.stateDb.listBankRestNotices(characterId);
778 if (!entries.length)
1159 if (!entries.length)
779 { return null; }
1160 { return null; }
780 const bank = this.nearestBank(tileX, tileY);
1161 const dim = normalizeDimensionId(dimensionId);
1162 const bank = this.nearestBank(tileX, tileY, dim);
781 if (!bank)
1163 if (!bank)
782 { return null; }
1164 { return null; }
783
1165
@@ -798,6 +1180,7 @@ export class CourierService
798 characterId,
1180 characterId,
799 originTileX: bank.tileX,
1181 originTileX: bank.tileX,
800 originTileY: bank.tileY,
1182 originTileY: bank.tileY,
1183 originDimensionId: bank.dimensionId ?? OVERWORLD_ID,
801 stack
1184 stack
802 });
1185 });
803 }
1186 }
server/src/ecs/serialize.js +4 −1
@@ -155,6 +155,7 @@ export function replicationSpawn (view)
155 155 accountId: view.accountId ?? null,
156 156 tileX: view.tileX,
157 157 tileY: view.tileY,
158 dimensionId: view.dimensionId,
158 159 worldX: view.worldX,
159 160 worldY: view.worldY,
160 161 gait: view.gait,
@@ -191,6 +192,7 @@ export function replicationMove (view, fromTileX, fromTileY)
191 192 entityId: view.entityId,
192 193 tileX: view.tileX,
193 194 tileY: view.tileY,
195 dimensionId: view.dimensionId,
194 196 worldX: view.worldX,
195 197 worldY: view.worldY,
196 198 gait: view.gait,
@@ -225,6 +227,7 @@ export function replicationDespawn (view)
225 227 type: "entity-despawn",
226 228 entityId: view.entityId,
227 229 tileX: view.tileX,
228 tileY: view.tileY
230 tileY: view.tileY,
231 dimensionId: view.dimensionId
229 232 };
230 233 }
@@ -155,6 +155,7 @@ export function replicationSpawn (view)
155 accountId: view.accountId ?? null,
155 accountId: view.accountId ?? null,
156 tileX: view.tileX,
156 tileX: view.tileX,
157 tileY: view.tileY,
157 tileY: view.tileY,
158 dimensionId: view.dimensionId,
158 worldX: view.worldX,
159 worldX: view.worldX,
159 worldY: view.worldY,
160 worldY: view.worldY,
160 gait: view.gait,
161 gait: view.gait,
@@ -191,6 +192,7 @@ export function replicationMove (view, fromTileX, fromTileY)
191 entityId: view.entityId,
192 entityId: view.entityId,
192 tileX: view.tileX,
193 tileX: view.tileX,
193 tileY: view.tileY,
194 tileY: view.tileY,
195 dimensionId: view.dimensionId,
194 worldX: view.worldX,
196 worldX: view.worldX,
195 worldY: view.worldY,
197 worldY: view.worldY,
196 gait: view.gait,
198 gait: view.gait,
@@ -225,6 +227,7 @@ export function replicationDespawn (view)
225 type: "entity-despawn",
227 type: "entity-despawn",
226 entityId: view.entityId,
228 entityId: view.entityId,
227 tileX: view.tileX,
229 tileX: view.tileX,
228 tileY: view.tileY
230 tileY: view.tileY,
231 dimensionId: view.dimensionId
229 };
232 };
230}
233}
server/src/editor/service.js +36 −0
@@ -447,6 +447,41 @@ export class EditorService
447 447 };
448 448 }
449 449
450
451 /** Flat list of authored spawners across all editor-revision chunks. */
452 listSpawners ()
453 {
454 const revisionId = this.worldDb.getEditorRevisionId();
455 const settings = this.worldDb.getLiveSettings();
456 const out = [];
457 const seen = new Set();
458 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of this.worldDb.listChunkCoords(revisionId))
459 {
460 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
461 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
462 if (!row)
463 { continue; }
464 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
465 for (const entry of data.spawners ?? [])
466 {
467 const config = entry?.config;
468 const spawnerId = String(config?.spawnerId ?? "").trim();
469 if (!spawnerId || seen.has(spawnerId))
470 { continue; }
471 seen.add(spawnerId);
472 out.push({
473 spawnerId,
474 mobTypeId: config.mobTypeId ?? null,
475 dimensionId: dim,
476 tileX: localToTile(cx, entry.localX),
477 tileY: localToTile(cy, entry.localY)
478 });
479 }
480 }
481 out.sort((a, b) => String(a.spawnerId).localeCompare(String(b.spawnerId)));
482 return out;
483 }
484
450 485 loadQuests ()
451 486 {
452 487 const revisionId = this.worldDb.getEditorRevisionId();
@@ -456,6 +491,7 @@ export class EditorService
456 491 pendingRevisionId: this.worldDb.getPendingRevisionId(),
457 492 activeRevisionId: this.worldDb.getActiveRevisionId(),
458 493 quests,
494 spawners: this.listSpawners(),
459 495 changelog: this.#enrichChangelog(this.worldDb.listQuestChangelog())
460 496 };
461 497 }
@@ -447,6 +447,41 @@ export class EditorService
447 };
447 };
448 }
448 }
449
449
450
451 /** Flat list of authored spawners across all editor-revision chunks. */
452 listSpawners ()
453 {
454 const revisionId = this.worldDb.getEditorRevisionId();
455 const settings = this.worldDb.getLiveSettings();
456 const out = [];
457 const seen = new Set();
458 for (const { chunk_x: cx, chunk_y: cy, dimension_id: dimensionId } of this.worldDb.listChunkCoords(revisionId))
459 {
460 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
461 const row = this.worldDb.getChunkVersion(cx, cy, revisionId, dim);
462 if (!row)
463 { continue; }
464 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
465 for (const entry of data.spawners ?? [])
466 {
467 const config = entry?.config;
468 const spawnerId = String(config?.spawnerId ?? "").trim();
469 if (!spawnerId || seen.has(spawnerId))
470 { continue; }
471 seen.add(spawnerId);
472 out.push({
473 spawnerId,
474 mobTypeId: config.mobTypeId ?? null,
475 dimensionId: dim,
476 tileX: localToTile(cx, entry.localX),
477 tileY: localToTile(cy, entry.localY)
478 });
479 }
480 }
481 out.sort((a, b) => String(a.spawnerId).localeCompare(String(b.spawnerId)));
482 return out;
483 }
484
450 loadQuests ()
485 loadQuests ()
451 {
486 {
452 const revisionId = this.worldDb.getEditorRevisionId();
487 const revisionId = this.worldDb.getEditorRevisionId();
@@ -456,6 +491,7 @@ export class EditorService
456 pendingRevisionId: this.worldDb.getPendingRevisionId(),
491 pendingRevisionId: this.worldDb.getPendingRevisionId(),
457 activeRevisionId: this.worldDb.getActiveRevisionId(),
492 activeRevisionId: this.worldDb.getActiveRevisionId(),
458 quests,
493 quests,
494 spawners: this.listSpawners(),
459 changelog: this.#enrichChangelog(this.worldDb.listQuestChangelog())
495 changelog: this.#enrichChangelog(this.worldDb.listQuestChangelog())
460 };
496 };
461 }
497 }
server/src/gifts/service.js +3 −1
@@ -210,11 +210,13 @@ export class GiftService
210 210 {
211 211 const originTileX = character.tile_x | 0;
212 212 const originTileY = character.tile_y | 0;
213 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY);
213 const originDim = character.dimension_id ?? undefined;
214 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY, originDim);
214 215 this.simulation.courier.enqueueSystemLetter({
215 216 characterId: character.character_id,
216 217 originTileX: bank?.tileX ?? originTileX,
217 218 originTileY: bank?.tileY ?? originTileY,
219 originDimensionId: bank?.dimensionId ?? originDim,
218 220 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
219 221 authorOrganization: QUESTWARD_GIFT_ORG,
220 222 body
@@ -210,11 +210,13 @@ export class GiftService
210 {
210 {
211 const originTileX = character.tile_x | 0;
211 const originTileX = character.tile_x | 0;
212 const originTileY = character.tile_y | 0;
212 const originTileY = character.tile_y | 0;
213 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY);
213 const originDim = character.dimension_id ?? undefined;
214 const bank = this.simulation.courier?.nearestBank?.(originTileX, originTileY, originDim);
214 this.simulation.courier.enqueueSystemLetter({
215 this.simulation.courier.enqueueSystemLetter({
215 characterId: character.character_id,
216 characterId: character.character_id,
216 originTileX: bank?.tileX ?? originTileX,
217 originTileX: bank?.tileX ?? originTileX,
217 originTileY: bank?.tileY ?? originTileY,
218 originTileY: bank?.tileY ?? originTileY,
219 originDimensionId: bank?.dimensionId ?? originDim,
218 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
220 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
219 authorOrganization: QUESTWARD_GIFT_ORG,
221 authorOrganization: QUESTWARD_GIFT_ORG,
220 body
222 body
server/src/market/service.js +2 −0
@@ -677,6 +677,7 @@ export class MarketService
677 677 characterId,
678 678 originTileX: origin.tileX,
679 679 originTileY: origin.tileY,
680 originDimensionId: origin.dimensionId,
680 681 authorDisplayName: name,
681 682 authorOrganization: CENTRAL_EXCHANGE_ORG,
682 683 body,
@@ -690,6 +691,7 @@ export class MarketService
690 691 senderCharacterId: characterId,
691 692 originTileX: origin.tileX,
692 693 originTileY: origin.tileY,
694 originDimensionId: origin.dimensionId,
693 695 destination: { kind: "bank" },
694 696 cargo
695 697 });
@@ -677,6 +677,7 @@ export class MarketService
677 characterId,
677 characterId,
678 originTileX: origin.tileX,
678 originTileX: origin.tileX,
679 originTileY: origin.tileY,
679 originTileY: origin.tileY,
680 originDimensionId: origin.dimensionId,
680 authorDisplayName: name,
681 authorDisplayName: name,
681 authorOrganization: CENTRAL_EXCHANGE_ORG,
682 authorOrganization: CENTRAL_EXCHANGE_ORG,
682 body,
683 body,
@@ -690,6 +691,7 @@ export class MarketService
690 senderCharacterId: characterId,
691 senderCharacterId: characterId,
691 originTileX: origin.tileX,
692 originTileX: origin.tileX,
692 originTileY: origin.tileY,
693 originTileY: origin.tileY,
694 originDimensionId: origin.dimensionId,
693 destination: { kind: "bank" },
695 destination: { kind: "bank" },
694 cargo
696 cargo
695 });
697 });
server/src/persistence/stateDb.js +47 −7
@@ -104,6 +104,10 @@ CREATE TABLE IF NOT EXISTS courier_transits (
104 104 origin_y REAL NOT NULL,
105 105 dest_x REAL NOT NULL,
106 106 dest_y REAL NOT NULL,
107 origin_dimension_id TEXT NOT NULL DEFAULT 'overworld',
108 dest_dimension_id TEXT NOT NULL DEFAULT 'overworld',
109 legs_blob TEXT,
110 leg_index INTEGER NOT NULL DEFAULT 0,
107 111 traveled REAL NOT NULL DEFAULT 0,
108 112 status TEXT NOT NULL,
109 113 entity_id INTEGER,
@@ -160,6 +164,7 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries (
160 164 sender_character_id INTEGER NOT NULL,
161 165 origin_tile_x INTEGER NOT NULL,
162 166 origin_tile_y INTEGER NOT NULL,
167 origin_dimension_id TEXT NOT NULL DEFAULT 'overworld',
163 168 destination_kind TEXT NOT NULL,
164 169 destination_character_id INTEGER,
165 170 vault_character_id INTEGER,
@@ -255,6 +260,17 @@ export class StateDatabase
255 260 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
256 261 if (!courierColumns.some((column) => column.name === "vault_character_id"))
257 262 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
263 if (!courierColumns.some((column) => column.name === "origin_dimension_id"))
264 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN origin_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
265 if (!courierColumns.some((column) => column.name === "dest_dimension_id"))
266 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN dest_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
267 if (!courierColumns.some((column) => column.name === "legs_blob"))
268 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN legs_blob TEXT"); }
269 if (!courierColumns.some((column) => column.name === "leg_index"))
270 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN leg_index INTEGER NOT NULL DEFAULT 0"); }
271 const heldCourierColumns = this.db.prepare("PRAGMA table_info(held_courier_deliveries)").all();
272 if (!heldCourierColumns.some((column) => column.name === "origin_dimension_id"))
273 { this.db.exec("ALTER TABLE held_courier_deliveries ADD COLUMN origin_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
258 274 if (!bagColumns.some((column) => column.name === "spells_blob"))
259 275 {
260 276 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
@@ -1644,8 +1660,8 @@ export class StateDatabase
1644 1660 INSERT INTO courier_transits (
1645 1661 sender_character_id, destination_kind, destination_character_id, cargo_blob,
1646 1662 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
1647 vault_character_id
1648 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1663 vault_character_id, origin_dimension_id, dest_dimension_id, legs_blob, leg_index
1664 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1649 1665 `).run(
1650 1666 transit.senderCharacterId,
1651 1667 transit.destinationKind,
@@ -1660,7 +1676,11 @@ export class StateDatabase
1660 1676 transit.entityId ?? null,
1661 1677 now,
1662 1678 transit.createdAt ?? now,
1663 transit.vaultCharacterId ?? null
1679 transit.vaultCharacterId ?? null,
1680 transit.originDimensionId ?? "overworld",
1681 transit.destDimensionId ?? "overworld",
1682 transit.legs != null ? JSON.stringify(transit.legs) : null,
1683 transit.legIndex | 0
1664 1684 );
1665 1685 return this.getCourierTransit(Number(result.lastInsertRowid));
1666 1686 }
@@ -1684,7 +1704,8 @@ export class StateDatabase
1684 1704 UPDATE courier_transits
1685 1705 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
1686 1706 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
1687 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
1707 destination_kind = ?, destination_character_id = ?, vault_character_id = ?,
1708 origin_dimension_id = ?, dest_dimension_id = ?, legs_blob = ?, leg_index = ?
1688 1709 WHERE courier_id = ?
1689 1710 `).run(
1690 1711 transit.traveled ?? 0,
@@ -1698,6 +1719,10 @@ export class StateDatabase
1698 1719 transit.destinationKind,
1699 1720 transit.destinationCharacterId ?? null,
1700 1721 transit.vaultCharacterId ?? null,
1722 transit.originDimensionId ?? "overworld",
1723 transit.destDimensionId ?? "overworld",
1724 transit.legs != null ? JSON.stringify(transit.legs) : null,
1725 transit.legIndex | 0,
1701 1726 transit.courierId
1702 1727 );
1703 1728 }
@@ -1744,8 +1769,9 @@ export class StateDatabase
1744 1769 const result = this.db.prepare(`
1745 1770 INSERT INTO held_courier_deliveries (
1746 1771 character_id, sender_character_id, origin_tile_x, origin_tile_y,
1747 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
1748 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1772 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at,
1773 origin_dimension_id
1774 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1749 1775 `).run(
1750 1776 delivery.characterId,
1751 1777 delivery.senderCharacterId,
@@ -1755,7 +1781,8 @@ export class StateDatabase
1755 1781 delivery.destinationCharacterId ?? null,
1756 1782 delivery.vaultCharacterId ?? null,
1757 1783 JSON.stringify(delivery.cargo),
1758 now
1784 now,
1785 delivery.originDimensionId ?? "overworld"
1759 1786 );
1760 1787 return Number(result.lastInsertRowid);
1761 1788 }
@@ -1996,6 +2023,14 @@ function parseBag (row, characterId)
1996 2023
1997 2024 function parseCourierTransit (row)
1998 2025 {
2026 let legs = null;
2027 if (row.legs_blob)
2028 {
2029 try
2030 { legs = JSON.parse(row.legs_blob); }
2031 catch
2032 { legs = null; }
2033 }
1999 2034 return {
2000 2035 courierId: row.courier_id,
2001 2036 senderCharacterId: row.sender_character_id,
@@ -2007,6 +2042,10 @@ function parseCourierTransit (row)
2007 2042 originY: row.origin_y,
2008 2043 destX: row.dest_x,
2009 2044 destY: row.dest_y,
2045 originDimensionId: row.origin_dimension_id ?? "overworld",
2046 destDimensionId: row.dest_dimension_id ?? "overworld",
2047 legs: Array.isArray(legs) ? legs : null,
2048 legIndex: row.leg_index | 0,
2010 2049 traveled: row.traveled,
2011 2050 status: row.status,
2012 2051 entityId: row.entity_id,
@@ -2023,6 +2062,7 @@ function parseHeldCourierDelivery (row)
2023 2062 senderCharacterId: row.sender_character_id,
2024 2063 originTileX: row.origin_tile_x,
2025 2064 originTileY: row.origin_tile_y,
2065 originDimensionId: row.origin_dimension_id ?? "overworld",
2026 2066 destinationKind: row.destination_kind,
2027 2067 destinationCharacterId: row.destination_character_id,
2028 2068 vaultCharacterId: row.vault_character_id,
@@ -104,6 +104,10 @@ CREATE TABLE IF NOT EXISTS courier_transits (
104 origin_y REAL NOT NULL,
104 origin_y REAL NOT NULL,
105 dest_x REAL NOT NULL,
105 dest_x REAL NOT NULL,
106 dest_y REAL NOT NULL,
106 dest_y REAL NOT NULL,
107 origin_dimension_id TEXT NOT NULL DEFAULT 'overworld',
108 dest_dimension_id TEXT NOT NULL DEFAULT 'overworld',
109 legs_blob TEXT,
110 leg_index INTEGER NOT NULL DEFAULT 0,
107 traveled REAL NOT NULL DEFAULT 0,
111 traveled REAL NOT NULL DEFAULT 0,
108 status TEXT NOT NULL,
112 status TEXT NOT NULL,
109 entity_id INTEGER,
113 entity_id INTEGER,
@@ -160,6 +164,7 @@ CREATE TABLE IF NOT EXISTS held_courier_deliveries (
160 sender_character_id INTEGER NOT NULL,
164 sender_character_id INTEGER NOT NULL,
161 origin_tile_x INTEGER NOT NULL,
165 origin_tile_x INTEGER NOT NULL,
162 origin_tile_y INTEGER NOT NULL,
166 origin_tile_y INTEGER NOT NULL,
167 origin_dimension_id TEXT NOT NULL DEFAULT 'overworld',
163 destination_kind TEXT NOT NULL,
168 destination_kind TEXT NOT NULL,
164 destination_character_id INTEGER,
169 destination_character_id INTEGER,
165 vault_character_id INTEGER,
170 vault_character_id INTEGER,
@@ -255,6 +260,17 @@ export class StateDatabase
255 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
260 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
256 if (!courierColumns.some((column) => column.name === "vault_character_id"))
261 if (!courierColumns.some((column) => column.name === "vault_character_id"))
257 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
262 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
263 if (!courierColumns.some((column) => column.name === "origin_dimension_id"))
264 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN origin_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
265 if (!courierColumns.some((column) => column.name === "dest_dimension_id"))
266 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN dest_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
267 if (!courierColumns.some((column) => column.name === "legs_blob"))
268 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN legs_blob TEXT"); }
269 if (!courierColumns.some((column) => column.name === "leg_index"))
270 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN leg_index INTEGER NOT NULL DEFAULT 0"); }
271 const heldCourierColumns = this.db.prepare("PRAGMA table_info(held_courier_deliveries)").all();
272 if (!heldCourierColumns.some((column) => column.name === "origin_dimension_id"))
273 { this.db.exec("ALTER TABLE held_courier_deliveries ADD COLUMN origin_dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
258 if (!bagColumns.some((column) => column.name === "spells_blob"))
274 if (!bagColumns.some((column) => column.name === "spells_blob"))
259 {
275 {
260 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
276 this.db.exec("ALTER TABLE character_bags ADD COLUMN spells_blob TEXT NOT NULL DEFAULT '{}'");
@@ -1644,8 +1660,8 @@ export class StateDatabase
1644 INSERT INTO courier_transits (
1660 INSERT INTO courier_transits (
1645 sender_character_id, destination_kind, destination_character_id, cargo_blob,
1661 sender_character_id, destination_kind, destination_character_id, cargo_blob,
1646 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
1662 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
1647 vault_character_id
1663 vault_character_id, origin_dimension_id, dest_dimension_id, legs_blob, leg_index
1648 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1664 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1649 `).run(
1665 `).run(
1650 transit.senderCharacterId,
1666 transit.senderCharacterId,
1651 transit.destinationKind,
1667 transit.destinationKind,
@@ -1660,7 +1676,11 @@ export class StateDatabase
1660 transit.entityId ?? null,
1676 transit.entityId ?? null,
1661 now,
1677 now,
1662 transit.createdAt ?? now,
1678 transit.createdAt ?? now,
1663 transit.vaultCharacterId ?? null
1679 transit.vaultCharacterId ?? null,
1680 transit.originDimensionId ?? "overworld",
1681 transit.destDimensionId ?? "overworld",
1682 transit.legs != null ? JSON.stringify(transit.legs) : null,
1683 transit.legIndex | 0
1664 );
1684 );
1665 return this.getCourierTransit(Number(result.lastInsertRowid));
1685 return this.getCourierTransit(Number(result.lastInsertRowid));
1666 }
1686 }
@@ -1684,7 +1704,8 @@ export class StateDatabase
1684 UPDATE courier_transits
1704 UPDATE courier_transits
1685 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
1705 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
1686 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
1706 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
1687 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
1707 destination_kind = ?, destination_character_id = ?, vault_character_id = ?,
1708 origin_dimension_id = ?, dest_dimension_id = ?, legs_blob = ?, leg_index = ?
1688 WHERE courier_id = ?
1709 WHERE courier_id = ?
1689 `).run(
1710 `).run(
1690 transit.traveled ?? 0,
1711 transit.traveled ?? 0,
@@ -1698,6 +1719,10 @@ export class StateDatabase
1698 transit.destinationKind,
1719 transit.destinationKind,
1699 transit.destinationCharacterId ?? null,
1720 transit.destinationCharacterId ?? null,
1700 transit.vaultCharacterId ?? null,
1721 transit.vaultCharacterId ?? null,
1722 transit.originDimensionId ?? "overworld",
1723 transit.destDimensionId ?? "overworld",
1724 transit.legs != null ? JSON.stringify(transit.legs) : null,
1725 transit.legIndex | 0,
1701 transit.courierId
1726 transit.courierId
1702 );
1727 );
1703 }
1728 }
@@ -1744,8 +1769,9 @@ export class StateDatabase
1744 const result = this.db.prepare(`
1769 const result = this.db.prepare(`
1745 INSERT INTO held_courier_deliveries (
1770 INSERT INTO held_courier_deliveries (
1746 character_id, sender_character_id, origin_tile_x, origin_tile_y,
1771 character_id, sender_character_id, origin_tile_x, origin_tile_y,
1747 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
1772 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at,
1748 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1773 origin_dimension_id
1774 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1749 `).run(
1775 `).run(
1750 delivery.characterId,
1776 delivery.characterId,
1751 delivery.senderCharacterId,
1777 delivery.senderCharacterId,
@@ -1755,7 +1781,8 @@ export class StateDatabase
1755 delivery.destinationCharacterId ?? null,
1781 delivery.destinationCharacterId ?? null,
1756 delivery.vaultCharacterId ?? null,
1782 delivery.vaultCharacterId ?? null,
1757 JSON.stringify(delivery.cargo),
1783 JSON.stringify(delivery.cargo),
1758 now
1784 now,
1785 delivery.originDimensionId ?? "overworld"
1759 );
1786 );
1760 return Number(result.lastInsertRowid);
1787 return Number(result.lastInsertRowid);
1761 }
1788 }
@@ -1996,6 +2023,14 @@ function parseBag (row, characterId)
1996
2023
1997function parseCourierTransit (row)
2024function parseCourierTransit (row)
1998{
2025{
2026 let legs = null;
2027 if (row.legs_blob)
2028 {
2029 try
2030 { legs = JSON.parse(row.legs_blob); }
2031 catch
2032 { legs = null; }
2033 }
1999 return {
2034 return {
2000 courierId: row.courier_id,
2035 courierId: row.courier_id,
2001 senderCharacterId: row.sender_character_id,
2036 senderCharacterId: row.sender_character_id,
@@ -2007,6 +2042,10 @@ function parseCourierTransit (row)
2007 originY: row.origin_y,
2042 originY: row.origin_y,
2008 destX: row.dest_x,
2043 destX: row.dest_x,
2009 destY: row.dest_y,
2044 destY: row.dest_y,
2045 originDimensionId: row.origin_dimension_id ?? "overworld",
2046 destDimensionId: row.dest_dimension_id ?? "overworld",
2047 legs: Array.isArray(legs) ? legs : null,
2048 legIndex: row.leg_index | 0,
2010 traveled: row.traveled,
2049 traveled: row.traveled,
2011 status: row.status,
2050 status: row.status,
2012 entityId: row.entity_id,
2051 entityId: row.entity_id,
@@ -2023,6 +2062,7 @@ function parseHeldCourierDelivery (row)
2023 senderCharacterId: row.sender_character_id,
2062 senderCharacterId: row.sender_character_id,
2024 originTileX: row.origin_tile_x,
2063 originTileX: row.origin_tile_x,
2025 originTileY: row.origin_tile_y,
2064 originTileY: row.origin_tile_y,
2065 originDimensionId: row.origin_dimension_id ?? "overworld",
2026 destinationKind: row.destination_kind,
2066 destinationKind: row.destination_kind,
2027 destinationCharacterId: row.destination_character_id,
2067 destinationCharacterId: row.destination_character_id,
2028 vaultCharacterId: row.vault_character_id,
2068 vaultCharacterId: row.vault_character_id,
server/src/quests/runtime.js +1026 −1006
@@ -1,1006 +1,1026 @@
1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3 import {
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
6 } from "../../../shared/quests/objectiveProgress.js";
7 import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10 import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11 import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12 import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
13 import {
14 formatDialogueRewardMessage,
15 formatDialogueQuestRewardMessage,
16 formatDialogueTakeMessage
17 } from "../../../shared/quests/dialogueRewards.js";
18 import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
19 import {
20 formatQuestBankRewardLetterBody,
21 QUESTWARD_GIFT_AUTHOR,
22 QUESTWARD_GIFT_ORG
23 } from "../../../shared/courier/questRewardLetters.js";
24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25 import { floorDiv } from "../world/coordinates.js";
26 import { WorkerMessage } from "../simulation/protocol.js";
27
28 /**
29 * Quest progress + dialogue sessions (main simulation thread).
30 */
31 export class QuestRuntime
32 {
33 constructor ({ stateDb, content, simulation })
34 {
35 this.stateDb = stateDb;
36 this.content = content;
37 this.simulation = simulation;
38 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
39 this.sessions = new Map();
40 }
41
42 reloadContent ()
43 {
44 this.content.reload();
45 }
46
47 closeAllSessions ()
48 {
49 for (const characterId of [...this.sessions.keys()])
50 { this.closeDialogue(characterId, "revision"); }
51 }
52
53 questSnapshot (characterId)
54 {
55 const states = this.stateDb.listQuestStates(characterId)
56 .filter((row) => row.state !== "not-started");
57 const quests = [];
58 const playerView = this.playerViewFor(characterId);
59 for (const row of states)
60 {
61 const def = this.content.quest(row.questId);
62 if (!def)
63 {
64 quests.push({
65 questId: row.questId,
66 title: "Quest unavailable",
67 orphaned: true,
68 state: row.state,
69 description: "",
70 step: null,
71 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
72 });
73 continue;
74 }
75 const stepIndex = typeof row.state === "number" ? row.state : null;
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
77 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78 const ctx = stepDef
79 ? this.buildConditionContext(characterId, playerView, row.questId)
80 : null;
81 quests.push({
82 questId: def.questId,
83 title: def.title,
84 orphaned: false,
85 state: row.state,
86 description: def.description,
87 step: stepDef
88 ? {
89 stepId: stepDef.stepId,
90 title: stepDef.title,
91 description: stepDef.description,
92 objectives: stepDef.objectives.map((obj) =>
93 {
94 const done = completedObjectiveIds.includes(obj.objectiveId);
95 const progress = countableObjectiveProgress(obj.when, ctx);
96 return {
97 objectiveId: obj.objectiveId,
98 text: obj.text,
99 done,
100 current: progress?.current ?? null,
101 required: progress?.required ?? null
102 };
103 })
104 }
105 : null,
106 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
107 });
108 }
109 quests.sort((a, b) =>
110 {
111 const aDone = a.state === "completed" ? 1 : 0;
112 const bDone = b.state === "completed" ? 1 : 0;
113 if (aDone !== bDone)
114 { return aDone - bDone; }
115 return String(a.title).localeCompare(String(b.title));
116 });
117 return { quests };
118 }
119
120 playerViewFor (characterId)
121 {
122 const entityId = this.simulation.characterEntities.get(characterId | 0);
123 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
124 const skills = this.stateDb.getSkills(characterId) ?? {};
125 let hp = 1;
126 let maxHp = 1;
127 let stamina = 1;
128 let maxStamina = 1;
129 if (entityId != null && record)
130 {
131 const staminaComp = this.simulation.staminaOf(entityId);
132 if (staminaComp)
133 {
134 stamina = Number(staminaComp.current) || 0;
135 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
136 }
137 const worker = this.simulation.workers[record.workerId];
138 const view = worker?.call?.({
139 type: WorkerMessage.inspect,
140 entityId
141 });
142 if (view && view.health != null)
143 {
144 hp = Number(view.health) || 0;
145 maxHp = Math.max(1, Number(view.maxHealth) || 1);
146 }
147 }
148 return {
149 tileX: record?.tileX | 0,
150 tileY: record?.tileY | 0,
151 dimensionId: record?.dimensionId ?? "overworld",
152 skills,
153 hp,
154 maxHp,
155 stamina,
156 maxStamina
157 };
158 }
159
160 buildConditionContext (characterId, playerView, activeQuestId = null)
161 {
162 const bag = this.#loadBag(characterId);
163 const inventory = bag?.inventory ?? [];
164 const tileX = playerView?.tileX | 0;
165 const tileY = playerView?.tileY | 0;
166 const dimensionId = playerView?.dimensionId ?? "overworld";
167 const chunkX = floorDiv(tileX, CHUNK_SIZE);
168 const chunkY = floorDiv(tileY, CHUNK_SIZE);
169 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
170 return {
171 tileX,
172 tileY,
173 chunkX,
174 chunkY,
175 dimensionId,
176 hp: playerView?.hp ?? 0,
177 maxHp: playerView?.maxHp ?? 1,
178 stamina: playerView?.stamina ?? 0,
179 maxStamina: playerView?.maxStamina ?? 1,
180 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
182 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183 dialogueTriggerLatched: (dialogueId, trigger) =>
184 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
185 skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
186 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
187 killCount: (condition) =>
188 {
189 if (!questRow)
190 { return 0; }
191 return questRow.progress?.counters?.[killKey(condition)] | 0;
192 },
193 interactBlockDone: (condition) =>
194 {
195 if (!questRow)
196 { return false; }
197 return !!questRow.progress?.interacts?.[interactKey(condition)];
198 }
199 };
200 }
201
202 tryOpenDialogue (characterId, entityId, dialogueId)
203 {
204 const tree = this.content.dialogue(dialogueId);
205 if (!tree)
206 { return { ok: false, error: "Nothing to say." }; }
207 this.closeDialogue(characterId, "replace");
208 const playerView = this.playerViewFor(characterId);
209 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
210 }
211
212 chooseDialogue (characterId, triggerId)
213 {
214 const session = this.sessions.get(characterId | 0);
215 if (!session)
216 { return { ok: false, error: "No dialogue open." }; }
217 if (session.phase === "lines")
218 { return { ok: false, error: "Finish reading first." }; }
219 if (session.phase === "rewards")
220 { return { ok: false, error: "Finish reading first." }; }
221 const tree = this.content.dialogue(session.dialogueId);
222 if (!tree)
223 {
224 this.closeDialogue(characterId, "missing");
225 return { ok: false, error: "Dialogue missing." };
226 }
227 const step = tree.steps.find((s) => s.stepId === session.stepId);
228 if (!step || step.exit?.kind !== "triggers")
229 { return { ok: false, error: "Cannot choose now." }; }
230 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
231 if (!trigger)
232 { return { ok: false, error: "Unknown choice." }; }
233 const playerView = this.playerViewFor(characterId);
234 const ctx = this.buildConditionContext(characterId, playerView);
235 if (!evaluateConditionSet(trigger.when, ctx))
236 { return { ok: false, error: "That choice is unavailable." }; }
237 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
238 const events = [];
239 this.#applyEffects(characterId, trigger.effects, playerView, events);
240 this.#reevaluateQuests(characterId, playerView, events);
241 if (!trigger.nextStepId)
242 {
243 const npcEntityId = session.entityId;
244 this.sessions.delete(characterId | 0);
245 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
246 return { ok: true, events };
247 }
248 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
249 }
250
251 closeDialogue (characterId, reason = "close")
252 {
253 const id = characterId | 0;
254 const session = this.sessions.get(id);
255 if (!session)
256 { return { events: [] }; }
257 this.sessions.delete(id);
258 return {
259 events: [{
260 type: "dialogueClose",
261 reason,
262 npcEntityId: session.entityId
263 }]
264 };
265 }
266
267 interruptDialogueForEntity (entityId)
268 {
269 const events = [];
270 for (const [characterId, session] of [...this.sessions])
271 {
272 if (session.entityId === (entityId | 0))
273 {
274 const closed = this.closeDialogue(characterId, "attacked");
275 events.push(...closed.events.map((e) => ({ ...e, characterId })));
276 }
277 }
278 return events;
279 }
280
281 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
282 {
283 const step = tree.steps.find((s) => s.stepId === stepId);
284 if (!step)
285 {
286 this.sessions.delete(characterId | 0);
287 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
288 return { ok: false, error: "Broken dialogue.", events: priorEvents };
289 }
290 const events = [...priorEvents];
291 const identity = this.#playerDialogueIdentity(characterId);
292 const linePayloads = [];
293 for (const line of step.lines)
294 {
295 this.#applyEffects(characterId, line.effects, playerView, events);
296 linePayloads.push({
297 speaker: line.speaker,
298 text: applyDialogueTextReplacements(line.text, identity)
299 });
300 }
301 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
302 // dialogueHeard is marked only when the step fully completes (after rewards).
303 this.sessions.set(characterId | 0, {
304 entityId: entityId | 0,
305 dialogueId: tree.dialogueId,
306 stepId: step.stepId,
307 phase: "lines",
308 pendingExit: step.exit ?? { kind: "end" }
309 });
310 events.push({
311 type: "dialogueStep",
312 dialogueId: tree.dialogueId,
313 stepId: step.stepId,
314 label: step.label,
315 npcEntityId: entityId | 0,
316 lines: linePayloads
317 });
318 this.#reevaluateQuests(characterId, playerView, events);
319 return { ok: true, events };
320 }
321
322 /** Client finished reading all lines (or reward notices) of the current step. */
323 advanceDialogue (characterId)
324 {
325 const session = this.sessions.get(characterId | 0);
326 if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
327 { return { ok: false, error: "No dialogue lines to advance." }; }
328 const tree = this.content.dialogue(session.dialogueId);
329 if (!tree)
330 {
331 this.sessions.delete(characterId | 0);
332 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
333 }
334 const playerView = this.playerViewFor(characterId);
335 const events = [];
336
337 if (session.phase === "lines")
338 {
339 const step = tree.steps.find((s) => s.stepId === session.stepId);
340 const rewardMessages = [
341 ...this.#takeStepItems(characterId, step, events),
342 ...this.#grantStepItemRewards(characterId, step, events),
343 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
344 ];
345 this.#reevaluateQuests(characterId, playerView, events);
346 if (rewardMessages.length > 0)
347 {
348 session.phase = "rewards";
349 events.push({
350 type: "dialogueItemRewards",
351 dialogueId: session.dialogueId,
352 stepId: session.stepId,
353 npcEntityId: session.entityId,
354 messages: rewardMessages
355 });
356 return { ok: true, events };
357 }
358 }
359
360 return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
361 }
362
363 #resolveDialogueExit (characterId, session, tree, playerView, events)
364 {
365 // Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
366 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
367 this.#reevaluateQuests(characterId, playerView, events);
368
369 const exit = session.pendingExit ?? { kind: "end" };
370
371 if (exit.kind === "branches")
372 {
373 const ctx = this.buildConditionContext(characterId, playerView);
374 let matched = null;
375 for (const branch of exit.branches ?? [])
376 {
377 if (evaluateConditionSet(branch.when, ctx))
378 {
379 matched = branch;
380 break;
381 }
382 }
383 if (!matched || !matched.nextStepId)
384 {
385 this.#applyEffects(characterId, matched?.effects, playerView, events);
386 const npcEntityId = session.entityId;
387 this.sessions.delete(characterId | 0);
388 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
389 return { ok: true, events };
390 }
391 this.#applyEffects(characterId, matched.effects, playerView, events);
392 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
393 }
394
395 if (exit.kind === "triggers")
396 {
397 const ctx = this.buildConditionContext(characterId, playerView);
398 const identity = this.#playerDialogueIdentity(characterId);
399 const triggers = (exit.triggers ?? [])
400 .filter((t) => evaluateConditionSet(t.when, ctx))
401 .map((t) => ({
402 trigger: t.trigger,
403 text: applyDialogueTextReplacements(t.text, identity)
404 }));
405 if (triggers.length === 0)
406 {
407 const npcEntityId = session.entityId;
408 this.sessions.delete(characterId | 0);
409 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
410 return { ok: true, events };
411 }
412 session.phase = "choices";
413 session.pendingExit = null;
414 events.push({
415 type: "dialogueChoices",
416 dialogueId: session.dialogueId,
417 stepId: session.stepId,
418 npcEntityId: session.entityId,
419 triggers
420 });
421 return { ok: true, events };
422 }
423
424 if (exit.kind === "continue")
425 {
426 if (!exit.nextStepId)
427 {
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
435
436 const npcEntityId = session.entityId;
437 this.sessions.delete(characterId | 0);
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439 return { ok: true, events };
440 }
441
442 /**
443 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444 */
445 #takeStepItems (characterId, step, events)
446 {
447 const takes = step?.itemTakes ?? [];
448 if (!takes.length)
449 { return []; }
450 const parts = [];
451 for (const take of takes)
452 {
453 const bag = this.#loadBag(characterId);
454 if (!bag)
455 { continue; }
456 const itemId = take.itemId | 0;
457 const want = Math.max(1, Number(take.quantity) || 1);
458 const def = itemDefinition(itemId);
459 const displayName = def?.displayName ?? `Item ${itemId}`;
460 const result = takeMatchingUpToFromSlots(bag.inventory, {
461 itemId,
462 quantity: want,
463 compact: false
464 });
465 if (!result.ok || result.takenQuantity <= 0)
466 { continue; }
467 bag.inventory = result.slots;
468 this.#persistBag(characterId, bag);
469 events.push({ type: "inventoryDirty" });
470 parts.push({ displayName, quantity: result.takenQuantity });
471 }
472 const message = formatDialogueTakeMessage(parts);
473 return message ? [message] : [];
474 }
475
476 /**
477 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478 */
479 #grantStepItemRewards (characterId, step, events)
480 {
481 const rewards = step?.itemRewards ?? [];
482 if (!rewards.length)
483 { return []; }
484 const bagParts = [];
485 const bankParts = [];
486 for (const reward of rewards)
487 {
488 const bag = this.#loadBag(characterId);
489 if (!bag)
490 { continue; }
491 const itemId = reward.itemId | 0;
492 const def = itemDefinition(itemId);
493 const quantity = Math.max(1, Number(reward.quantity) || 1);
494 const displayName = def?.displayName ?? `Item ${itemId}`;
495 const stack = attachOrigins({
496 itemId,
497 quantity,
498 origins: [{ origin: godsOrigin(), quantity }]
499 });
500 const result = insertStack(bag.inventory, stack, def);
501 bag.inventory = result.slots;
502 const intoBag = quantity - Math.max(0, result.remainder | 0);
503 let intoBank = 0;
504 if (result.remainder > 0)
505 {
506 const vaultResult = insertStackGrowable(
507 bag.vault,
508 attachOrigins({
509 itemId,
510 quantity: result.remainder,
511 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512 }),
513 def
514 );
515 bag.vault = vaultResult.slots;
516 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517 }
518 this.#persistBag(characterId, bag);
519 events.push({ type: "inventoryDirty" });
520 if (intoBag > 0)
521 { bagParts.push({ displayName, quantity: intoBag }); }
522 if (intoBank > 0)
523 { bankParts.push({ displayName, quantity: intoBank }); }
524 }
525 const messages = [];
526 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528 if (bagMsg)
529 { messages.push(bagMsg); }
530 if (bankMsg)
531 { messages.push(bankMsg); }
532 return messages;
533 }
534
535 /** Start step.questRewards; returns player-facing notices for newly started quests. */
536 #grantStepQuestRewards (characterId, step, playerView, events)
537 {
538 const rewards = step?.questRewards ?? [];
539 if (!rewards.length)
540 { return []; }
541 const titles = [];
542 for (const questId of rewards)
543 {
544 const current = this.stateDb.getQuestState(characterId, questId);
545 if (current.state !== "not-started")
546 { continue; }
547 const def = this.content.quest(questId);
548 if (!def)
549 { continue; }
550 this.startQuest(characterId, questId, playerView, events);
551 titles.push(def.title || def.questId);
552 }
553 const message = formatDialogueQuestRewardMessage(titles);
554 return message ? [message] : [];
555 }
556
557 #loadBag (characterId)
558 {
559 const onlineId = this.simulation.characterEntities.get(characterId | 0);
560 const bag = onlineId
561 ? this.simulation.bagOf(onlineId)
562 : this.stateDb.getBag(characterId);
563 return bag;
564 }
565
566 #playerDialogueIdentity (characterId)
567 {
568 const row = this.stateDb.getCharacter(characterId | 0);
569 return {
570 firstName: String(row?.first_name ?? "").trim(),
571 lastName: String(row?.last_name ?? "").trim(),
572 sex: row?.sex === "female" ? "female" : "male"
573 };
574 }
575
576 #persistBag (characterId, bag)
577 {
578 this.stateDb.saveBag(characterId, bag);
579 const onlineId = this.simulation.characterEntities.get(characterId | 0);
580 if (onlineId)
581 {
582 this.simulation.applyBag?.(onlineId, bag);
583 this.simulation.pushInventory?.(characterId, bag);
584 }
585 }
586
587 #applyEffects (characterId, effects, playerView, events)
588 {
589 if (!Array.isArray(effects) || effects.length === 0)
590 { return; }
591 for (const effect of effects)
592 {
593 if (effect.kind === EffectKind.giveItem)
594 {
595 const bag = this.#loadBag(characterId);
596 if (!bag)
597 { continue; }
598 const def = itemDefinition(effect.itemId | 0);
599 const quantity = Math.max(1, Number(effect.quantity) || 1);
600 const stack = attachOrigins({
601 itemId: effect.itemId | 0,
602 quantity,
603 origins: [{ origin: godsOrigin(), quantity }]
604 });
605 if (effect.toBank)
606 {
607 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608 bag.vault = vaultResult.slots;
609 }
610 else
611 {
612 const result = insertStack(bag.inventory, stack, def);
613 bag.inventory = result.slots;
614 if (result.remainder > 0)
615 {
616 const vaultResult = insertStackGrowable(
617 bag.vault ?? [],
618 attachOrigins({
619 itemId: effect.itemId | 0,
620 quantity: result.remainder,
621 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622 }),
623 def
624 );
625 bag.vault = vaultResult.slots;
626 }
627 }
628 this.#persistBag(characterId, bag);
629 events.push({ type: "inventoryDirty" });
630 }
631 else if (effect.kind === EffectKind.takeItem)
632 {
633 const bag = this.#loadBag(characterId);
634 if (!bag)
635 { continue; }
636 const taken = takeMatchingFromSlots(bag.inventory, {
637 itemId: effect.itemId | 0,
638 quantity: Math.max(1, Number(effect.quantity) || 1),
639 compact: false
640 });
641 if (taken.ok)
642 {
643 bag.inventory = taken.slots;
644 this.#persistBag(characterId, bag);
645 events.push({ type: "inventoryDirty" });
646 }
647 }
648 else if (effect.kind === EffectKind.giveXp)
649 {
650 const skills = this.stateDb.getSkills(characterId);
651 if (skills)
652 {
653 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654 this.stateDb.saveSkills(characterId, skills);
655 if (playerView)
656 { playerView.skills = skills; }
657 events.push({ type: "skillsDirty" });
658 }
659 }
660 else if (effect.kind === EffectKind.startQuest)
661 { this.startQuest(characterId, effect.questId, playerView, events); }
662 }
663 }
664
665 startQuest (characterId, questId, playerView, events = [])
666 {
667 const def = this.content.quest(questId);
668 if (!def)
669 { return; }
670 const current = this.stateDb.getQuestState(characterId, questId);
671 if (current.state !== "not-started")
672 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
674 completedObjectiveIds: [],
675 counters: {},
676 interacts: {}
677 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679 events.push({ type: "questsDirty" });
680 this.#reevaluateQuests(characterId, playerView, events);
681 }
682
683 /**
684 * Grant world-settings initial quests when the character has not started or completed them.
685 */
686 ensureInitialQuests (characterId, playerView = null, events = [])
687 {
688 const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689 for (const questId of list)
690 { this.startQuest(characterId, questId, playerView, events); }
691 return events;
692 }
693
694 /**
695 * Re-check active quest objectives against live bag/position/etc.
696 * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697 */
698 reevaluateQuests (characterId, playerView = null, events = [])
699 {
700 const view = playerView ?? this.playerViewFor(characterId);
701 this.#reevaluateQuests(characterId, view, events);
702 return events;
703 }
704
705 /** Apply initial quests to every character in state (settings save / apply). */
706 grantInitialQuestsToAllCharacters ()
707 {
708 const events = [];
709 for (const characterId of this.stateDb.listAllCharacterIds())
710 { this.ensureInitialQuests(characterId, null, events); }
711 return events;
712 }
713
714 /**
715 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717 */
718 #grantQuestCompletionRewards (characterId, def, playerView, events)
719 {
720 const xp = [];
721 const bagItems = [];
722 const bankItems = [];
723 const rewards = def?.rewards ?? [];
724 for (const effect of rewards)
725 {
726 if (effect.kind === EffectKind.giveXp)
727 {
728 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729 if (amount <= 0)
730 { continue; }
731 const skillId = String(effect.skillId ?? "").trim();
732 if (!skillId)
733 { continue; }
734 const onlineId = this.simulation.characterEntities.get(characterId | 0);
735 let skills = onlineId
736 ? this.simulation.skillsOf(onlineId)
737 : this.stateDb.getSkills(characterId);
738 if (!skills)
739 { skills = this.stateDb.getSkills(characterId); }
740 if (!skills)
741 { continue; }
742 applySkillXp(skills, skillId, amount);
743 this.stateDb.saveSkills(characterId, skills);
744 if (playerView)
745 { playerView.skills = skills; }
746 if (onlineId)
747 { this.simulation.applySkills?.(onlineId, skills); }
748 const payload = publicSkillsPayload(skills);
749 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750 xp.push({
751 skillId,
752 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753 amount
754 });
755 continue;
756 }
757 if (effect.kind !== EffectKind.giveItem)
758 { continue; }
759 const bag = this.#loadBag(characterId);
760 if (!bag)
761 { continue; }
762 const itemId = effect.itemId | 0;
763 const defItem = itemDefinition(itemId);
764 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765 const displayName = defItem
766 ? itemDisplayName({ itemId, quantity }, defItem)
767 : `Item ${itemId}`;
768 const stack = attachOrigins({
769 itemId,
770 quantity,
771 origins: [{ origin: godsOrigin(), quantity }]
772 });
773 let intoBag = 0;
774 let intoBank = 0;
775 if (effect.toBank)
776 {
777 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778 bag.vault = vaultResult.slots;
779 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780 }
781 else
782 {
783 const result = insertStack(bag.inventory, stack, defItem);
784 bag.inventory = result.slots;
785 intoBag = quantity - Math.max(0, result.remainder | 0);
786 if (result.remainder > 0)
787 {
788 const vaultResult = insertStackGrowable(
789 bag.vault ?? [],
790 attachOrigins({
791 itemId,
792 quantity: result.remainder,
793 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794 }),
795 defItem
796 );
797 bag.vault = vaultResult.slots;
798 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799 }
800 }
801 this.#persistBag(characterId, bag);
802 events.push({ type: "inventoryDirty" });
803 if (intoBag > 0)
804 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
805 if (intoBank > 0)
806 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
807 }
808
809 if (bankItems.length)
810 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
812 return { xp, bagItems };
813 }
814
815 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
816 {
817 const courier = this.simulation.courier;
818 if (!courier?.enqueueSystemLetter)
819 { return; }
820 const row = this.stateDb.getCharacter?.(characterId);
821 const characterDisplayName = row
822 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823 : "Adventurer";
824 const originTileX = row?.tile_x | 0;
825 const originTileY = row?.tile_y | 0;
826 const bank = courier.nearestBank?.(originTileX, originTileY);
827 courier.enqueueSystemLetter({
828 characterId: characterId | 0,
829 originTileX: bank?.tileX ?? originTileX,
830 originTileY: bank?.tileY ?? originTileY,
831 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
832 authorOrganization: QUESTWARD_GIFT_ORG,
833 body: formatQuestBankRewardLetterBody({
834 characterDisplayName,
835 questTitle: def?.title ?? def?.questId,
836 items: bankItems
837 })
838 });
839 }
840
841 #reevaluateQuests (characterId, playerView, events)
842 {
843 const states = this.stateDb.listQuestStates(characterId)
844 .filter((row) => typeof row.state === "number");
845 for (const row of states)
846 {
847 const def = this.content.quest(row.questId);
848 if (!def)
849 { continue; }
850 const stepDef = def.steps[row.state - 1];
851 if (!stepDef)
852 { continue; }
853 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
854 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
855 const newlyDone = [];
856 let changed = false;
857 for (const obj of stepDef.objectives)
858 {
859 if (completed.has(obj.objectiveId))
860 { continue; }
861 if (evaluateConditionSet(obj.when, ctx))
862 {
863 completed.add(obj.objectiveId);
864 newlyDone.push(obj);
865 changed = true;
866 }
867 }
868 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
869 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
870 if (!changed && !progressChanged)
871 { continue; }
872 for (const obj of newlyDone)
873 {
874 events.push({
875 type: "questObjectiveComplete",
876 questId: row.questId,
877 objectiveId: obj.objectiveId,
878 text: obj.text || "Objective"
879 });
880 }
881 const progress = {
882 ...row.progress,
883 completedObjectiveIds: [...completed],
884 progressFingerprint: fingerprint
885 };
886 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
887 if (!allDone)
888 {
889 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
890 events.push({ type: "questsDirty" });
891 continue;
892 }
893 if (!changed)
894 {
895 // Progress-only update while already fully complete (should not happen).
896 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
897 events.push({ type: "questsDirty" });
898 continue;
899 }
900 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
901 const journal = this.stateDb.appendQuestJournal(
902 characterId,
903 row.questId,
904 stepDef.stepId,
905 stepDef.completionJournalText
906 );
907 const nextIndex = row.state + 1;
908 if (nextIndex > def.steps.length)
909 {
910 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
911 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
912 events.push({
913 type: "questComplete",
914 questId: row.questId,
915 title: def.title,
916 xp: summary.xp,
917 items: summary.bagItems
918 });
919 }
920 else
921 {
922 const nextStep = def.steps[nextIndex - 1];
923 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
924 completedObjectiveIds: [],
925 counters: {},
926 interacts: {},
927 progressFingerprint: ""
928 }, row.startedAt, null);
929 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
930 events.push({
931 type: "questStepComplete",
932 questId: row.questId,
933 title: def.title,
934 journalText: journal?.text ?? null
935 });
936 }
937 events.push({ type: "questsDirty" });
938 }
939 }
940
941 noteKill (characterId, { mobTypeId, spawnerId })
942 {
943 const events = [];
944 const playerView = this.playerViewFor(characterId);
945 const states = this.stateDb.listQuestStates(characterId)
946 .filter((row) => typeof row.state === "number");
947 for (const row of states)
948 {
949 const def = this.content.quest(row.questId);
950 const stepDef = def?.steps[row.state - 1];
951 if (!stepDef)
952 { continue; }
953 let changed = false;
954 const counters = { ...(row.progress?.counters ?? {}) };
955 for (const obj of stepDef.objectives)
956 {
957 for (const clause of obj.when?.all ?? [])
958 {
959 const c = clause.condition;
960 if (c?.kind !== "killCount")
961 { continue; }
962 const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
963 const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
964 if (!matchMob && !matchSpawner)
965 { continue; }
966 const key = killKey(c);
967 counters[key] = (counters[key] | 0) + 1;
968 changed = true;
969 }
970 }
971 if (!changed)
972 { continue; }
973 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
974 ...row.progress,
975 counters
976 }, row.startedAt, row.completedAt);
977 }
978 this.#reevaluateQuests(characterId, playerView, events);
979 return events;
980 }
981 }
982
983 function journalPublic (row)
984 {
985 return {
986 entryId: row.entry_id ?? row.entryId,
987 questId: row.quest_id ?? row.questId,
988 stepId: row.step_id ?? row.stepId,
989 text: row.text,
990 writtenAt: row.written_at ?? row.writtenAt
991 };
992 }
993
994 function killKey (condition)
995 {
996 if (condition.spawnerId)
997 { return `spawner:${condition.spawnerId}`; }
998 return `mob:${condition.mobTypeId}`;
999 }
1000
1001 function interactKey (condition)
1002 {
1003 if (condition.tileX != null)
1004 { return `tile:${condition.tileX},${condition.tileY}`; }
1005 return `block:${condition.blockTypeId}`;
1006 }
1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3 import {
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
6 } from "../../../shared/quests/objectiveProgress.js";
7 import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8 import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9 import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10 import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11 import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12 import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
13 import {
14 formatDialogueRewardMessage,
15 formatDialogueQuestRewardMessage,
16 formatDialogueTakeMessage
17 } from "../../../shared/quests/dialogueRewards.js";
18 import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
19 import {
20 formatQuestBankRewardLetterBody,
21 QUESTWARD_GIFT_AUTHOR,
22 QUESTWARD_GIFT_ORG
23 } from "../../../shared/courier/questRewardLetters.js";
24 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25 import { floorDiv } from "../world/coordinates.js";
26 import { WorkerMessage } from "../simulation/protocol.js";
27
28 /**
29 * Quest progress + dialogue sessions (main simulation thread).
30 */
31 export class QuestRuntime
32 {
33 constructor ({ stateDb, content, simulation })
34 {
35 this.stateDb = stateDb;
36 this.content = content;
37 this.simulation = simulation;
38 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
39 this.sessions = new Map();
40 }
41
42 reloadContent ()
43 {
44 this.content.reload();
45 }
46
47 closeAllSessions ()
48 {
49 for (const characterId of [...this.sessions.keys()])
50 { this.closeDialogue(characterId, "revision"); }
51 }
52
53 questSnapshot (characterId)
54 {
55 const states = this.stateDb.listQuestStates(characterId)
56 .filter((row) => row.state !== "not-started");
57 const quests = [];
58 const playerView = this.playerViewFor(characterId);
59 for (const row of states)
60 {
61 const def = this.content.quest(row.questId);
62 if (!def)
63 {
64 quests.push({
65 questId: row.questId,
66 title: "Quest unavailable",
67 orphaned: true,
68 state: row.state,
69 description: "",
70 step: null,
71 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
72 });
73 continue;
74 }
75 const stepIndex = typeof row.state === "number" ? row.state : null;
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
77 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78 const ctx = stepDef
79 ? this.buildConditionContext(characterId, playerView, row.questId)
80 : null;
81 quests.push({
82 questId: def.questId,
83 title: def.title,
84 orphaned: false,
85 state: row.state,
86 description: def.description,
87 step: stepDef
88 ? {
89 stepId: stepDef.stepId,
90 title: stepDef.title,
91 description: stepDef.description,
92 objectives: stepDef.objectives.map((obj) =>
93 {
94 const done = completedObjectiveIds.includes(obj.objectiveId);
95 const progress = countableObjectiveProgress(obj.when, ctx);
96 return {
97 objectiveId: obj.objectiveId,
98 text: obj.text,
99 done,
100 current: progress?.current ?? null,
101 required: progress?.required ?? null
102 };
103 })
104 }
105 : null,
106 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
107 });
108 }
109 quests.sort((a, b) =>
110 {
111 const aDone = a.state === "completed" ? 1 : 0;
112 const bDone = b.state === "completed" ? 1 : 0;
113 if (aDone !== bDone)
114 { return aDone - bDone; }
115 return String(a.title).localeCompare(String(b.title));
116 });
117 return { quests };
118 }
119
120 playerViewFor (characterId)
121 {
122 const entityId = this.simulation.characterEntities.get(characterId | 0);
123 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
124 const skills = this.stateDb.getSkills(characterId) ?? {};
125 let hp = 1;
126 let maxHp = 1;
127 let stamina = 1;
128 let maxStamina = 1;
129 if (entityId != null && record)
130 {
131 const staminaComp = this.simulation.staminaOf(entityId);
132 if (staminaComp)
133 {
134 stamina = Number(staminaComp.current) || 0;
135 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
136 }
137 const worker = this.simulation.workers[record.workerId];
138 const view = worker?.call?.({
139 type: WorkerMessage.inspect,
140 entityId
141 });
142 if (view && view.health != null)
143 {
144 hp = Number(view.health) || 0;
145 maxHp = Math.max(1, Number(view.maxHealth) || 1);
146 }
147 }
148 return {
149 tileX: record?.tileX | 0,
150 tileY: record?.tileY | 0,
151 dimensionId: record?.dimensionId ?? "overworld",
152 skills,
153 hp,
154 maxHp,
155 stamina,
156 maxStamina
157 };
158 }
159
160 buildConditionContext (characterId, playerView, activeQuestId = null)
161 {
162 const bag = this.#loadBag(characterId);
163 const inventory = bag?.inventory ?? [];
164 const tileX = playerView?.tileX | 0;
165 const tileY = playerView?.tileY | 0;
166 const dimensionId = playerView?.dimensionId ?? "overworld";
167 const chunkX = floorDiv(tileX, CHUNK_SIZE);
168 const chunkY = floorDiv(tileY, CHUNK_SIZE);
169 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
170 return {
171 tileX,
172 tileY,
173 chunkX,
174 chunkY,
175 dimensionId,
176 hp: playerView?.hp ?? 0,
177 maxHp: playerView?.maxHp ?? 1,
178 stamina: playerView?.stamina ?? 0,
179 maxStamina: playerView?.maxStamina ?? 1,
180 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
182 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183 dialogueTriggerLatched: (dialogueId, trigger) =>
184 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
185 skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
186 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
187 killCount: (condition) =>
188 {
189 if (!questRow)
190 { return 0; }
191 return questRow.progress?.counters?.[killKey(condition)] | 0;
192 },
193 interactBlockDone: (condition) =>
194 {
195 if (!questRow)
196 { return false; }
197 return !!questRow.progress?.interacts?.[interactKey(condition)];
198 }
199 };
200 }
201
202 tryOpenDialogue (characterId, entityId, dialogueId)
203 {
204 const tree = this.content.dialogue(dialogueId);
205 if (!tree)
206 { return { ok: false, error: "Nothing to say." }; }
207 this.closeDialogue(characterId, "replace");
208 const playerView = this.playerViewFor(characterId);
209 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
210 }
211
212 chooseDialogue (characterId, triggerId)
213 {
214 const session = this.sessions.get(characterId | 0);
215 if (!session)
216 { return { ok: false, error: "No dialogue open." }; }
217 if (session.phase === "lines")
218 { return { ok: false, error: "Finish reading first." }; }
219 if (session.phase === "rewards")
220 { return { ok: false, error: "Finish reading first." }; }
221 const tree = this.content.dialogue(session.dialogueId);
222 if (!tree)
223 {
224 this.closeDialogue(characterId, "missing");
225 return { ok: false, error: "Dialogue missing." };
226 }
227 const step = tree.steps.find((s) => s.stepId === session.stepId);
228 if (!step || step.exit?.kind !== "triggers")
229 { return { ok: false, error: "Cannot choose now." }; }
230 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
231 if (!trigger)
232 { return { ok: false, error: "Unknown choice." }; }
233 const playerView = this.playerViewFor(characterId);
234 const ctx = this.buildConditionContext(characterId, playerView);
235 if (!evaluateConditionSet(trigger.when, ctx))
236 { return { ok: false, error: "That choice is unavailable." }; }
237 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
238 const events = [];
239 this.#applyEffects(characterId, trigger.effects, playerView, events);
240 this.#reevaluateQuests(characterId, playerView, events);
241 if (!trigger.nextStepId)
242 {
243 const npcEntityId = session.entityId;
244 this.sessions.delete(characterId | 0);
245 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
246 return { ok: true, events };
247 }
248 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
249 }
250
251 closeDialogue (characterId, reason = "close")
252 {
253 const id = characterId | 0;
254 const session = this.sessions.get(id);
255 if (!session)
256 { return { events: [] }; }
257 this.sessions.delete(id);
258 return {
259 events: [{
260 type: "dialogueClose",
261 reason,
262 npcEntityId: session.entityId
263 }]
264 };
265 }
266
267 interruptDialogueForEntity (entityId)
268 {
269 const events = [];
270 for (const [characterId, session] of [...this.sessions])
271 {
272 if (session.entityId === (entityId | 0))
273 {
274 const closed = this.closeDialogue(characterId, "attacked");
275 events.push(...closed.events.map((e) => ({ ...e, characterId })));
276 }
277 }
278 return events;
279 }
280
281 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
282 {
283 const step = tree.steps.find((s) => s.stepId === stepId);
284 if (!step)
285 {
286 this.sessions.delete(characterId | 0);
287 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
288 return { ok: false, error: "Broken dialogue.", events: priorEvents };
289 }
290 const events = [...priorEvents];
291 const identity = this.#playerDialogueIdentity(characterId);
292 const linePayloads = [];
293 for (const line of step.lines)
294 {
295 this.#applyEffects(characterId, line.effects, playerView, events);
296 linePayloads.push({
297 speaker: line.speaker,
298 text: applyDialogueTextReplacements(line.text, identity)
299 });
300 }
301 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
302 // dialogueHeard is marked only when the step fully completes (after rewards).
303 this.sessions.set(characterId | 0, {
304 entityId: entityId | 0,
305 dialogueId: tree.dialogueId,
306 stepId: step.stepId,
307 phase: "lines",
308 pendingExit: step.exit ?? { kind: "end" }
309 });
310 events.push({
311 type: "dialogueStep",
312 dialogueId: tree.dialogueId,
313 stepId: step.stepId,
314 label: step.label,
315 npcEntityId: entityId | 0,
316 lines: linePayloads
317 });
318 this.#reevaluateQuests(characterId, playerView, events);
319 return { ok: true, events };
320 }
321
322 /** Client finished reading all lines (or reward notices) of the current step. */
323 advanceDialogue (characterId)
324 {
325 const session = this.sessions.get(characterId | 0);
326 if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
327 { return { ok: false, error: "No dialogue lines to advance." }; }
328 const tree = this.content.dialogue(session.dialogueId);
329 if (!tree)
330 {
331 this.sessions.delete(characterId | 0);
332 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
333 }
334 const playerView = this.playerViewFor(characterId);
335 const events = [];
336
337 if (session.phase === "lines")
338 {
339 const step = tree.steps.find((s) => s.stepId === session.stepId);
340 const rewardMessages = [
341 ...this.#takeStepItems(characterId, step, events),
342 ...this.#grantStepItemRewards(characterId, step, events),
343 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
344 ];
345 this.#reevaluateQuests(characterId, playerView, events);
346 if (rewardMessages.length > 0)
347 {
348 session.phase = "rewards";
349 events.push({
350 type: "dialogueItemRewards",
351 dialogueId: session.dialogueId,
352 stepId: session.stepId,
353 npcEntityId: session.entityId,
354 messages: rewardMessages
355 });
356 return { ok: true, events };
357 }
358 }
359
360 return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
361 }
362
363 #resolveDialogueExit (characterId, session, tree, playerView, events)
364 {
365 // Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
366 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
367 this.#reevaluateQuests(characterId, playerView, events);
368
369 const exit = session.pendingExit ?? { kind: "end" };
370
371 if (exit.kind === "branches")
372 {
373 const ctx = this.buildConditionContext(characterId, playerView);
374 let matched = null;
375 for (const branch of exit.branches ?? [])
376 {
377 if (evaluateConditionSet(branch.when, ctx))
378 {
379 matched = branch;
380 break;
381 }
382 }
383 if (!matched || !matched.nextStepId)
384 {
385 this.#applyEffects(characterId, matched?.effects, playerView, events);
386 const npcEntityId = session.entityId;
387 this.sessions.delete(characterId | 0);
388 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
389 return { ok: true, events };
390 }
391 this.#applyEffects(characterId, matched.effects, playerView, events);
392 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
393 }
394
395 if (exit.kind === "triggers")
396 {
397 const ctx = this.buildConditionContext(characterId, playerView);
398 const identity = this.#playerDialogueIdentity(characterId);
399 const triggers = (exit.triggers ?? [])
400 .filter((t) => evaluateConditionSet(t.when, ctx))
401 .map((t) => ({
402 trigger: t.trigger,
403 text: applyDialogueTextReplacements(t.text, identity)
404 }));
405 if (triggers.length === 0)
406 {
407 const npcEntityId = session.entityId;
408 this.sessions.delete(characterId | 0);
409 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
410 return { ok: true, events };
411 }
412 session.phase = "choices";
413 session.pendingExit = null;
414 events.push({
415 type: "dialogueChoices",
416 dialogueId: session.dialogueId,
417 stepId: session.stepId,
418 npcEntityId: session.entityId,
419 triggers
420 });
421 return { ok: true, events };
422 }
423
424 if (exit.kind === "continue")
425 {
426 if (!exit.nextStepId)
427 {
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
435
436 const npcEntityId = session.entityId;
437 this.sessions.delete(characterId | 0);
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439 return { ok: true, events };
440 }
441
442 /**
443 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444 */
445 #takeStepItems (characterId, step, events)
446 {
447 const takes = step?.itemTakes ?? [];
448 if (!takes.length)
449 { return []; }
450 const parts = [];
451 for (const take of takes)
452 {
453 const bag = this.#loadBag(characterId);
454 if (!bag)
455 { continue; }
456 const itemId = take.itemId | 0;
457 const want = Math.max(1, Number(take.quantity) || 1);
458 const def = itemDefinition(itemId);
459 const displayName = def?.displayName ?? `Item ${itemId}`;
460 const result = takeMatchingUpToFromSlots(bag.inventory, {
461 itemId,
462 quantity: want,
463 compact: false
464 });
465 if (!result.ok || result.takenQuantity <= 0)
466 { continue; }
467 bag.inventory = result.slots;
468 this.#persistBag(characterId, bag);
469 events.push({ type: "inventoryDirty" });
470 parts.push({ displayName, quantity: result.takenQuantity });
471 }
472 const message = formatDialogueTakeMessage(parts);
473 return message ? [message] : [];
474 }
475
476 /**
477 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478 */
479 #grantStepItemRewards (characterId, step, events)
480 {
481 const rewards = step?.itemRewards ?? [];
482 if (!rewards.length)
483 { return []; }
484 const bagParts = [];
485 const bankParts = [];
486 for (const reward of rewards)
487 {
488 const bag = this.#loadBag(characterId);
489 if (!bag)
490 { continue; }
491 const itemId = reward.itemId | 0;
492 const def = itemDefinition(itemId);
493 const quantity = Math.max(1, Number(reward.quantity) || 1);
494 const displayName = def?.displayName ?? `Item ${itemId}`;
495 const stack = attachOrigins({
496 itemId,
497 quantity,
498 origins: [{ origin: godsOrigin(), quantity }]
499 });
500 const result = insertStack(bag.inventory, stack, def);
501 bag.inventory = result.slots;
502 const intoBag = quantity - Math.max(0, result.remainder | 0);
503 let intoBank = 0;
504 if (result.remainder > 0)
505 {
506 const vaultResult = insertStackGrowable(
507 bag.vault,
508 attachOrigins({
509 itemId,
510 quantity: result.remainder,
511 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512 }),
513 def
514 );
515 bag.vault = vaultResult.slots;
516 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517 }
518 this.#persistBag(characterId, bag);
519 events.push({ type: "inventoryDirty" });
520 if (intoBag > 0)
521 { bagParts.push({ displayName, quantity: intoBag }); }
522 if (intoBank > 0)
523 { bankParts.push({ displayName, quantity: intoBank }); }
524 }
525 const messages = [];
526 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528 if (bagMsg)
529 { messages.push(bagMsg); }
530 if (bankMsg)
531 { messages.push(bankMsg); }
532 return messages;
533 }
534
535 /** Start step.questRewards; returns player-facing notices for newly started quests. */
536 #grantStepQuestRewards (characterId, step, playerView, events)
537 {
538 const rewards = step?.questRewards ?? [];
539 if (!rewards.length)
540 { return []; }
541 const titles = [];
542 for (const questId of rewards)
543 {
544 const current = this.stateDb.getQuestState(characterId, questId);
545 if (current.state !== "not-started")
546 { continue; }
547 const def = this.content.quest(questId);
548 if (!def)
549 { continue; }
550 this.startQuest(characterId, questId, playerView, events);
551 titles.push(def.title || def.questId);
552 }
553 const message = formatDialogueQuestRewardMessage(titles);
554 return message ? [message] : [];
555 }
556
557 #loadBag (characterId)
558 {
559 const onlineId = this.simulation.characterEntities.get(characterId | 0);
560 const bag = onlineId
561 ? this.simulation.bagOf(onlineId)
562 : this.stateDb.getBag(characterId);
563 return bag;
564 }
565
566 #playerDialogueIdentity (characterId)
567 {
568 const row = this.stateDb.getCharacter(characterId | 0);
569 return {
570 firstName: String(row?.first_name ?? "").trim(),
571 lastName: String(row?.last_name ?? "").trim(),
572 sex: row?.sex === "female" ? "female" : "male"
573 };
574 }
575
576 #persistBag (characterId, bag)
577 {
578 this.stateDb.saveBag(characterId, bag);
579 const onlineId = this.simulation.characterEntities.get(characterId | 0);
580 if (onlineId)
581 {
582 this.simulation.applyBag?.(onlineId, bag);
583 this.simulation.pushInventory?.(characterId, bag);
584 }
585 }
586
587 #applyEffects (characterId, effects, playerView, events)
588 {
589 if (!Array.isArray(effects) || effects.length === 0)
590 { return; }
591 for (const effect of effects)
592 {
593 if (effect.kind === EffectKind.giveItem)
594 {
595 const bag = this.#loadBag(characterId);
596 if (!bag)
597 { continue; }
598 const def = itemDefinition(effect.itemId | 0);
599 const quantity = Math.max(1, Number(effect.quantity) || 1);
600 const stack = attachOrigins({
601 itemId: effect.itemId | 0,
602 quantity,
603 origins: [{ origin: godsOrigin(), quantity }]
604 });
605 if (effect.toBank)
606 {
607 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608 bag.vault = vaultResult.slots;
609 }
610 else
611 {
612 const result = insertStack(bag.inventory, stack, def);
613 bag.inventory = result.slots;
614 if (result.remainder > 0)
615 {
616 const vaultResult = insertStackGrowable(
617 bag.vault ?? [],
618 attachOrigins({
619 itemId: effect.itemId | 0,
620 quantity: result.remainder,
621 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622 }),
623 def
624 );
625 bag.vault = vaultResult.slots;
626 }
627 }
628 this.#persistBag(characterId, bag);
629 events.push({ type: "inventoryDirty" });
630 }
631 else if (effect.kind === EffectKind.takeItem)
632 {
633 const bag = this.#loadBag(characterId);
634 if (!bag)
635 { continue; }
636 const taken = takeMatchingFromSlots(bag.inventory, {
637 itemId: effect.itemId | 0,
638 quantity: Math.max(1, Number(effect.quantity) || 1),
639 compact: false
640 });
641 if (taken.ok)
642 {
643 bag.inventory = taken.slots;
644 this.#persistBag(characterId, bag);
645 events.push({ type: "inventoryDirty" });
646 }
647 }
648 else if (effect.kind === EffectKind.giveXp)
649 {
650 const skills = this.stateDb.getSkills(characterId);
651 if (skills)
652 {
653 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654 this.stateDb.saveSkills(characterId, skills);
655 if (playerView)
656 { playerView.skills = skills; }
657 events.push({ type: "skillsDirty" });
658 }
659 }
660 else if (effect.kind === EffectKind.startQuest)
661 { this.startQuest(characterId, effect.questId, playerView, events); }
662 }
663 }
664
665 startQuest (characterId, questId, playerView, events = [])
666 {
667 const def = this.content.quest(questId);
668 if (!def)
669 { return; }
670 const current = this.stateDb.getQuestState(characterId, questId);
671 if (current.state !== "not-started")
672 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
674 completedObjectiveIds: [],
675 counters: {},
676 interacts: {}
677 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679 events.push({ type: "questsDirty", characterId });
680 this.#reevaluateQuests(characterId, playerView, events);
681 }
682
683 /**
684 * Grant world-settings initial quests when the character has not started or completed them.
685 */
686 ensureInitialQuests (characterId, playerView = null, events = [])
687 {
688 const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689 for (const questId of list)
690 { this.startQuest(characterId, questId, playerView, events); }
691 return events;
692 }
693
694 /**
695 * Re-check active quest objectives against live bag/position/etc.
696 * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697 */
698 reevaluateQuests (characterId, playerView = null, events = [])
699 {
700 const view = playerView ?? this.playerViewFor(characterId);
701 this.#reevaluateQuests(characterId, view, events);
702 return events;
703 }
704
705 /** Apply initial quests to every character in state (settings save / apply). */
706 grantInitialQuestsToAllCharacters ()
707 {
708 const events = [];
709 for (const characterId of this.stateDb.listAllCharacterIds())
710 { this.ensureInitialQuests(characterId, null, events); }
711 return events;
712 }
713
714 /**
715 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717 */
718 #grantQuestCompletionRewards (characterId, def, playerView, events)
719 {
720 const xp = [];
721 const bagItems = [];
722 const bankItems = [];
723 const rewards = def?.rewards ?? [];
724 for (const effect of rewards)
725 {
726 if (effect.kind === EffectKind.giveXp)
727 {
728 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729 if (amount <= 0)
730 { continue; }
731 const skillId = String(effect.skillId ?? "").trim();
732 if (!skillId)
733 { continue; }
734 const onlineId = this.simulation.characterEntities.get(characterId | 0);
735 let skills = onlineId
736 ? this.simulation.skillsOf(onlineId)
737 : this.stateDb.getSkills(characterId);
738 if (!skills)
739 { skills = this.stateDb.getSkills(characterId); }
740 if (!skills)
741 { continue; }
742 applySkillXp(skills, skillId, amount);
743 this.stateDb.saveSkills(characterId, skills);
744 if (playerView)
745 { playerView.skills = skills; }
746 if (onlineId)
747 { this.simulation.applySkills?.(onlineId, skills); }
748 const payload = publicSkillsPayload(skills);
749 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750 xp.push({
751 skillId,
752 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753 amount
754 });
755 continue;
756 }
757 if (effect.kind !== EffectKind.giveItem)
758 { continue; }
759 const bag = this.#loadBag(characterId);
760 if (!bag)
761 { continue; }
762 const itemId = effect.itemId | 0;
763 const defItem = itemDefinition(itemId);
764 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765 const displayName = defItem
766 ? itemDisplayName({ itemId, quantity }, defItem)
767 : `Item ${itemId}`;
768 const stack = attachOrigins({
769 itemId,
770 quantity,
771 origins: [{ origin: godsOrigin(), quantity }]
772 });
773 let intoBag = 0;
774 let intoBank = 0;
775 if (effect.toBank)
776 {
777 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778 bag.vault = vaultResult.slots;
779 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780 }
781 else
782 {
783 const result = insertStack(bag.inventory, stack, defItem);
784 bag.inventory = result.slots;
785 intoBag = quantity - Math.max(0, result.remainder | 0);
786 if (result.remainder > 0)
787 {
788 const vaultResult = insertStackGrowable(
789 bag.vault ?? [],
790 attachOrigins({
791 itemId,
792 quantity: result.remainder,
793 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794 }),
795 defItem
796 );
797 bag.vault = vaultResult.slots;
798 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799 }
800 }
801 this.#persistBag(characterId, bag);
802 events.push({ type: "inventoryDirty" });
803 if (intoBag > 0)
804 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
805 if (intoBank > 0)
806 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
807 }
808
809 if (bankItems.length)
810 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
812 return { xp, bagItems };
813 }
814
815 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
816 {
817 const courier = this.simulation.courier;
818 if (!courier?.enqueueSystemLetter)
819 { return; }
820 const row = this.stateDb.getCharacter?.(characterId);
821 const characterDisplayName = row
822 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823 : "Adventurer";
824 const originTileX = row?.tile_x | 0;
825 const originTileY = row?.tile_y | 0;
826 const originDim = row?.dimension_id ?? undefined;
827 const bank = courier.nearestBank?.(originTileX, originTileY, originDim);
828 courier.enqueueSystemLetter({
829 characterId: characterId | 0,
830 originTileX: bank?.tileX ?? originTileX,
831 originTileY: bank?.tileY ?? originTileY,
832 originDimensionId: bank?.dimensionId ?? originDim,
833 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
834 authorOrganization: QUESTWARD_GIFT_ORG,
835 body: formatQuestBankRewardLetterBody({
836 characterDisplayName,
837 questTitle: def?.title ?? def?.questId,
838 items: bankItems
839 })
840 });
841 }
842
843 #reevaluateQuests (characterId, playerView, events)
844 {
845 const states = this.stateDb.listQuestStates(characterId)
846 .filter((row) => typeof row.state === "number");
847 for (const row of states)
848 {
849 const def = this.content.quest(row.questId);
850 if (!def)
851 { continue; }
852 const stepDef = def.steps[row.state - 1];
853 if (!stepDef)
854 { continue; }
855 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857 const newlyDone = [];
858 let changed = false;
859 for (const obj of stepDef.objectives)
860 {
861 if (completed.has(obj.objectiveId))
862 { continue; }
863 if (evaluateConditionSet(obj.when, ctx))
864 {
865 completed.add(obj.objectiveId);
866 newlyDone.push(obj);
867 changed = true;
868 }
869 }
870 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
871 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
872 if (!changed && !progressChanged)
873 { continue; }
874 for (const obj of newlyDone)
875 {
876 events.push({
877 type: "questObjectiveComplete",
878 questId: row.questId,
879 objectiveId: obj.objectiveId,
880 text: obj.text || "Objective"
881 });
882 }
883 const progress = {
884 ...row.progress,
885 completedObjectiveIds: [...completed],
886 progressFingerprint: fingerprint
887 };
888 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889 if (!allDone)
890 {
891 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
892 events.push({ type: "questsDirty", characterId });
893 continue;
894 }
895 if (!changed)
896 {
897 // Progress-only update while already fully complete (should not happen).
898 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
899 events.push({ type: "questsDirty", characterId });
900 continue;
901 }
902 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
903 const journal = this.stateDb.appendQuestJournal(
904 characterId,
905 row.questId,
906 stepDef.stepId,
907 stepDef.completionJournalText
908 );
909 const nextIndex = row.state + 1;
910 if (nextIndex > def.steps.length)
911 {
912 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
913 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
914 events.push({
915 type: "questComplete",
916 questId: row.questId,
917 title: def.title,
918 xp: summary.xp,
919 items: summary.bagItems
920 });
921 }
922 else
923 {
924 const nextStep = def.steps[nextIndex - 1];
925 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
926 completedObjectiveIds: [],
927 counters: {},
928 interacts: {},
929 progressFingerprint: ""
930 }, row.startedAt, null);
931 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932 events.push({
933 type: "questStepComplete",
934 questId: row.questId,
935 title: def.title,
936 journalText: journal?.text ?? null
937 });
938 }
939 events.push({ type: "questsDirty", characterId });
940 }
941 }
942
943 noteKill (characterId, { mobTypeId, spawnerId })
944 {
945 const events = [];
946 const playerView = this.playerViewFor(characterId);
947 const states = this.stateDb.listQuestStates(characterId)
948 .filter((row) => typeof row.state === "number");
949 for (const row of states)
950 {
951 const def = this.content.quest(row.questId);
952 const stepDef = def?.steps[row.state - 1];
953 if (!stepDef)
954 { continue; }
955 let changed = false;
956 const counters = { ...(row.progress?.counters ?? {}) };
957 for (const obj of stepDef.objectives)
958 {
959 for (const clause of obj.when?.all ?? [])
960 {
961 const c = clause.condition;
962 if (!matchesKillCondition(c, mobTypeId, spawnerId))
963 { continue; }
964 const key = killKey(c);
965 counters[key] = (counters[key] | 0) + 1;
966 changed = true;
967 }
968 }
969 if (!changed)
970 { continue; }
971 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
972 ...row.progress,
973 counters
974 }, row.startedAt, row.completedAt);
975 }
976 this.#reevaluateQuests(characterId, playerView, events);
977 return events;
978 }
979 }
980
981 function journalPublic (row)
982 {
983 return {
984 entryId: row.entry_id ?? row.entryId,
985 questId: row.quest_id ?? row.questId,
986 stepId: row.step_id ?? row.stepId,
987 text: row.text,
988 writtenAt: row.written_at ?? row.writtenAt
989 };
990 }
991
992
993 function matchesKillCondition (condition, mobTypeId, spawnerId)
994 {
995 if (!condition || typeof condition !== "object")
996 { return false; }
997 if (condition.kind === "killMobFromSpawner")
998 {
999 if (condition.mobTypeId == null || condition.spawnerId == null || spawnerId == null)
1000 { return false; }
1001 return String(condition.mobTypeId) === String(mobTypeId)
1002 && String(condition.spawnerId) === String(spawnerId);
1003 }
1004 if (condition.kind === "killCount")
1005 {
1006 // Mob-type kills: match type. Legacy JSON may also use spawnerId alone.
1007 const matchMob = condition.mobTypeId != null && String(condition.mobTypeId) === String(mobTypeId);
1008 const matchSpawner = condition.spawnerId != null && String(condition.spawnerId) === String(spawnerId);
1009 return matchMob || matchSpawner;
1010 }
1011 return false;
1012 }
1013
1014 function killKey (condition)
1015 {
1016 if (condition.spawnerId)
1017 { return `spawner:${condition.spawnerId}`; }
1018 return `mob:${condition.mobTypeId}`;
1019 }
1020
1021 function interactKey (condition)
1022 {
1023 if (condition.tileX != null)
1024 { return `tile:${condition.tileX},${condition.tileY}`; }
1025 return `block:${condition.blockTypeId}`;
1026 }
@@ -1,1006 +1,1026 @@
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
3import {
3import {
4 countableObjectiveProgress,
4 countableObjectiveProgress,
5 objectiveProgressFingerprint
5 objectiveProgressFingerprint
6} from "../../../shared/quests/objectiveProgress.js";
6} from "../../../shared/quests/objectiveProgress.js";
7import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
7import { countItemInSlots, insertStack, takeMatchingFromSlots, takeMatchingUpToFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
8import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
8import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
9import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
9import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
10import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
10import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
11import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
11import { SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
12import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
12import { resolveSkillRequirementLevel } from "../../../shared/combat/combatLevel.js";
13import {
13import {
14 formatDialogueRewardMessage,
14 formatDialogueRewardMessage,
15 formatDialogueQuestRewardMessage,
15 formatDialogueQuestRewardMessage,
16 formatDialogueTakeMessage
16 formatDialogueTakeMessage
17} from "../../../shared/quests/dialogueRewards.js";
17} from "../../../shared/quests/dialogueRewards.js";
18import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
18import { applyDialogueTextReplacements } from "../../../shared/speech/dialogueText.js";
19import {
19import {
20 formatQuestBankRewardLetterBody,
20 formatQuestBankRewardLetterBody,
21 QUESTWARD_GIFT_AUTHOR,
21 QUESTWARD_GIFT_AUTHOR,
22 QUESTWARD_GIFT_ORG
22 QUESTWARD_GIFT_ORG
23} from "../../../shared/courier/questRewardLetters.js";
23} from "../../../shared/courier/questRewardLetters.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25import { floorDiv } from "../world/coordinates.js";
25import { floorDiv } from "../world/coordinates.js";
26import { WorkerMessage } from "../simulation/protocol.js";
26import { WorkerMessage } from "../simulation/protocol.js";
27
27
28/**
28/**
29 * Quest progress + dialogue sessions (main simulation thread).
29 * Quest progress + dialogue sessions (main simulation thread).
30 */
30 */
31export class QuestRuntime
31export class QuestRuntime
32{
32{
33 constructor ({ stateDb, content, simulation })
33 constructor ({ stateDb, content, simulation })
34 {
34 {
35 this.stateDb = stateDb;
35 this.stateDb = stateDb;
36 this.content = content;
36 this.content = content;
37 this.simulation = simulation;
37 this.simulation = simulation;
38 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
38 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
39 this.sessions = new Map();
39 this.sessions = new Map();
40 }
40 }
41
41
42 reloadContent ()
42 reloadContent ()
43 {
43 {
44 this.content.reload();
44 this.content.reload();
45 }
45 }
46
46
47 closeAllSessions ()
47 closeAllSessions ()
48 {
48 {
49 for (const characterId of [...this.sessions.keys()])
49 for (const characterId of [...this.sessions.keys()])
50 { this.closeDialogue(characterId, "revision"); }
50 { this.closeDialogue(characterId, "revision"); }
51 }
51 }
52
52
53 questSnapshot (characterId)
53 questSnapshot (characterId)
54 {
54 {
55 const states = this.stateDb.listQuestStates(characterId)
55 const states = this.stateDb.listQuestStates(characterId)
56 .filter((row) => row.state !== "not-started");
56 .filter((row) => row.state !== "not-started");
57 const quests = [];
57 const quests = [];
58 const playerView = this.playerViewFor(characterId);
58 const playerView = this.playerViewFor(characterId);
59 for (const row of states)
59 for (const row of states)
60 {
60 {
61 const def = this.content.quest(row.questId);
61 const def = this.content.quest(row.questId);
62 if (!def)
62 if (!def)
63 {
63 {
64 quests.push({
64 quests.push({
65 questId: row.questId,
65 questId: row.questId,
66 title: "Quest unavailable",
66 title: "Quest unavailable",
67 orphaned: true,
67 orphaned: true,
68 state: row.state,
68 state: row.state,
69 description: "",
69 description: "",
70 step: null,
70 step: null,
71 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
71 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
72 });
72 });
73 continue;
73 continue;
74 }
74 }
75 const stepIndex = typeof row.state === "number" ? row.state : null;
75 const stepIndex = typeof row.state === "number" ? row.state : null;
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
76 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
77 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
77 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
78 const ctx = stepDef
78 const ctx = stepDef
79 ? this.buildConditionContext(characterId, playerView, row.questId)
79 ? this.buildConditionContext(characterId, playerView, row.questId)
80 : null;
80 : null;
81 quests.push({
81 quests.push({
82 questId: def.questId,
82 questId: def.questId,
83 title: def.title,
83 title: def.title,
84 orphaned: false,
84 orphaned: false,
85 state: row.state,
85 state: row.state,
86 description: def.description,
86 description: def.description,
87 step: stepDef
87 step: stepDef
88 ? {
88 ? {
89 stepId: stepDef.stepId,
89 stepId: stepDef.stepId,
90 title: stepDef.title,
90 title: stepDef.title,
91 description: stepDef.description,
91 description: stepDef.description,
92 objectives: stepDef.objectives.map((obj) =>
92 objectives: stepDef.objectives.map((obj) =>
93 {
93 {
94 const done = completedObjectiveIds.includes(obj.objectiveId);
94 const done = completedObjectiveIds.includes(obj.objectiveId);
95 const progress = countableObjectiveProgress(obj.when, ctx);
95 const progress = countableObjectiveProgress(obj.when, ctx);
96 return {
96 return {
97 objectiveId: obj.objectiveId,
97 objectiveId: obj.objectiveId,
98 text: obj.text,
98 text: obj.text,
99 done,
99 done,
100 current: progress?.current ?? null,
100 current: progress?.current ?? null,
101 required: progress?.required ?? null
101 required: progress?.required ?? null
102 };
102 };
103 })
103 })
104 }
104 }
105 : null,
105 : null,
106 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
106 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
107 });
107 });
108 }
108 }
109 quests.sort((a, b) =>
109 quests.sort((a, b) =>
110 {
110 {
111 const aDone = a.state === "completed" ? 1 : 0;
111 const aDone = a.state === "completed" ? 1 : 0;
112 const bDone = b.state === "completed" ? 1 : 0;
112 const bDone = b.state === "completed" ? 1 : 0;
113 if (aDone !== bDone)
113 if (aDone !== bDone)
114 { return aDone - bDone; }
114 { return aDone - bDone; }
115 return String(a.title).localeCompare(String(b.title));
115 return String(a.title).localeCompare(String(b.title));
116 });
116 });
117 return { quests };
117 return { quests };
118 }
118 }
119
119
120 playerViewFor (characterId)
120 playerViewFor (characterId)
121 {
121 {
122 const entityId = this.simulation.characterEntities.get(characterId | 0);
122 const entityId = this.simulation.characterEntities.get(characterId | 0);
123 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
123 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
124 const skills = this.stateDb.getSkills(characterId) ?? {};
124 const skills = this.stateDb.getSkills(characterId) ?? {};
125 let hp = 1;
125 let hp = 1;
126 let maxHp = 1;
126 let maxHp = 1;
127 let stamina = 1;
127 let stamina = 1;
128 let maxStamina = 1;
128 let maxStamina = 1;
129 if (entityId != null && record)
129 if (entityId != null && record)
130 {
130 {
131 const staminaComp = this.simulation.staminaOf(entityId);
131 const staminaComp = this.simulation.staminaOf(entityId);
132 if (staminaComp)
132 if (staminaComp)
133 {
133 {
134 stamina = Number(staminaComp.current) || 0;
134 stamina = Number(staminaComp.current) || 0;
135 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
135 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
136 }
136 }
137 const worker = this.simulation.workers[record.workerId];
137 const worker = this.simulation.workers[record.workerId];
138 const view = worker?.call?.({
138 const view = worker?.call?.({
139 type: WorkerMessage.inspect,
139 type: WorkerMessage.inspect,
140 entityId
140 entityId
141 });
141 });
142 if (view && view.health != null)
142 if (view && view.health != null)
143 {
143 {
144 hp = Number(view.health) || 0;
144 hp = Number(view.health) || 0;
145 maxHp = Math.max(1, Number(view.maxHealth) || 1);
145 maxHp = Math.max(1, Number(view.maxHealth) || 1);
146 }
146 }
147 }
147 }
148 return {
148 return {
149 tileX: record?.tileX | 0,
149 tileX: record?.tileX | 0,
150 tileY: record?.tileY | 0,
150 tileY: record?.tileY | 0,
151 dimensionId: record?.dimensionId ?? "overworld",
151 dimensionId: record?.dimensionId ?? "overworld",
152 skills,
152 skills,
153 hp,
153 hp,
154 maxHp,
154 maxHp,
155 stamina,
155 stamina,
156 maxStamina
156 maxStamina
157 };
157 };
158 }
158 }
159
159
160 buildConditionContext (characterId, playerView, activeQuestId = null)
160 buildConditionContext (characterId, playerView, activeQuestId = null)
161 {
161 {
162 const bag = this.#loadBag(characterId);
162 const bag = this.#loadBag(characterId);
163 const inventory = bag?.inventory ?? [];
163 const inventory = bag?.inventory ?? [];
164 const tileX = playerView?.tileX | 0;
164 const tileX = playerView?.tileX | 0;
165 const tileY = playerView?.tileY | 0;
165 const tileY = playerView?.tileY | 0;
166 const dimensionId = playerView?.dimensionId ?? "overworld";
166 const dimensionId = playerView?.dimensionId ?? "overworld";
167 const chunkX = floorDiv(tileX, CHUNK_SIZE);
167 const chunkX = floorDiv(tileX, CHUNK_SIZE);
168 const chunkY = floorDiv(tileY, CHUNK_SIZE);
168 const chunkY = floorDiv(tileY, CHUNK_SIZE);
169 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
169 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
170 return {
170 return {
171 tileX,
171 tileX,
172 tileY,
172 tileY,
173 chunkX,
173 chunkX,
174 chunkY,
174 chunkY,
175 dimensionId,
175 dimensionId,
176 hp: playerView?.hp ?? 0,
176 hp: playerView?.hp ?? 0,
177 maxHp: playerView?.maxHp ?? 1,
177 maxHp: playerView?.maxHp ?? 1,
178 stamina: playerView?.stamina ?? 0,
178 stamina: playerView?.stamina ?? 0,
179 maxStamina: playerView?.maxStamina ?? 1,
179 maxStamina: playerView?.maxStamina ?? 1,
180 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
180 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
181 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
182 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
182 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
183 dialogueTriggerLatched: (dialogueId, trigger) =>
183 dialogueTriggerLatched: (dialogueId, trigger) =>
184 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
184 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
185 skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
185 skillLevel: (skillId) => resolveSkillRequirementLevel(playerView?.skills ?? {}, skillId),
186 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
186 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
187 killCount: (condition) =>
187 killCount: (condition) =>
188 {
188 {
189 if (!questRow)
189 if (!questRow)
190 { return 0; }
190 { return 0; }
191 return questRow.progress?.counters?.[killKey(condition)] | 0;
191 return questRow.progress?.counters?.[killKey(condition)] | 0;
192 },
192 },
193 interactBlockDone: (condition) =>
193 interactBlockDone: (condition) =>
194 {
194 {
195 if (!questRow)
195 if (!questRow)
196 { return false; }
196 { return false; }
197 return !!questRow.progress?.interacts?.[interactKey(condition)];
197 return !!questRow.progress?.interacts?.[interactKey(condition)];
198 }
198 }
199 };
199 };
200 }
200 }
201
201
202 tryOpenDialogue (characterId, entityId, dialogueId)
202 tryOpenDialogue (characterId, entityId, dialogueId)
203 {
203 {
204 const tree = this.content.dialogue(dialogueId);
204 const tree = this.content.dialogue(dialogueId);
205 if (!tree)
205 if (!tree)
206 { return { ok: false, error: "Nothing to say." }; }
206 { return { ok: false, error: "Nothing to say." }; }
207 this.closeDialogue(characterId, "replace");
207 this.closeDialogue(characterId, "replace");
208 const playerView = this.playerViewFor(characterId);
208 const playerView = this.playerViewFor(characterId);
209 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
209 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
210 }
210 }
211
211
212 chooseDialogue (characterId, triggerId)
212 chooseDialogue (characterId, triggerId)
213 {
213 {
214 const session = this.sessions.get(characterId | 0);
214 const session = this.sessions.get(characterId | 0);
215 if (!session)
215 if (!session)
216 { return { ok: false, error: "No dialogue open." }; }
216 { return { ok: false, error: "No dialogue open." }; }
217 if (session.phase === "lines")
217 if (session.phase === "lines")
218 { return { ok: false, error: "Finish reading first." }; }
218 { return { ok: false, error: "Finish reading first." }; }
219 if (session.phase === "rewards")
219 if (session.phase === "rewards")
220 { return { ok: false, error: "Finish reading first." }; }
220 { return { ok: false, error: "Finish reading first." }; }
221 const tree = this.content.dialogue(session.dialogueId);
221 const tree = this.content.dialogue(session.dialogueId);
222 if (!tree)
222 if (!tree)
223 {
223 {
224 this.closeDialogue(characterId, "missing");
224 this.closeDialogue(characterId, "missing");
225 return { ok: false, error: "Dialogue missing." };
225 return { ok: false, error: "Dialogue missing." };
226 }
226 }
227 const step = tree.steps.find((s) => s.stepId === session.stepId);
227 const step = tree.steps.find((s) => s.stepId === session.stepId);
228 if (!step || step.exit?.kind !== "triggers")
228 if (!step || step.exit?.kind !== "triggers")
229 { return { ok: false, error: "Cannot choose now." }; }
229 { return { ok: false, error: "Cannot choose now." }; }
230 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
230 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
231 if (!trigger)
231 if (!trigger)
232 { return { ok: false, error: "Unknown choice." }; }
232 { return { ok: false, error: "Unknown choice." }; }
233 const playerView = this.playerViewFor(characterId);
233 const playerView = this.playerViewFor(characterId);
234 const ctx = this.buildConditionContext(characterId, playerView);
234 const ctx = this.buildConditionContext(characterId, playerView);
235 if (!evaluateConditionSet(trigger.when, ctx))
235 if (!evaluateConditionSet(trigger.when, ctx))
236 { return { ok: false, error: "That choice is unavailable." }; }
236 { return { ok: false, error: "That choice is unavailable." }; }
237 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
237 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
238 const events = [];
238 const events = [];
239 this.#applyEffects(characterId, trigger.effects, playerView, events);
239 this.#applyEffects(characterId, trigger.effects, playerView, events);
240 this.#reevaluateQuests(characterId, playerView, events);
240 this.#reevaluateQuests(characterId, playerView, events);
241 if (!trigger.nextStepId)
241 if (!trigger.nextStepId)
242 {
242 {
243 const npcEntityId = session.entityId;
243 const npcEntityId = session.entityId;
244 this.sessions.delete(characterId | 0);
244 this.sessions.delete(characterId | 0);
245 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
245 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
246 return { ok: true, events };
246 return { ok: true, events };
247 }
247 }
248 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
248 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
249 }
249 }
250
250
251 closeDialogue (characterId, reason = "close")
251 closeDialogue (characterId, reason = "close")
252 {
252 {
253 const id = characterId | 0;
253 const id = characterId | 0;
254 const session = this.sessions.get(id);
254 const session = this.sessions.get(id);
255 if (!session)
255 if (!session)
256 { return { events: [] }; }
256 { return { events: [] }; }
257 this.sessions.delete(id);
257 this.sessions.delete(id);
258 return {
258 return {
259 events: [{
259 events: [{
260 type: "dialogueClose",
260 type: "dialogueClose",
261 reason,
261 reason,
262 npcEntityId: session.entityId
262 npcEntityId: session.entityId
263 }]
263 }]
264 };
264 };
265 }
265 }
266
266
267 interruptDialogueForEntity (entityId)
267 interruptDialogueForEntity (entityId)
268 {
268 {
269 const events = [];
269 const events = [];
270 for (const [characterId, session] of [...this.sessions])
270 for (const [characterId, session] of [...this.sessions])
271 {
271 {
272 if (session.entityId === (entityId | 0))
272 if (session.entityId === (entityId | 0))
273 {
273 {
274 const closed = this.closeDialogue(characterId, "attacked");
274 const closed = this.closeDialogue(characterId, "attacked");
275 events.push(...closed.events.map((e) => ({ ...e, characterId })));
275 events.push(...closed.events.map((e) => ({ ...e, characterId })));
276 }
276 }
277 }
277 }
278 return events;
278 return events;
279 }
279 }
280
280
281 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
281 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
282 {
282 {
283 const step = tree.steps.find((s) => s.stepId === stepId);
283 const step = tree.steps.find((s) => s.stepId === stepId);
284 if (!step)
284 if (!step)
285 {
285 {
286 this.sessions.delete(characterId | 0);
286 this.sessions.delete(characterId | 0);
287 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
287 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
288 return { ok: false, error: "Broken dialogue.", events: priorEvents };
288 return { ok: false, error: "Broken dialogue.", events: priorEvents };
289 }
289 }
290 const events = [...priorEvents];
290 const events = [...priorEvents];
291 const identity = this.#playerDialogueIdentity(characterId);
291 const identity = this.#playerDialogueIdentity(characterId);
292 const linePayloads = [];
292 const linePayloads = [];
293 for (const line of step.lines)
293 for (const line of step.lines)
294 {
294 {
295 this.#applyEffects(characterId, line.effects, playerView, events);
295 this.#applyEffects(characterId, line.effects, playerView, events);
296 linePayloads.push({
296 linePayloads.push({
297 speaker: line.speaker,
297 speaker: line.speaker,
298 text: applyDialogueTextReplacements(line.text, identity)
298 text: applyDialogueTextReplacements(line.text, identity)
299 });
299 });
300 }
300 }
301 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
301 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
302 // dialogueHeard is marked only when the step fully completes (after rewards).
302 // dialogueHeard is marked only when the step fully completes (after rewards).
303 this.sessions.set(characterId | 0, {
303 this.sessions.set(characterId | 0, {
304 entityId: entityId | 0,
304 entityId: entityId | 0,
305 dialogueId: tree.dialogueId,
305 dialogueId: tree.dialogueId,
306 stepId: step.stepId,
306 stepId: step.stepId,
307 phase: "lines",
307 phase: "lines",
308 pendingExit: step.exit ?? { kind: "end" }
308 pendingExit: step.exit ?? { kind: "end" }
309 });
309 });
310 events.push({
310 events.push({
311 type: "dialogueStep",
311 type: "dialogueStep",
312 dialogueId: tree.dialogueId,
312 dialogueId: tree.dialogueId,
313 stepId: step.stepId,
313 stepId: step.stepId,
314 label: step.label,
314 label: step.label,
315 npcEntityId: entityId | 0,
315 npcEntityId: entityId | 0,
316 lines: linePayloads
316 lines: linePayloads
317 });
317 });
318 this.#reevaluateQuests(characterId, playerView, events);
318 this.#reevaluateQuests(characterId, playerView, events);
319 return { ok: true, events };
319 return { ok: true, events };
320 }
320 }
321
321
322 /** Client finished reading all lines (or reward notices) of the current step. */
322 /** Client finished reading all lines (or reward notices) of the current step. */
323 advanceDialogue (characterId)
323 advanceDialogue (characterId)
324 {
324 {
325 const session = this.sessions.get(characterId | 0);
325 const session = this.sessions.get(characterId | 0);
326 if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
326 if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
327 { return { ok: false, error: "No dialogue lines to advance." }; }
327 { return { ok: false, error: "No dialogue lines to advance." }; }
328 const tree = this.content.dialogue(session.dialogueId);
328 const tree = this.content.dialogue(session.dialogueId);
329 if (!tree)
329 if (!tree)
330 {
330 {
331 this.sessions.delete(characterId | 0);
331 this.sessions.delete(characterId | 0);
332 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
332 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
333 }
333 }
334 const playerView = this.playerViewFor(characterId);
334 const playerView = this.playerViewFor(characterId);
335 const events = [];
335 const events = [];
336
336
337 if (session.phase === "lines")
337 if (session.phase === "lines")
338 {
338 {
339 const step = tree.steps.find((s) => s.stepId === session.stepId);
339 const step = tree.steps.find((s) => s.stepId === session.stepId);
340 const rewardMessages = [
340 const rewardMessages = [
341 ...this.#takeStepItems(characterId, step, events),
341 ...this.#takeStepItems(characterId, step, events),
342 ...this.#grantStepItemRewards(characterId, step, events),
342 ...this.#grantStepItemRewards(characterId, step, events),
343 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
343 ...this.#grantStepQuestRewards(characterId, step, playerView, events)
344 ];
344 ];
345 this.#reevaluateQuests(characterId, playerView, events);
345 this.#reevaluateQuests(characterId, playerView, events);
346 if (rewardMessages.length > 0)
346 if (rewardMessages.length > 0)
347 {
347 {
348 session.phase = "rewards";
348 session.phase = "rewards";
349 events.push({
349 events.push({
350 type: "dialogueItemRewards",
350 type: "dialogueItemRewards",
351 dialogueId: session.dialogueId,
351 dialogueId: session.dialogueId,
352 stepId: session.stepId,
352 stepId: session.stepId,
353 npcEntityId: session.entityId,
353 npcEntityId: session.entityId,
354 messages: rewardMessages
354 messages: rewardMessages
355 });
355 });
356 return { ok: true, events };
356 return { ok: true, events };
357 }
357 }
358 }
358 }
359
359
360 return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
360 return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
361 }
361 }
362
362
363 #resolveDialogueExit (characterId, session, tree, playerView, events)
363 #resolveDialogueExit (characterId, session, tree, playerView, events)
364 {
364 {
365 // Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
365 // Step is fully finished: lines read + takes/rewards/quest notices acknowledged.
366 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
366 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, session.stepId);
367 this.#reevaluateQuests(characterId, playerView, events);
367 this.#reevaluateQuests(characterId, playerView, events);
368
368
369 const exit = session.pendingExit ?? { kind: "end" };
369 const exit = session.pendingExit ?? { kind: "end" };
370
370
371 if (exit.kind === "branches")
371 if (exit.kind === "branches")
372 {
372 {
373 const ctx = this.buildConditionContext(characterId, playerView);
373 const ctx = this.buildConditionContext(characterId, playerView);
374 let matched = null;
374 let matched = null;
375 for (const branch of exit.branches ?? [])
375 for (const branch of exit.branches ?? [])
376 {
376 {
377 if (evaluateConditionSet(branch.when, ctx))
377 if (evaluateConditionSet(branch.when, ctx))
378 {
378 {
379 matched = branch;
379 matched = branch;
380 break;
380 break;
381 }
381 }
382 }
382 }
383 if (!matched || !matched.nextStepId)
383 if (!matched || !matched.nextStepId)
384 {
384 {
385 this.#applyEffects(characterId, matched?.effects, playerView, events);
385 this.#applyEffects(characterId, matched?.effects, playerView, events);
386 const npcEntityId = session.entityId;
386 const npcEntityId = session.entityId;
387 this.sessions.delete(characterId | 0);
387 this.sessions.delete(characterId | 0);
388 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
388 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
389 return { ok: true, events };
389 return { ok: true, events };
390 }
390 }
391 this.#applyEffects(characterId, matched.effects, playerView, events);
391 this.#applyEffects(characterId, matched.effects, playerView, events);
392 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
392 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
393 }
393 }
394
394
395 if (exit.kind === "triggers")
395 if (exit.kind === "triggers")
396 {
396 {
397 const ctx = this.buildConditionContext(characterId, playerView);
397 const ctx = this.buildConditionContext(characterId, playerView);
398 const identity = this.#playerDialogueIdentity(characterId);
398 const identity = this.#playerDialogueIdentity(characterId);
399 const triggers = (exit.triggers ?? [])
399 const triggers = (exit.triggers ?? [])
400 .filter((t) => evaluateConditionSet(t.when, ctx))
400 .filter((t) => evaluateConditionSet(t.when, ctx))
401 .map((t) => ({
401 .map((t) => ({
402 trigger: t.trigger,
402 trigger: t.trigger,
403 text: applyDialogueTextReplacements(t.text, identity)
403 text: applyDialogueTextReplacements(t.text, identity)
404 }));
404 }));
405 if (triggers.length === 0)
405 if (triggers.length === 0)
406 {
406 {
407 const npcEntityId = session.entityId;
407 const npcEntityId = session.entityId;
408 this.sessions.delete(characterId | 0);
408 this.sessions.delete(characterId | 0);
409 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
409 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
410 return { ok: true, events };
410 return { ok: true, events };
411 }
411 }
412 session.phase = "choices";
412 session.phase = "choices";
413 session.pendingExit = null;
413 session.pendingExit = null;
414 events.push({
414 events.push({
415 type: "dialogueChoices",
415 type: "dialogueChoices",
416 dialogueId: session.dialogueId,
416 dialogueId: session.dialogueId,
417 stepId: session.stepId,
417 stepId: session.stepId,
418 npcEntityId: session.entityId,
418 npcEntityId: session.entityId,
419 triggers
419 triggers
420 });
420 });
421 return { ok: true, events };
421 return { ok: true, events };
422 }
422 }
423
423
424 if (exit.kind === "continue")
424 if (exit.kind === "continue")
425 {
425 {
426 if (!exit.nextStepId)
426 if (!exit.nextStepId)
427 {
427 {
428 const npcEntityId = session.entityId;
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
431 return { ok: true, events };
432 }
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
434 }
435
435
436 const npcEntityId = session.entityId;
436 const npcEntityId = session.entityId;
437 this.sessions.delete(characterId | 0);
437 this.sessions.delete(characterId | 0);
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439 return { ok: true, events };
439 return { ok: true, events };
440 }
440 }
441
441
442 /**
442 /**
443 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
443 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444 */
444 */
445 #takeStepItems (characterId, step, events)
445 #takeStepItems (characterId, step, events)
446 {
446 {
447 const takes = step?.itemTakes ?? [];
447 const takes = step?.itemTakes ?? [];
448 if (!takes.length)
448 if (!takes.length)
449 { return []; }
449 { return []; }
450 const parts = [];
450 const parts = [];
451 for (const take of takes)
451 for (const take of takes)
452 {
452 {
453 const bag = this.#loadBag(characterId);
453 const bag = this.#loadBag(characterId);
454 if (!bag)
454 if (!bag)
455 { continue; }
455 { continue; }
456 const itemId = take.itemId | 0;
456 const itemId = take.itemId | 0;
457 const want = Math.max(1, Number(take.quantity) || 1);
457 const want = Math.max(1, Number(take.quantity) || 1);
458 const def = itemDefinition(itemId);
458 const def = itemDefinition(itemId);
459 const displayName = def?.displayName ?? `Item ${itemId}`;
459 const displayName = def?.displayName ?? `Item ${itemId}`;
460 const result = takeMatchingUpToFromSlots(bag.inventory, {
460 const result = takeMatchingUpToFromSlots(bag.inventory, {
461 itemId,
461 itemId,
462 quantity: want,
462 quantity: want,
463 compact: false
463 compact: false
464 });
464 });
465 if (!result.ok || result.takenQuantity <= 0)
465 if (!result.ok || result.takenQuantity <= 0)
466 { continue; }
466 { continue; }
467 bag.inventory = result.slots;
467 bag.inventory = result.slots;
468 this.#persistBag(characterId, bag);
468 this.#persistBag(characterId, bag);
469 events.push({ type: "inventoryDirty" });
469 events.push({ type: "inventoryDirty" });
470 parts.push({ displayName, quantity: result.takenQuantity });
470 parts.push({ displayName, quantity: result.takenQuantity });
471 }
471 }
472 const message = formatDialogueTakeMessage(parts);
472 const message = formatDialogueTakeMessage(parts);
473 return message ? [message] : [];
473 return message ? [message] : [];
474 }
474 }
475
475
476 /**
476 /**
477 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
477 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478 */
478 */
479 #grantStepItemRewards (characterId, step, events)
479 #grantStepItemRewards (characterId, step, events)
480 {
480 {
481 const rewards = step?.itemRewards ?? [];
481 const rewards = step?.itemRewards ?? [];
482 if (!rewards.length)
482 if (!rewards.length)
483 { return []; }
483 { return []; }
484 const bagParts = [];
484 const bagParts = [];
485 const bankParts = [];
485 const bankParts = [];
486 for (const reward of rewards)
486 for (const reward of rewards)
487 {
487 {
488 const bag = this.#loadBag(characterId);
488 const bag = this.#loadBag(characterId);
489 if (!bag)
489 if (!bag)
490 { continue; }
490 { continue; }
491 const itemId = reward.itemId | 0;
491 const itemId = reward.itemId | 0;
492 const def = itemDefinition(itemId);
492 const def = itemDefinition(itemId);
493 const quantity = Math.max(1, Number(reward.quantity) || 1);
493 const quantity = Math.max(1, Number(reward.quantity) || 1);
494 const displayName = def?.displayName ?? `Item ${itemId}`;
494 const displayName = def?.displayName ?? `Item ${itemId}`;
495 const stack = attachOrigins({
495 const stack = attachOrigins({
496 itemId,
496 itemId,
497 quantity,
497 quantity,
498 origins: [{ origin: godsOrigin(), quantity }]
498 origins: [{ origin: godsOrigin(), quantity }]
499 });
499 });
500 const result = insertStack(bag.inventory, stack, def);
500 const result = insertStack(bag.inventory, stack, def);
501 bag.inventory = result.slots;
501 bag.inventory = result.slots;
502 const intoBag = quantity - Math.max(0, result.remainder | 0);
502 const intoBag = quantity - Math.max(0, result.remainder | 0);
503 let intoBank = 0;
503 let intoBank = 0;
504 if (result.remainder > 0)
504 if (result.remainder > 0)
505 {
505 {
506 const vaultResult = insertStackGrowable(
506 const vaultResult = insertStackGrowable(
507 bag.vault,
507 bag.vault,
508 attachOrigins({
508 attachOrigins({
509 itemId,
509 itemId,
510 quantity: result.remainder,
510 quantity: result.remainder,
511 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
511 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512 }),
512 }),
513 def
513 def
514 );
514 );
515 bag.vault = vaultResult.slots;
515 bag.vault = vaultResult.slots;
516 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
516 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517 }
517 }
518 this.#persistBag(characterId, bag);
518 this.#persistBag(characterId, bag);
519 events.push({ type: "inventoryDirty" });
519 events.push({ type: "inventoryDirty" });
520 if (intoBag > 0)
520 if (intoBag > 0)
521 { bagParts.push({ displayName, quantity: intoBag }); }
521 { bagParts.push({ displayName, quantity: intoBag }); }
522 if (intoBank > 0)
522 if (intoBank > 0)
523 { bankParts.push({ displayName, quantity: intoBank }); }
523 { bankParts.push({ displayName, quantity: intoBank }); }
524 }
524 }
525 const messages = [];
525 const messages = [];
526 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
526 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
527 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528 if (bagMsg)
528 if (bagMsg)
529 { messages.push(bagMsg); }
529 { messages.push(bagMsg); }
530 if (bankMsg)
530 if (bankMsg)
531 { messages.push(bankMsg); }
531 { messages.push(bankMsg); }
532 return messages;
532 return messages;
533 }
533 }
534
534
535 /** Start step.questRewards; returns player-facing notices for newly started quests. */
535 /** Start step.questRewards; returns player-facing notices for newly started quests. */
536 #grantStepQuestRewards (characterId, step, playerView, events)
536 #grantStepQuestRewards (characterId, step, playerView, events)
537 {
537 {
538 const rewards = step?.questRewards ?? [];
538 const rewards = step?.questRewards ?? [];
539 if (!rewards.length)
539 if (!rewards.length)
540 { return []; }
540 { return []; }
541 const titles = [];
541 const titles = [];
542 for (const questId of rewards)
542 for (const questId of rewards)
543 {
543 {
544 const current = this.stateDb.getQuestState(characterId, questId);
544 const current = this.stateDb.getQuestState(characterId, questId);
545 if (current.state !== "not-started")
545 if (current.state !== "not-started")
546 { continue; }
546 { continue; }
547 const def = this.content.quest(questId);
547 const def = this.content.quest(questId);
548 if (!def)
548 if (!def)
549 { continue; }
549 { continue; }
550 this.startQuest(characterId, questId, playerView, events);
550 this.startQuest(characterId, questId, playerView, events);
551 titles.push(def.title || def.questId);
551 titles.push(def.title || def.questId);
552 }
552 }
553 const message = formatDialogueQuestRewardMessage(titles);
553 const message = formatDialogueQuestRewardMessage(titles);
554 return message ? [message] : [];
554 return message ? [message] : [];
555 }
555 }
556
556
557 #loadBag (characterId)
557 #loadBag (characterId)
558 {
558 {
559 const onlineId = this.simulation.characterEntities.get(characterId | 0);
559 const onlineId = this.simulation.characterEntities.get(characterId | 0);
560 const bag = onlineId
560 const bag = onlineId
561 ? this.simulation.bagOf(onlineId)
561 ? this.simulation.bagOf(onlineId)
562 : this.stateDb.getBag(characterId);
562 : this.stateDb.getBag(characterId);
563 return bag;
563 return bag;
564 }
564 }
565
565
566 #playerDialogueIdentity (characterId)
566 #playerDialogueIdentity (characterId)
567 {
567 {
568 const row = this.stateDb.getCharacter(characterId | 0);
568 const row = this.stateDb.getCharacter(characterId | 0);
569 return {
569 return {
570 firstName: String(row?.first_name ?? "").trim(),
570 firstName: String(row?.first_name ?? "").trim(),
571 lastName: String(row?.last_name ?? "").trim(),
571 lastName: String(row?.last_name ?? "").trim(),
572 sex: row?.sex === "female" ? "female" : "male"
572 sex: row?.sex === "female" ? "female" : "male"
573 };
573 };
574 }
574 }
575
575
576 #persistBag (characterId, bag)
576 #persistBag (characterId, bag)
577 {
577 {
578 this.stateDb.saveBag(characterId, bag);
578 this.stateDb.saveBag(characterId, bag);
579 const onlineId = this.simulation.characterEntities.get(characterId | 0);
579 const onlineId = this.simulation.characterEntities.get(characterId | 0);
580 if (onlineId)
580 if (onlineId)
581 {
581 {
582 this.simulation.applyBag?.(onlineId, bag);
582 this.simulation.applyBag?.(onlineId, bag);
583 this.simulation.pushInventory?.(characterId, bag);
583 this.simulation.pushInventory?.(characterId, bag);
584 }
584 }
585 }
585 }
586
586
587 #applyEffects (characterId, effects, playerView, events)
587 #applyEffects (characterId, effects, playerView, events)
588 {
588 {
589 if (!Array.isArray(effects) || effects.length === 0)
589 if (!Array.isArray(effects) || effects.length === 0)
590 { return; }
590 { return; }
591 for (const effect of effects)
591 for (const effect of effects)
592 {
592 {
593 if (effect.kind === EffectKind.giveItem)
593 if (effect.kind === EffectKind.giveItem)
594 {
594 {
595 const bag = this.#loadBag(characterId);
595 const bag = this.#loadBag(characterId);
596 if (!bag)
596 if (!bag)
597 { continue; }
597 { continue; }
598 const def = itemDefinition(effect.itemId | 0);
598 const def = itemDefinition(effect.itemId | 0);
599 const quantity = Math.max(1, Number(effect.quantity) || 1);
599 const quantity = Math.max(1, Number(effect.quantity) || 1);
600 const stack = attachOrigins({
600 const stack = attachOrigins({
601 itemId: effect.itemId | 0,
601 itemId: effect.itemId | 0,
602 quantity,
602 quantity,
603 origins: [{ origin: godsOrigin(), quantity }]
603 origins: [{ origin: godsOrigin(), quantity }]
604 });
604 });
605 if (effect.toBank)
605 if (effect.toBank)
606 {
606 {
607 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
607 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608 bag.vault = vaultResult.slots;
608 bag.vault = vaultResult.slots;
609 }
609 }
610 else
610 else
611 {
611 {
612 const result = insertStack(bag.inventory, stack, def);
612 const result = insertStack(bag.inventory, stack, def);
613 bag.inventory = result.slots;
613 bag.inventory = result.slots;
614 if (result.remainder > 0)
614 if (result.remainder > 0)
615 {
615 {
616 const vaultResult = insertStackGrowable(
616 const vaultResult = insertStackGrowable(
617 bag.vault ?? [],
617 bag.vault ?? [],
618 attachOrigins({
618 attachOrigins({
619 itemId: effect.itemId | 0,
619 itemId: effect.itemId | 0,
620 quantity: result.remainder,
620 quantity: result.remainder,
621 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
621 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622 }),
622 }),
623 def
623 def
624 );
624 );
625 bag.vault = vaultResult.slots;
625 bag.vault = vaultResult.slots;
626 }
626 }
627 }
627 }
628 this.#persistBag(characterId, bag);
628 this.#persistBag(characterId, bag);
629 events.push({ type: "inventoryDirty" });
629 events.push({ type: "inventoryDirty" });
630 }
630 }
631 else if (effect.kind === EffectKind.takeItem)
631 else if (effect.kind === EffectKind.takeItem)
632 {
632 {
633 const bag = this.#loadBag(characterId);
633 const bag = this.#loadBag(characterId);
634 if (!bag)
634 if (!bag)
635 { continue; }
635 { continue; }
636 const taken = takeMatchingFromSlots(bag.inventory, {
636 const taken = takeMatchingFromSlots(bag.inventory, {
637 itemId: effect.itemId | 0,
637 itemId: effect.itemId | 0,
638 quantity: Math.max(1, Number(effect.quantity) || 1),
638 quantity: Math.max(1, Number(effect.quantity) || 1),
639 compact: false
639 compact: false
640 });
640 });
641 if (taken.ok)
641 if (taken.ok)
642 {
642 {
643 bag.inventory = taken.slots;
643 bag.inventory = taken.slots;
644 this.#persistBag(characterId, bag);
644 this.#persistBag(characterId, bag);
645 events.push({ type: "inventoryDirty" });
645 events.push({ type: "inventoryDirty" });
646 }
646 }
647 }
647 }
648 else if (effect.kind === EffectKind.giveXp)
648 else if (effect.kind === EffectKind.giveXp)
649 {
649 {
650 const skills = this.stateDb.getSkills(characterId);
650 const skills = this.stateDb.getSkills(characterId);
651 if (skills)
651 if (skills)
652 {
652 {
653 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
653 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654 this.stateDb.saveSkills(characterId, skills);
654 this.stateDb.saveSkills(characterId, skills);
655 if (playerView)
655 if (playerView)
656 { playerView.skills = skills; }
656 { playerView.skills = skills; }
657 events.push({ type: "skillsDirty" });
657 events.push({ type: "skillsDirty" });
658 }
658 }
659 }
659 }
660 else if (effect.kind === EffectKind.startQuest)
660 else if (effect.kind === EffectKind.startQuest)
661 { this.startQuest(characterId, effect.questId, playerView, events); }
661 { this.startQuest(characterId, effect.questId, playerView, events); }
662 }
662 }
663 }
663 }
664
664
665 startQuest (characterId, questId, playerView, events = [])
665 startQuest (characterId, questId, playerView, events = [])
666 {
666 {
667 const def = this.content.quest(questId);
667 const def = this.content.quest(questId);
668 if (!def)
668 if (!def)
669 { return; }
669 { return; }
670 const current = this.stateDb.getQuestState(characterId, questId);
670 const current = this.stateDb.getQuestState(characterId, questId);
671 if (current.state !== "not-started")
671 if (current.state !== "not-started")
672 { return; }
672 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
673 this.stateDb.saveQuestState(characterId, questId, 1, {
674 completedObjectiveIds: [],
674 completedObjectiveIds: [],
675 counters: {},
675 counters: {},
676 interacts: {}
676 interacts: {}
677 }, Date.now(), null);
677 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679 events.push({ type: "questsDirty" });
679 events.push({ type: "questsDirty", characterId });
680 this.#reevaluateQuests(characterId, playerView, events);
680 this.#reevaluateQuests(characterId, playerView, events);
681 }
681 }
682
682
683 /**
683 /**
684 * Grant world-settings initial quests when the character has not started or completed them.
684 * Grant world-settings initial quests when the character has not started or completed them.
685 */
685 */
686 ensureInitialQuests (characterId, playerView = null, events = [])
686 ensureInitialQuests (characterId, playerView = null, events = [])
687 {
687 {
688 const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
688 const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689 for (const questId of list)
689 for (const questId of list)
690 { this.startQuest(characterId, questId, playerView, events); }
690 { this.startQuest(characterId, questId, playerView, events); }
691 return events;
691 return events;
692 }
692 }
693
693
694 /**
694 /**
695 * Re-check active quest objectives against live bag/position/etc.
695 * Re-check active quest objectives against live bag/position/etc.
696 * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
696 * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697 */
697 */
698 reevaluateQuests (characterId, playerView = null, events = [])
698 reevaluateQuests (characterId, playerView = null, events = [])
699 {
699 {
700 const view = playerView ?? this.playerViewFor(characterId);
700 const view = playerView ?? this.playerViewFor(characterId);
701 this.#reevaluateQuests(characterId, view, events);
701 this.#reevaluateQuests(characterId, view, events);
702 return events;
702 return events;
703 }
703 }
704
704
705 /** Apply initial quests to every character in state (settings save / apply). */
705 /** Apply initial quests to every character in state (settings save / apply). */
706 grantInitialQuestsToAllCharacters ()
706 grantInitialQuestsToAllCharacters ()
707 {
707 {
708 const events = [];
708 const events = [];
709 for (const characterId of this.stateDb.listAllCharacterIds())
709 for (const characterId of this.stateDb.listAllCharacterIds())
710 { this.ensureInitialQuests(characterId, null, events); }
710 { this.ensureInitialQuests(characterId, null, events); }
711 return events;
711 return events;
712 }
712 }
713
713
714 /**
714 /**
715 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
715 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
716 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717 */
717 */
718 #grantQuestCompletionRewards (characterId, def, playerView, events)
718 #grantQuestCompletionRewards (characterId, def, playerView, events)
719 {
719 {
720 const xp = [];
720 const xp = [];
721 const bagItems = [];
721 const bagItems = [];
722 const bankItems = [];
722 const bankItems = [];
723 const rewards = def?.rewards ?? [];
723 const rewards = def?.rewards ?? [];
724 for (const effect of rewards)
724 for (const effect of rewards)
725 {
725 {
726 if (effect.kind === EffectKind.giveXp)
726 if (effect.kind === EffectKind.giveXp)
727 {
727 {
728 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
728 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729 if (amount <= 0)
729 if (amount <= 0)
730 { continue; }
730 { continue; }
731 const skillId = String(effect.skillId ?? "").trim();
731 const skillId = String(effect.skillId ?? "").trim();
732 if (!skillId)
732 if (!skillId)
733 { continue; }
733 { continue; }
734 const onlineId = this.simulation.characterEntities.get(characterId | 0);
734 const onlineId = this.simulation.characterEntities.get(characterId | 0);
735 let skills = onlineId
735 let skills = onlineId
736 ? this.simulation.skillsOf(onlineId)
736 ? this.simulation.skillsOf(onlineId)
737 : this.stateDb.getSkills(characterId);
737 : this.stateDb.getSkills(characterId);
738 if (!skills)
738 if (!skills)
739 { skills = this.stateDb.getSkills(characterId); }
739 { skills = this.stateDb.getSkills(characterId); }
740 if (!skills)
740 if (!skills)
741 { continue; }
741 { continue; }
742 applySkillXp(skills, skillId, amount);
742 applySkillXp(skills, skillId, amount);
743 this.stateDb.saveSkills(characterId, skills);
743 this.stateDb.saveSkills(characterId, skills);
744 if (playerView)
744 if (playerView)
745 { playerView.skills = skills; }
745 { playerView.skills = skills; }
746 if (onlineId)
746 if (onlineId)
747 { this.simulation.applySkills?.(onlineId, skills); }
747 { this.simulation.applySkills?.(onlineId, skills); }
748 const payload = publicSkillsPayload(skills);
748 const payload = publicSkillsPayload(skills);
749 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
749 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750 xp.push({
750 xp.push({
751 skillId,
751 skillId,
752 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
752 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753 amount
753 amount
754 });
754 });
755 continue;
755 continue;
756 }
756 }
757 if (effect.kind !== EffectKind.giveItem)
757 if (effect.kind !== EffectKind.giveItem)
758 { continue; }
758 { continue; }
759 const bag = this.#loadBag(characterId);
759 const bag = this.#loadBag(characterId);
760 if (!bag)
760 if (!bag)
761 { continue; }
761 { continue; }
762 const itemId = effect.itemId | 0;
762 const itemId = effect.itemId | 0;
763 const defItem = itemDefinition(itemId);
763 const defItem = itemDefinition(itemId);
764 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
764 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765 const displayName = defItem
765 const displayName = defItem
766 ? itemDisplayName({ itemId, quantity }, defItem)
766 ? itemDisplayName({ itemId, quantity }, defItem)
767 : `Item ${itemId}`;
767 : `Item ${itemId}`;
768 const stack = attachOrigins({
768 const stack = attachOrigins({
769 itemId,
769 itemId,
770 quantity,
770 quantity,
771 origins: [{ origin: godsOrigin(), quantity }]
771 origins: [{ origin: godsOrigin(), quantity }]
772 });
772 });
773 let intoBag = 0;
773 let intoBag = 0;
774 let intoBank = 0;
774 let intoBank = 0;
775 if (effect.toBank)
775 if (effect.toBank)
776 {
776 {
777 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
777 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778 bag.vault = vaultResult.slots;
778 bag.vault = vaultResult.slots;
779 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
779 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780 }
780 }
781 else
781 else
782 {
782 {
783 const result = insertStack(bag.inventory, stack, defItem);
783 const result = insertStack(bag.inventory, stack, defItem);
784 bag.inventory = result.slots;
784 bag.inventory = result.slots;
785 intoBag = quantity - Math.max(0, result.remainder | 0);
785 intoBag = quantity - Math.max(0, result.remainder | 0);
786 if (result.remainder > 0)
786 if (result.remainder > 0)
787 {
787 {
788 const vaultResult = insertStackGrowable(
788 const vaultResult = insertStackGrowable(
789 bag.vault ?? [],
789 bag.vault ?? [],
790 attachOrigins({
790 attachOrigins({
791 itemId,
791 itemId,
792 quantity: result.remainder,
792 quantity: result.remainder,
793 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
793 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794 }),
794 }),
795 defItem
795 defItem
796 );
796 );
797 bag.vault = vaultResult.slots;
797 bag.vault = vaultResult.slots;
798 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
798 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799 }
799 }
800 }
800 }
801 this.#persistBag(characterId, bag);
801 this.#persistBag(characterId, bag);
802 events.push({ type: "inventoryDirty" });
802 events.push({ type: "inventoryDirty" });
803 if (intoBag > 0)
803 if (intoBag > 0)
804 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
804 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
805 if (intoBank > 0)
805 if (intoBank > 0)
806 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
806 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
807 }
807 }
808
808
809 if (bankItems.length)
809 if (bankItems.length)
810 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
810 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
811
812 return { xp, bagItems };
812 return { xp, bagItems };
813 }
813 }
814
814
815 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
815 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
816 {
816 {
817 const courier = this.simulation.courier;
817 const courier = this.simulation.courier;
818 if (!courier?.enqueueSystemLetter)
818 if (!courier?.enqueueSystemLetter)
819 { return; }
819 { return; }
820 const row = this.stateDb.getCharacter?.(characterId);
820 const row = this.stateDb.getCharacter?.(characterId);
821 const characterDisplayName = row
821 const characterDisplayName = row
822 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
822 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823 : "Adventurer";
823 : "Adventurer";
824 const originTileX = row?.tile_x | 0;
824 const originTileX = row?.tile_x | 0;
825 const originTileY = row?.tile_y | 0;
825 const originTileY = row?.tile_y | 0;
826 const bank = courier.nearestBank?.(originTileX, originTileY);
826 const originDim = row?.dimension_id ?? undefined;
827 courier.enqueueSystemLetter({
827 const bank = courier.nearestBank?.(originTileX, originTileY, originDim);
828 characterId: characterId | 0,
828 courier.enqueueSystemLetter({
829 originTileX: bank?.tileX ?? originTileX,
829 characterId: characterId | 0,
830 originTileY: bank?.tileY ?? originTileY,
830 originTileX: bank?.tileX ?? originTileX,
831 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
831 originTileY: bank?.tileY ?? originTileY,
832 authorOrganization: QUESTWARD_GIFT_ORG,
832 originDimensionId: bank?.dimensionId ?? originDim,
833 body: formatQuestBankRewardLetterBody({
833 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
834 characterDisplayName,
834 authorOrganization: QUESTWARD_GIFT_ORG,
835 questTitle: def?.title ?? def?.questId,
835 body: formatQuestBankRewardLetterBody({
836 items: bankItems
836 characterDisplayName,
837 })
837 questTitle: def?.title ?? def?.questId,
838 });
838 items: bankItems
839 }
839 })
840
840 });
841 #reevaluateQuests (characterId, playerView, events)
841 }
842 {
842
843 const states = this.stateDb.listQuestStates(characterId)
843 #reevaluateQuests (characterId, playerView, events)
844 .filter((row) => typeof row.state === "number");
844 {
845 for (const row of states)
845 const states = this.stateDb.listQuestStates(characterId)
846 {
846 .filter((row) => typeof row.state === "number");
847 const def = this.content.quest(row.questId);
847 for (const row of states)
848 if (!def)
848 {
849 { continue; }
849 const def = this.content.quest(row.questId);
850 const stepDef = def.steps[row.state - 1];
850 if (!def)
851 if (!stepDef)
851 { continue; }
852 { continue; }
852 const stepDef = def.steps[row.state - 1];
853 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
853 if (!stepDef)
854 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
854 { continue; }
855 const newlyDone = [];
855 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856 let changed = false;
856 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857 for (const obj of stepDef.objectives)
857 const newlyDone = [];
858 {
858 let changed = false;
859 if (completed.has(obj.objectiveId))
859 for (const obj of stepDef.objectives)
860 { continue; }
860 {
861 if (evaluateConditionSet(obj.when, ctx))
861 if (completed.has(obj.objectiveId))
862 {
862 { continue; }
863 completed.add(obj.objectiveId);
863 if (evaluateConditionSet(obj.when, ctx))
864 newlyDone.push(obj);
864 {
865 changed = true;
865 completed.add(obj.objectiveId);
866 }
866 newlyDone.push(obj);
867 }
867 changed = true;
868 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
868 }
869 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
869 }
870 if (!changed && !progressChanged)
870 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
871 { continue; }
871 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
872 for (const obj of newlyDone)
872 if (!changed && !progressChanged)
873 {
873 { continue; }
874 events.push({
874 for (const obj of newlyDone)
875 type: "questObjectiveComplete",
875 {
876 questId: row.questId,
876 events.push({
877 objectiveId: obj.objectiveId,
877 type: "questObjectiveComplete",
878 text: obj.text || "Objective"
878 questId: row.questId,
879 });
879 objectiveId: obj.objectiveId,
880 }
880 text: obj.text || "Objective"
881 const progress = {
881 });
882 ...row.progress,
882 }
883 completedObjectiveIds: [...completed],
883 const progress = {
884 progressFingerprint: fingerprint
884 ...row.progress,
885 };
885 completedObjectiveIds: [...completed],
886 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
886 progressFingerprint: fingerprint
887 if (!allDone)
887 };
888 {
888 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
889 if (!allDone)
890 events.push({ type: "questsDirty" });
890 {
891 continue;
891 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
892 }
892 events.push({ type: "questsDirty", characterId });
893 if (!changed)
893 continue;
894 {
894 }
895 // Progress-only update while already fully complete (should not happen).
895 if (!changed)
896 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
896 {
897 events.push({ type: "questsDirty" });
897 // Progress-only update while already fully complete (should not happen).
898 continue;
898 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
899 }
899 events.push({ type: "questsDirty", characterId });
900 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
900 continue;
901 const journal = this.stateDb.appendQuestJournal(
901 }
902 characterId,
902 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
903 row.questId,
903 const journal = this.stateDb.appendQuestJournal(
904 stepDef.stepId,
904 characterId,
905 stepDef.completionJournalText
905 row.questId,
906 );
906 stepDef.stepId,
907 const nextIndex = row.state + 1;
907 stepDef.completionJournalText
908 if (nextIndex > def.steps.length)
908 );
909 {
909 const nextIndex = row.state + 1;
910 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
910 if (nextIndex > def.steps.length)
911 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
911 {
912 events.push({
912 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
913 type: "questComplete",
913 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
914 questId: row.questId,
914 events.push({
915 title: def.title,
915 type: "questComplete",
916 xp: summary.xp,
916 questId: row.questId,
917 items: summary.bagItems
917 title: def.title,
918 });
918 xp: summary.xp,
919 }
919 items: summary.bagItems
920 else
920 });
921 {
921 }
922 const nextStep = def.steps[nextIndex - 1];
922 else
923 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
923 {
924 completedObjectiveIds: [],
924 const nextStep = def.steps[nextIndex - 1];
925 counters: {},
925 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
926 interacts: {},
926 completedObjectiveIds: [],
927 progressFingerprint: ""
927 counters: {},
928 }, row.startedAt, null);
928 interacts: {},
929 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
929 progressFingerprint: ""
930 events.push({
930 }, row.startedAt, null);
931 type: "questStepComplete",
931 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932 questId: row.questId,
932 events.push({
933 title: def.title,
933 type: "questStepComplete",
934 journalText: journal?.text ?? null
934 questId: row.questId,
935 });
935 title: def.title,
936 }
936 journalText: journal?.text ?? null
937 events.push({ type: "questsDirty" });
937 });
938 }
938 }
939 }
939 events.push({ type: "questsDirty", characterId });
940
940 }
941 noteKill (characterId, { mobTypeId, spawnerId })
941 }
942 {
942
943 const events = [];
943 noteKill (characterId, { mobTypeId, spawnerId })
944 const playerView = this.playerViewFor(characterId);
944 {
945 const states = this.stateDb.listQuestStates(characterId)
945 const events = [];
946 .filter((row) => typeof row.state === "number");
946 const playerView = this.playerViewFor(characterId);
947 for (const row of states)
947 const states = this.stateDb.listQuestStates(characterId)
948 {
948 .filter((row) => typeof row.state === "number");
949 const def = this.content.quest(row.questId);
949 for (const row of states)
950 const stepDef = def?.steps[row.state - 1];
950 {
951 if (!stepDef)
951 const def = this.content.quest(row.questId);
952 { continue; }
952 const stepDef = def?.steps[row.state - 1];
953 let changed = false;
953 if (!stepDef)
954 const counters = { ...(row.progress?.counters ?? {}) };
954 { continue; }
955 for (const obj of stepDef.objectives)
955 let changed = false;
956 {
956 const counters = { ...(row.progress?.counters ?? {}) };
957 for (const clause of obj.when?.all ?? [])
957 for (const obj of stepDef.objectives)
958 {
958 {
959 const c = clause.condition;
959 for (const clause of obj.when?.all ?? [])
960 if (c?.kind !== "killCount")
960 {
961 { continue; }
961 const c = clause.condition;
962 const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
962 if (!matchesKillCondition(c, mobTypeId, spawnerId))
963 const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
963 { continue; }
964 if (!matchMob && !matchSpawner)
964 const key = killKey(c);
965 { continue; }
965 counters[key] = (counters[key] | 0) + 1;
966 const key = killKey(c);
966 changed = true;
967 counters[key] = (counters[key] | 0) + 1;
967 }
968 changed = true;
968 }
969 }
969 if (!changed)
970 }
970 { continue; }
971 if (!changed)
971 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
972 { continue; }
972 ...row.progress,
973 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
973 counters
974 ...row.progress,
974 }, row.startedAt, row.completedAt);
975 counters
975 }
976 }, row.startedAt, row.completedAt);
976 this.#reevaluateQuests(characterId, playerView, events);
977 }
977 return events;
978 this.#reevaluateQuests(characterId, playerView, events);
978 }
979 return events;
979}
980 }
980
981}
981function journalPublic (row)
982
982{
983function journalPublic (row)
983 return {
984{
984 entryId: row.entry_id ?? row.entryId,
985 return {
985 questId: row.quest_id ?? row.questId,
986 entryId: row.entry_id ?? row.entryId,
986 stepId: row.step_id ?? row.stepId,
987 questId: row.quest_id ?? row.questId,
987 text: row.text,
988 stepId: row.step_id ?? row.stepId,
988 writtenAt: row.written_at ?? row.writtenAt
989 text: row.text,
989 };
990 writtenAt: row.written_at ?? row.writtenAt
990}
991 };
991
992}
992
993
993function matchesKillCondition (condition, mobTypeId, spawnerId)
994function killKey (condition)
994{
995{
995 if (!condition || typeof condition !== "object")
996 if (condition.spawnerId)
996 { return false; }
997 { return `spawner:${condition.spawnerId}`; }
997 if (condition.kind === "killMobFromSpawner")
998 return `mob:${condition.mobTypeId}`;
998 {
999}
999 if (condition.mobTypeId == null || condition.spawnerId == null || spawnerId == null)
1000
1000 { return false; }
1001function interactKey (condition)
1001 return String(condition.mobTypeId) === String(mobTypeId)
1002{
1002 && String(condition.spawnerId) === String(spawnerId);
1003 if (condition.tileX != null)
1003 }
1004 { return `tile:${condition.tileX},${condition.tileY}`; }
1004 if (condition.kind === "killCount")
1005 return `block:${condition.blockTypeId}`;
1005 {
1006}
1006 // Mob-type kills: match type. Legacy JSON may also use spawnerId alone.
1007 const matchMob = condition.mobTypeId != null && String(condition.mobTypeId) === String(mobTypeId);
1008 const matchSpawner = condition.spawnerId != null && String(condition.spawnerId) === String(spawnerId);
1009 return matchMob || matchSpawner;
1010 }
1011 return false;
1012}
1013
1014function killKey (condition)
1015{
1016 if (condition.spawnerId)
1017 { return `spawner:${condition.spawnerId}`; }
1018 return `mob:${condition.mobTypeId}`;
1019}
1020
1021function interactKey (condition)
1022{
1023 if (condition.tileX != null)
1024 { return `tile:${condition.tileX},${condition.tileY}`; }
1025 return `block:${condition.blockTypeId}`;
1026}
server/src/simulation/simulation.js +41 −17
@@ -227,6 +227,7 @@ export class Simulation
227 227 this.#syncAllReplicas();
228 228 this.courier?.refreshBankIndex();
229 229 this.courier?.refreshBountyOfficeIndex();
230 this.courier?.refreshDoorwayIndex();
230 231 this.market?.refreshIndex();
231 232 this.questContent.reload();
232 233 this.quests?.closeAllSessions();
@@ -578,7 +579,7 @@ export class Simulation
578 579 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
579 580 this.#recalculateActivation(this.now);
580 581 this.#syncGhosts();
581 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
582 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY, dimensionId);
582 583 const characterId = character.character_id ?? row.character_id;
583 584 this.quests?.ensureInitialQuests?.(characterId);
584 585 this.syncCharacterConditionAccess(characterId);
@@ -925,8 +926,12 @@ export class Simulation
925 926 for (const [characterId, logout] of [...this.combatLogouts.entries()])
926 927 {
927 928 const track = this.combatTracking.get(characterId);
928 const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt;
929 if ((now - lastActivity) < COMBAT_LOGOUT_MS)
929 const startedAt = logout.startedAt ?? now;
930 const lastActivity = track?.lastCombatActivityAt ?? startedAt;
931 const quietDone = (now - lastActivity) >= COMBAT_LOGOUT_MS;
932 // Hard cap from disconnect so auto-cast / hits cannot extend forever.
933 const hardCapDone = (now - startedAt) >= COMBAT_LOGOUT_MS;
934 if (!quietDone && !hardCapDone)
930 935 { continue; }
931 936 if (logout.pendingCowardice)
932 937 { applyCombatLogoutCowardice(this, characterId, { now }); }
@@ -963,16 +968,22 @@ export class Simulation
963 968 });
964 969 if (dropped)
965 970 {
971 const dimensionId = normalizeDimensionId(
972 dropped.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
973 );
966 974 this.stateDb.saveCharacterPosition(
967 975 characterId,
968 976 dropped.tileX,
969 977 dropped.tileY,
970 978 dropped.gait ?? GAIT.walk,
971 dropped.dimensionId ?? OVERWORLD_ID
979 dimensionId
972 980 );
973 981 if (dropped.health != null)
974 982 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
975 this.#queueReplication(replicationDespawn(dropped));
983 this.#queueReplication({
984 ...replicationDespawn(dropped),
985 dimensionId
986 });
976 987 }
977 988 this.#forget(entityId);
978 989 this.combatLogouts.delete(characterId | 0);
@@ -1243,6 +1254,7 @@ export class Simulation
1243 1254 characterId,
1244 1255 originTileX: position.tileX,
1245 1256 originTileY: position.tileY,
1257 originDimensionId: position.dimensionId ?? OVERWORLD_ID,
1246 1258 destination,
1247 1259 cargo
1248 1260 });
@@ -2022,6 +2034,7 @@ export class Simulation
2022 2034 {
2023 2035 const out = [];
2024 2036 let needSnapshot = false;
2037 const snapshotCharacterIds = new Set();
2025 2038 const syncAccessIds = new Set();
2026 2039 for (const event of events ?? [])
2027 2040 {
@@ -2102,7 +2115,11 @@ export class Simulation
2102 2115 });
2103 2116 }
2104 2117 else if (event.type === "questsDirty")
2105 { needSnapshot = true; }
2118 {
2119 needSnapshot = true;
2120 if (cid != null)
2121 { snapshotCharacterIds.add(cid | 0); }
2122 }
2106 2123 else if (event.type === "inventoryDirty" && cid != null)
2107 2124 {
2108 2125 const onlineId = this.characterEntities.get(cid | 0);
@@ -2129,16 +2146,21 @@ export class Simulation
2129 2146 needSnapshot = true;
2130 2147 }
2131 2148 }
2132 if (needSnapshot && characterId != null)
2149 if (needSnapshot)
2133 2150 {
2134 const snap = this.quests.questSnapshot(characterId);
2135 out.push({
2136 type: "quests-snapshot",
2137 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
2138 characterId,
2139 ...snap
2140 });
2141 syncAccessIds.add(characterId | 0);
2151 if (characterId != null)
2152 { snapshotCharacterIds.add(characterId | 0); }
2153 for (const snapCharacterId of snapshotCharacterIds)
2154 {
2155 const snap = this.quests.questSnapshot(snapCharacterId);
2156 out.push({
2157 type: "quests-snapshot",
2158 sessionId: sessionId ?? this.#sessionIdForCharacter(snapCharacterId),
2159 characterId: snapCharacterId,
2160 ...snap
2161 });
2162 syncAccessIds.add(snapCharacterId | 0);
2163 }
2142 2164 }
2143 2165 for (const id of syncAccessIds)
2144 2166 { this.syncCharacterConditionAccess(id); }
@@ -2162,10 +2184,11 @@ export class Simulation
2162 2184 : null;
2163 2185 if (killerCharacterId && this.quests)
2164 2186 {
2187 // Pass characterId so questsDirty produces a quests-snapshot for the killer.
2165 2188 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
2166 2189 mobTypeId: event.mobTypeId,
2167 2190 spawnerId: event.spawnerId
2168 })));
2191 }), null, killerCharacterId));
2169 2192 }
2170 2193 out.push(...this.#mapQuestPrivateEvents(
2171 2194 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
@@ -2253,7 +2276,8 @@ export class Simulation
2253 2276 event.characterId,
2254 2277 event.attackerId,
2255 2278 event.tileX,
2256 event.tileY
2279 event.tileY,
2280 record.dimensionId ?? OVERWORLD_ID
2257 2281 );
2258 2282 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
2259 2283 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
@@ -227,6 +227,7 @@ export class Simulation
227 this.#syncAllReplicas();
227 this.#syncAllReplicas();
228 this.courier?.refreshBankIndex();
228 this.courier?.refreshBankIndex();
229 this.courier?.refreshBountyOfficeIndex();
229 this.courier?.refreshBountyOfficeIndex();
230 this.courier?.refreshDoorwayIndex();
230 this.market?.refreshIndex();
231 this.market?.refreshIndex();
231 this.questContent.reload();
232 this.questContent.reload();
232 this.quests?.closeAllSessions();
233 this.quests?.closeAllSessions();
@@ -578,7 +579,7 @@ export class Simulation
578 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
579 this.#queueReplication(replicationSpawn(this.directory.get(view.entityId) ?? view));
579 this.#recalculateActivation(this.now);
580 this.#recalculateActivation(this.now);
580 this.#syncGhosts();
581 this.#syncGhosts();
581 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
582 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY, dimensionId);
582 const characterId = character.character_id ?? row.character_id;
583 const characterId = character.character_id ?? row.character_id;
583 this.quests?.ensureInitialQuests?.(characterId);
584 this.quests?.ensureInitialQuests?.(characterId);
584 this.syncCharacterConditionAccess(characterId);
585 this.syncCharacterConditionAccess(characterId);
@@ -925,8 +926,12 @@ export class Simulation
925 for (const [characterId, logout] of [...this.combatLogouts.entries()])
926 for (const [characterId, logout] of [...this.combatLogouts.entries()])
926 {
927 {
927 const track = this.combatTracking.get(characterId);
928 const track = this.combatTracking.get(characterId);
928 const lastActivity = track?.lastCombatActivityAt ?? logout.startedAt;
929 const startedAt = logout.startedAt ?? now;
929 if ((now - lastActivity) < COMBAT_LOGOUT_MS)
930 const lastActivity = track?.lastCombatActivityAt ?? startedAt;
931 const quietDone = (now - lastActivity) >= COMBAT_LOGOUT_MS;
932 // Hard cap from disconnect so auto-cast / hits cannot extend forever.
933 const hardCapDone = (now - startedAt) >= COMBAT_LOGOUT_MS;
934 if (!quietDone && !hardCapDone)
930 { continue; }
935 { continue; }
931 if (logout.pendingCowardice)
936 if (logout.pendingCowardice)
932 { applyCombatLogoutCowardice(this, characterId, { now }); }
937 { applyCombatLogoutCowardice(this, characterId, { now }); }
@@ -963,16 +968,22 @@ export class Simulation
963 });
968 });
964 if (dropped)
969 if (dropped)
965 {
970 {
971 const dimensionId = normalizeDimensionId(
972 dropped.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
973 );
966 this.stateDb.saveCharacterPosition(
974 this.stateDb.saveCharacterPosition(
967 characterId,
975 characterId,
968 dropped.tileX,
976 dropped.tileX,
969 dropped.tileY,
977 dropped.tileY,
970 dropped.gait ?? GAIT.walk,
978 dropped.gait ?? GAIT.walk,
971 dropped.dimensionId ?? OVERWORLD_ID
979 dimensionId
972 );
980 );
973 if (dropped.health != null)
981 if (dropped.health != null)
974 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
982 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
975 this.#queueReplication(replicationDespawn(dropped));
983 this.#queueReplication({
984 ...replicationDespawn(dropped),
985 dimensionId
986 });
976 }
987 }
977 this.#forget(entityId);
988 this.#forget(entityId);
978 this.combatLogouts.delete(characterId | 0);
989 this.combatLogouts.delete(characterId | 0);
@@ -1243,6 +1254,7 @@ export class Simulation
1243 characterId,
1254 characterId,
1244 originTileX: position.tileX,
1255 originTileX: position.tileX,
1245 originTileY: position.tileY,
1256 originTileY: position.tileY,
1257 originDimensionId: position.dimensionId ?? OVERWORLD_ID,
1246 destination,
1258 destination,
1247 cargo
1259 cargo
1248 });
1260 });
@@ -2022,6 +2034,7 @@ export class Simulation
2022 {
2034 {
2023 const out = [];
2035 const out = [];
2024 let needSnapshot = false;
2036 let needSnapshot = false;
2037 const snapshotCharacterIds = new Set();
2025 const syncAccessIds = new Set();
2038 const syncAccessIds = new Set();
2026 for (const event of events ?? [])
2039 for (const event of events ?? [])
2027 {
2040 {
@@ -2102,7 +2115,11 @@ export class Simulation
2102 });
2115 });
2103 }
2116 }
2104 else if (event.type === "questsDirty")
2117 else if (event.type === "questsDirty")
2105 { needSnapshot = true; }
2118 {
2119 needSnapshot = true;
2120 if (cid != null)
2121 { snapshotCharacterIds.add(cid | 0); }
2122 }
2106 else if (event.type === "inventoryDirty" && cid != null)
2123 else if (event.type === "inventoryDirty" && cid != null)
2107 {
2124 {
2108 const onlineId = this.characterEntities.get(cid | 0);
2125 const onlineId = this.characterEntities.get(cid | 0);
@@ -2129,16 +2146,21 @@ export class Simulation
2129 needSnapshot = true;
2146 needSnapshot = true;
2130 }
2147 }
2131 }
2148 }
2132 if (needSnapshot && characterId != null)
2149 if (needSnapshot)
2133 {
2150 {
2134 const snap = this.quests.questSnapshot(characterId);
2151 if (characterId != null)
2135 out.push({
2152 { snapshotCharacterIds.add(characterId | 0); }
2136 type: "quests-snapshot",
2153 for (const snapCharacterId of snapshotCharacterIds)
2137 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
2154 {
2138 characterId,
2155 const snap = this.quests.questSnapshot(snapCharacterId);
2139 ...snap
2156 out.push({
2140 });
2157 type: "quests-snapshot",
2141 syncAccessIds.add(characterId | 0);
2158 sessionId: sessionId ?? this.#sessionIdForCharacter(snapCharacterId),
2159 characterId: snapCharacterId,
2160 ...snap
2161 });
2162 syncAccessIds.add(snapCharacterId | 0);
2163 }
2142 }
2164 }
2143 for (const id of syncAccessIds)
2165 for (const id of syncAccessIds)
2144 { this.syncCharacterConditionAccess(id); }
2166 { this.syncCharacterConditionAccess(id); }
@@ -2162,10 +2184,11 @@ export class Simulation
2162 : null;
2184 : null;
2163 if (killerCharacterId && this.quests)
2185 if (killerCharacterId && this.quests)
2164 {
2186 {
2187 // Pass characterId so questsDirty produces a quests-snapshot for the killer.
2165 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
2188 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
2166 mobTypeId: event.mobTypeId,
2189 mobTypeId: event.mobTypeId,
2167 spawnerId: event.spawnerId
2190 spawnerId: event.spawnerId
2168 })));
2191 }), null, killerCharacterId));
2169 }
2192 }
2170 out.push(...this.#mapQuestPrivateEvents(
2193 out.push(...this.#mapQuestPrivateEvents(
2171 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
2194 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
@@ -2253,7 +2276,8 @@ export class Simulation
2253 event.characterId,
2276 event.characterId,
2254 event.attackerId,
2277 event.attackerId,
2255 event.tileX,
2278 event.tileX,
2256 event.tileY
2279 event.tileY,
2280 record.dimensionId ?? OVERWORLD_ID
2257 );
2281 );
2258 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
2282 const attackerRecord = event.attackerId != null ? this.directory.get(event.attackerId) : null;
2259 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
2283 const killerCharacterId = Number(attackerRecord?.characterId) || 0;
server/src/simulation/spawners.js +5 −0
@@ -98,6 +98,7 @@ export function collectSpawnRequests (world, now = Date.now())
98 98 level: config.level,
99 99 bounty: config.bounty,
100 100 aggressive: !!config.aggressive,
101 passive: !!config.passive,
101 102 spells: config.spells,
102 103 persistent,
103 104 sex: staff.sex,
@@ -146,6 +147,7 @@ export function collectSpawnRequests (world, now = Date.now())
146 147 aggressive: isHumanoidMob(config.mobTypeId) || config.townGuard
147 148 ? !!config.aggressive
148 149 : undefined,
150 passive: !!config.passive,
149 151 spells: config.spells,
150 152 persistent,
151 153 sex: config.sex,
@@ -308,6 +310,8 @@ export function mobComponents (request)
308 310 const aggressive = request.aggressive != null
309 311 ? !!request.aggressive
310 312 : !!def.aggressive;
313 // Passive only when Aggressive is off (config + resolved flag).
314 const passive = !aggressive && !!request.passive;
311 315 // Humanoid Aggressive flag forces bounty 0; wildlife can be aggressive and still pay kill bounty.
312 316 const bounty = request.aggressive === true
313 317 ? 0
@@ -320,6 +324,7 @@ export function mobComponents (request)
320 324 bounty,
321 325 level,
322 326 aggressive,
327 passive,
323 328 centralExchange: !!request.centralExchange,
324 329 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
325 330 stationTileX: null,
@@ -98,6 +98,7 @@ export function collectSpawnRequests (world, now = Date.now())
98 level: config.level,
98 level: config.level,
99 bounty: config.bounty,
99 bounty: config.bounty,
100 aggressive: !!config.aggressive,
100 aggressive: !!config.aggressive,
101 passive: !!config.passive,
101 spells: config.spells,
102 spells: config.spells,
102 persistent,
103 persistent,
103 sex: staff.sex,
104 sex: staff.sex,
@@ -146,6 +147,7 @@ export function collectSpawnRequests (world, now = Date.now())
146 aggressive: isHumanoidMob(config.mobTypeId) || config.townGuard
147 aggressive: isHumanoidMob(config.mobTypeId) || config.townGuard
147 ? !!config.aggressive
148 ? !!config.aggressive
148 : undefined,
149 : undefined,
150 passive: !!config.passive,
149 spells: config.spells,
151 spells: config.spells,
150 persistent,
152 persistent,
151 sex: config.sex,
153 sex: config.sex,
@@ -308,6 +310,8 @@ export function mobComponents (request)
308 const aggressive = request.aggressive != null
310 const aggressive = request.aggressive != null
309 ? !!request.aggressive
311 ? !!request.aggressive
310 : !!def.aggressive;
312 : !!def.aggressive;
313 // Passive only when Aggressive is off (config + resolved flag).
314 const passive = !aggressive && !!request.passive;
311 // Humanoid Aggressive flag forces bounty 0; wildlife can be aggressive and still pay kill bounty.
315 // Humanoid Aggressive flag forces bounty 0; wildlife can be aggressive and still pay kill bounty.
312 const bounty = request.aggressive === true
316 const bounty = request.aggressive === true
313 ? 0
317 ? 0
@@ -320,6 +324,7 @@ export function mobComponents (request)
320 bounty,
324 bounty,
321 level,
325 level,
322 aggressive,
326 aggressive,
327 passive,
323 centralExchange: !!request.centralExchange,
328 centralExchange: !!request.centralExchange,
324 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
329 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
325 stationTileX: null,
330 stationTileX: null,
server/src/simulation/workerWorld.js +18 −2
@@ -1578,7 +1578,15 @@ export class WorkerWorld
1578 1578 {
1579 1579 const dropped = this.#destroyEntity(entityId);
1580 1580 if (dropped)
1581 { events.push({ type: "entity-despawn", entityId }); }
1581 {
1582 events.push({
1583 type: "entity-despawn",
1584 entityId,
1585 tileX: dropped.tileX,
1586 tileY: dropped.tileY,
1587 dimensionId: dropped.dimensionId
1588 });
1589 }
1582 1590 }
1583 1591 const fairies = stepJadeiteFairies(this, now);
1584 1592 events.push(...(fairies.events ?? []));
@@ -1586,7 +1594,15 @@ export class WorkerWorld
1586 1594 {
1587 1595 const dropped = this.#destroyEntity(entityId);
1588 1596 if (dropped)
1589 { events.push({ type: "entity-despawn", entityId }); }
1597 {
1598 events.push({
1599 type: "entity-despawn",
1600 entityId,
1601 tileX: dropped.tileX,
1602 tileY: dropped.tileY,
1603 dimensionId: dropped.dimensionId
1604 });
1605 }
1590 1606 }
1591 1607 events.push(...stepJewelryTeleports(this, now).events);
1592 1608 stepFollow(this);
@@ -1578,7 +1578,15 @@ export class WorkerWorld
1578 {
1578 {
1579 const dropped = this.#destroyEntity(entityId);
1579 const dropped = this.#destroyEntity(entityId);
1580 if (dropped)
1580 if (dropped)
1581 { events.push({ type: "entity-despawn", entityId }); }
1581 {
1582 events.push({
1583 type: "entity-despawn",
1584 entityId,
1585 tileX: dropped.tileX,
1586 tileY: dropped.tileY,
1587 dimensionId: dropped.dimensionId
1588 });
1589 }
1582 }
1590 }
1583 const fairies = stepJadeiteFairies(this, now);
1591 const fairies = stepJadeiteFairies(this, now);
1584 events.push(...(fairies.events ?? []));
1592 events.push(...(fairies.events ?? []));
@@ -1586,7 +1594,15 @@ export class WorkerWorld
1586 {
1594 {
1587 const dropped = this.#destroyEntity(entityId);
1595 const dropped = this.#destroyEntity(entityId);
1588 if (dropped)
1596 if (dropped)
1589 { events.push({ type: "entity-despawn", entityId }); }
1597 {
1598 events.push({
1599 type: "entity-despawn",
1600 entityId,
1601 tileX: dropped.tileX,
1602 tileY: dropped.tileY,
1603 dimensionId: dropped.dimensionId
1604 });
1605 }
1590 }
1606 }
1591 events.push(...stepJewelryTeleports(this, now).events);
1607 events.push(...stepJewelryTeleports(this, now).events);
1592 stepFollow(this);
1608 stepFollow(this);
server/src/spells/summons.js +9 −2
@@ -162,7 +162,14 @@ export function shadeSummonComponents ({ tileX, tileY, level, ownerEntityId, exp
162 162 return components;
163 163 }
164 164
165 export function publicSummonDespawn (entityId)
165 export function publicSummonDespawn (entityId, view = null)
166 166 {
167 return { type: "entity-despawn", entityId };
167 const event = { type: "entity-despawn", entityId };
168 if (view)
169 {
170 event.tileX = view.tileX;
171 event.tileY = view.tileY;
172 event.dimensionId = view.dimensionId;
173 }
174 return event;
168 175 }
@@ -162,7 +162,14 @@ export function shadeSummonComponents ({ tileX, tileY, level, ownerEntityId, exp
162 return components;
162 return components;
163}
163}
164
164
165export function publicSummonDespawn (entityId)
165export function publicSummonDespawn (entityId, view = null)
166{
166{
167 return { type: "entity-despawn", entityId };
167 const event = { type: "entity-despawn", entityId };
168 if (view)
169 {
170 event.tileX = view.tileX;
171 event.tileY = view.tileY;
172 event.dimensionId = view.dimensionId;
173 }
174 return event;
168}
175}
server/tests/bounty.test.js +82 −3
@@ -5,22 +5,35 @@ import { ItemId } from "../../shared/definitions/items.js";
5 5 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6 6 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7 7 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8 import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
8 9
9 function placeBlock (worldDb, tileX, tileY, typeId)
10 function placeBlock (worldDb, tileX, tileY, typeId, dimensionId = OVERWORLD_ID)
10 11 {
11 12 const chunkX = Math.floor(tileX / 16);
12 13 const chunkY = Math.floor(tileY / 16);
14 const rev = worldDb.getActiveRevisionId();
15 const existing = worldDb.getChunkVersion(chunkX, chunkY, rev, dimensionId);
13 16 const data = createEmptyChunkData();
14 17 data.open = true;
18 if (existing?.data_blob)
19 {
20 const parsed = typeof existing.data_blob === "string"
21 ? JSON.parse(existing.data_blob)
22 : existing.data_blob;
23 data.grounds = parsed.grounds ?? data.grounds;
24 data.blocks = parsed.blocks ?? data.blocks;
25 data.open = parsed.open ?? true;
26 }
15 27 const localX = tileX - chunkX * 16;
16 28 const localY = tileY - chunkY * 16;
17 29 data.blocks[localY * 16 + localX] = { typeId, state: 0 };
18 30 worldDb.saveChunkVersion(
19 31 chunkX,
20 32 chunkY,
21 worldDb.getActiveRevisionId(),
33 rev,
22 34 true,
23 encodeChunkBlob(data)
35 encodeChunkBlob(data),
36 dimensionId
24 37 );
25 38 }
26 39
@@ -291,3 +304,69 @@ test("bounty decays one coin per calendar day", () =>
291 304 finally
292 305 { harness.close(); }
293 306 });
307
308
309 test("bounty payout letter prefers office in death dimension", () =>
310 {
311 const harness = makeSimulation({ workerCount: 1 });
312 const CAVE_ID = "bounty-cave";
313 try
314 {
315 const rev = harness.worldDb.getActiveRevisionId();
316 harness.worldDb.saveDimension(rev, {
317 dimensionId: CAVE_ID,
318 displayName: "Bounty Cave",
319 lightingMode: "alwaysLit",
320 seasonMode: "summer",
321 defaultGroundTypeId: 1
322 });
323 const cave = createEmptyChunkData();
324 cave.open = true;
325 harness.worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
326
327 // Overworld office farther from death tile than cave office
328 placeBlock(harness.worldDb, 2, 2, BlockType.bountyOffice, OVERWORLD_ID);
329 placeBlock(harness.worldDb, 1, 2, BlockType.bank, OVERWORLD_ID);
330 placeBlock(harness.worldDb, 9, 9, BlockType.bountyOffice, CAVE_ID);
331 placeBlock(harness.worldDb, 8, 9, BlockType.bank, CAVE_ID);
332 harness.simulation.reloadWorld();
333
334 const victim = makeCharacter(harness.stateDb, {
335 firstName: "Vic",
336 lastName: "DimVictim",
337 tileX: 10,
338 tileY: 9
339 });
340 const killer = makeCharacter(harness.stateDb, {
341 firstName: "Kill",
342 lastName: "DimKiller",
343 tileX: 11,
344 tileY: 9
345 });
346 harness.stateDb.addCharacterBounty(victim.character_id, 400);
347
348 const killerId = harness.simulation.spawnCharacter(2, killer);
349 const settled = harness.simulation.bounty.settleKill(
350 victim.character_id,
351 killerId,
352 10,
353 9,
354 CAVE_ID
355 );
356 assert.equal(settled?.paidCopper, 400);
357
358 const office = harness.simulation.courier.nearestBountyOffice(10, 9, CAVE_ID);
359 assert.equal(office.dimensionId, CAVE_ID);
360 assert.equal(office.tileX, 9);
361 assert.equal(office.tileY, 9);
362
363 const open = harness.stateDb.listActiveCourierTransits();
364 assert.ok(open.length >= 1);
365 const row = open[open.length - 1];
366 assert.equal(row.originDimensionId, CAVE_ID);
367 assert.equal(Math.floor(row.originX), 9);
368 assert.equal(Math.floor(row.originY), 9);
369 }
370 finally
371 { harness.close(); }
372 });
@@ -5,22 +5,35 @@ import { ItemId } from "../../shared/definitions/items.js";
5import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
5import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
8import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
8
9
9function placeBlock (worldDb, tileX, tileY, typeId)
10function placeBlock (worldDb, tileX, tileY, typeId, dimensionId = OVERWORLD_ID)
10{
11{
11 const chunkX = Math.floor(tileX / 16);
12 const chunkX = Math.floor(tileX / 16);
12 const chunkY = Math.floor(tileY / 16);
13 const chunkY = Math.floor(tileY / 16);
14 const rev = worldDb.getActiveRevisionId();
15 const existing = worldDb.getChunkVersion(chunkX, chunkY, rev, dimensionId);
13 const data = createEmptyChunkData();
16 const data = createEmptyChunkData();
14 data.open = true;
17 data.open = true;
18 if (existing?.data_blob)
19 {
20 const parsed = typeof existing.data_blob === "string"
21 ? JSON.parse(existing.data_blob)
22 : existing.data_blob;
23 data.grounds = parsed.grounds ?? data.grounds;
24 data.blocks = parsed.blocks ?? data.blocks;
25 data.open = parsed.open ?? true;
26 }
15 const localX = tileX - chunkX * 16;
27 const localX = tileX - chunkX * 16;
16 const localY = tileY - chunkY * 16;
28 const localY = tileY - chunkY * 16;
17 data.blocks[localY * 16 + localX] = { typeId, state: 0 };
29 data.blocks[localY * 16 + localX] = { typeId, state: 0 };
18 worldDb.saveChunkVersion(
30 worldDb.saveChunkVersion(
19 chunkX,
31 chunkX,
20 chunkY,
32 chunkY,
21 worldDb.getActiveRevisionId(),
33 rev,
22 true,
34 true,
23 encodeChunkBlob(data)
35 encodeChunkBlob(data),
36 dimensionId
24 );
37 );
25}
38}
26
39
@@ -291,3 +304,69 @@ test("bounty decays one coin per calendar day", () =>
291 finally
304 finally
292 { harness.close(); }
305 { harness.close(); }
293});
306});
307
308
309test("bounty payout letter prefers office in death dimension", () =>
310{
311 const harness = makeSimulation({ workerCount: 1 });
312 const CAVE_ID = "bounty-cave";
313 try
314 {
315 const rev = harness.worldDb.getActiveRevisionId();
316 harness.worldDb.saveDimension(rev, {
317 dimensionId: CAVE_ID,
318 displayName: "Bounty Cave",
319 lightingMode: "alwaysLit",
320 seasonMode: "summer",
321 defaultGroundTypeId: 1
322 });
323 const cave = createEmptyChunkData();
324 cave.open = true;
325 harness.worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
326
327 // Overworld office farther from death tile than cave office
328 placeBlock(harness.worldDb, 2, 2, BlockType.bountyOffice, OVERWORLD_ID);
329 placeBlock(harness.worldDb, 1, 2, BlockType.bank, OVERWORLD_ID);
330 placeBlock(harness.worldDb, 9, 9, BlockType.bountyOffice, CAVE_ID);
331 placeBlock(harness.worldDb, 8, 9, BlockType.bank, CAVE_ID);
332 harness.simulation.reloadWorld();
333
334 const victim = makeCharacter(harness.stateDb, {
335 firstName: "Vic",
336 lastName: "DimVictim",
337 tileX: 10,
338 tileY: 9
339 });
340 const killer = makeCharacter(harness.stateDb, {
341 firstName: "Kill",
342 lastName: "DimKiller",
343 tileX: 11,
344 tileY: 9
345 });
346 harness.stateDb.addCharacterBounty(victim.character_id, 400);
347
348 const killerId = harness.simulation.spawnCharacter(2, killer);
349 const settled = harness.simulation.bounty.settleKill(
350 victim.character_id,
351 killerId,
352 10,
353 9,
354 CAVE_ID
355 );
356 assert.equal(settled?.paidCopper, 400);
357
358 const office = harness.simulation.courier.nearestBountyOffice(10, 9, CAVE_ID);
359 assert.equal(office.dimensionId, CAVE_ID);
360 assert.equal(office.tileX, 9);
361 assert.equal(office.tileY, 9);
362
363 const open = harness.stateDb.listActiveCourierTransits();
364 assert.ok(open.length >= 1);
365 const row = open[open.length - 1];
366 assert.equal(row.originDimensionId, CAVE_ID);
367 assert.equal(Math.floor(row.originX), 9);
368 assert.equal(Math.floor(row.originY), 9);
369 }
370 finally
371 { harness.close(); }
372});
server/tests/combat-logout.test.js +14 −6
@@ -119,7 +119,7 @@ test("combat logout keeps the character until quiet timeout", () =>
119 119 { harness.close(); }
120 120 });
121 121
122 test("combat activity resets the combat-logout quiet timer", () =>
122 test("combat activity delays quiet expiry but hard-caps from disconnect", () =>
123 123 {
124 124 const harness = makeSimulation({ workerCount: 1 });
125 125 try
@@ -133,24 +133,32 @@ test("combat activity resets the combat-logout quiet timer", () =>
133 133 spawnerId: null
134 134 }));
135 135 engageAndLogout(harness, character, playerId, deerId);
136 const logout = harness.simulation.combatLogouts.get(character.character_id);
137 const startedAt = logout.startedAt;
136 138
139 // Fresh combat activity shortly before the quiet window would end.
137 140 harness.advance(COMBAT_LOGOUT_MS - 5_000);
138 141 for (let i = 0; i < 3; i++)
139 142 { harness.simulation.step(); }
140 143 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
141
142 144 const track = harness.simulation.combatTracking.get(character.character_id);
143 145 track.lastCombatActivityAt = harness.now();
144 const logout = harness.simulation.combatLogouts.get(character.character_id);
145 logout.startedAt = harness.now();
146 146
147 harness.advance(COMBAT_LOGOUT_MS - 10_000);
147 // Still within the hard cap from original disconnect → stay.
148 harness.advance(2_000);
148 149 for (let i = 0; i < 3; i++)
149 150 { harness.simulation.step(); }
150 151 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
152 assert.equal(logout.startedAt, startedAt);
151 153
152 clearCombatAndExpireQuiet(harness, character.character_id, playerId);
154 // Past hard cap from disconnect even with fresh activity → despawn.
155 harness.advance(COMBAT_LOGOUT_MS);
156 track.lastCombatActivityAt = harness.now();
157 // Combat-logout is checked about once per second of sim ticks.
158 for (let i = 0; i < 60; i++)
159 { harness.simulation.step(); }
153 160 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
161 assert.equal(harness.simulation.isCombatLogout(character.character_id), false);
154 162 }
155 163 finally
156 164 { harness.close(); }
@@ -119,7 +119,7 @@ test("combat logout keeps the character until quiet timeout", () =>
119 { harness.close(); }
119 { harness.close(); }
120});
120});
121
121
122test("combat activity resets the combat-logout quiet timer", () =>
122test("combat activity delays quiet expiry but hard-caps from disconnect", () =>
123{
123{
124 const harness = makeSimulation({ workerCount: 1 });
124 const harness = makeSimulation({ workerCount: 1 });
125 try
125 try
@@ -133,24 +133,32 @@ test("combat activity resets the combat-logout quiet timer", () =>
133 spawnerId: null
133 spawnerId: null
134 }));
134 }));
135 engageAndLogout(harness, character, playerId, deerId);
135 engageAndLogout(harness, character, playerId, deerId);
136 const logout = harness.simulation.combatLogouts.get(character.character_id);
137 const startedAt = logout.startedAt;
136
138
139 // Fresh combat activity shortly before the quiet window would end.
137 harness.advance(COMBAT_LOGOUT_MS - 5_000);
140 harness.advance(COMBAT_LOGOUT_MS - 5_000);
138 for (let i = 0; i < 3; i++)
141 for (let i = 0; i < 3; i++)
139 { harness.simulation.step(); }
142 { harness.simulation.step(); }
140 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
143 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
141
142 const track = harness.simulation.combatTracking.get(character.character_id);
144 const track = harness.simulation.combatTracking.get(character.character_id);
143 track.lastCombatActivityAt = harness.now();
145 track.lastCombatActivityAt = harness.now();
144 const logout = harness.simulation.combatLogouts.get(character.character_id);
145 logout.startedAt = harness.now();
146
146
147 harness.advance(COMBAT_LOGOUT_MS - 10_000);
147 // Still within the hard cap from original disconnect → stay.
148 harness.advance(2_000);
148 for (let i = 0; i < 3; i++)
149 for (let i = 0; i < 3; i++)
149 { harness.simulation.step(); }
150 { harness.simulation.step(); }
150 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
151 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), true);
152 assert.equal(logout.startedAt, startedAt);
151
153
152 clearCombatAndExpireQuiet(harness, character.character_id, playerId);
154 // Past hard cap from disconnect even with fresh activity → despawn.
155 harness.advance(COMBAT_LOGOUT_MS);
156 track.lastCombatActivityAt = harness.now();
157 // Combat-logout is checked about once per second of sim ticks.
158 for (let i = 0; i < 60; i++)
159 { harness.simulation.step(); }
153 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
160 assert.equal(harness.simulation.isCharacterInWorld(character.character_id), false);
161 assert.equal(harness.simulation.isCombatLogout(character.character_id), false);
154 }
162 }
155 finally
163 finally
156 { harness.close(); }
164 { harness.close(); }
server/tests/combat.test.js +52 −0
@@ -408,6 +408,58 @@ test("attack engages the attacker; target retaliates on first swing", () =>
408 408 { harness.close(); }
409 409 });
410 410
411 test("passive spawner mob takes hits but does not retaliate", () =>
412 {
413 const harness = makeSimulation({ workerCount: 1 });
414 try
415 {
416 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
417 const playerId = harness.simulation.spawnCharacter(1, character);
418 const npcId = harness.simulation.spawnEntity(mobComponents({
419 tileX: 9,
420 tileY: 8,
421 mobTypeId: MobId.humanoid,
422 spawnerId: "passive-npc",
423 originTileX: 9,
424 originTileY: 8,
425 wanderRangeTiles: 1,
426 level: 1,
427 aggressive: false,
428 passive: true,
429 displayName: "Pacifist",
430 sex: "male"
431 }));
432
433 harness.simulation.enqueue(1, {
434 type: "attack",
435 characterId: character.character_id,
436 targetEntityId: npcId
437 });
438 harness.simulation.step();
439 assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, npcId);
440
441 let swung = false;
442 for (let i = 0; i < 80; i++)
443 {
444 harness.advance(50);
445 const events = harness.simulation.step().events;
446 if (events.some((event) => event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss"))
447 {
448 swung = true;
449 break;
450 }
451 }
452 assert.ok(swung, "expected a melee swing against the passive npc");
453 assert.equal(
454 componentsOf(harness.simulation, npcId).combat?.targetEntityId ?? null,
455 null,
456 "passive npc must not retaliate"
457 );
458 }
459 finally
460 { harness.close(); }
461 });
462
411 463 test("melee swing only resolves at Chebyshev distance 1", () =>
412 464 {
413 465 const harness = makeSimulation({ workerCount: 1 });
@@ -408,6 +408,58 @@ test("attack engages the attacker; target retaliates on first swing", () =>
408 { harness.close(); }
408 { harness.close(); }
409});
409});
410
410
411test("passive spawner mob takes hits but does not retaliate", () =>
412{
413 const harness = makeSimulation({ workerCount: 1 });
414 try
415 {
416 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
417 const playerId = harness.simulation.spawnCharacter(1, character);
418 const npcId = harness.simulation.spawnEntity(mobComponents({
419 tileX: 9,
420 tileY: 8,
421 mobTypeId: MobId.humanoid,
422 spawnerId: "passive-npc",
423 originTileX: 9,
424 originTileY: 8,
425 wanderRangeTiles: 1,
426 level: 1,
427 aggressive: false,
428 passive: true,
429 displayName: "Pacifist",
430 sex: "male"
431 }));
432
433 harness.simulation.enqueue(1, {
434 type: "attack",
435 characterId: character.character_id,
436 targetEntityId: npcId
437 });
438 harness.simulation.step();
439 assert.equal(componentsOf(harness.simulation, playerId).combat.targetEntityId, npcId);
440
441 let swung = false;
442 for (let i = 0; i < 80; i++)
443 {
444 harness.advance(50);
445 const events = harness.simulation.step().events;
446 if (events.some((event) => event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss"))
447 {
448 swung = true;
449 break;
450 }
451 }
452 assert.ok(swung, "expected a melee swing against the passive npc");
453 assert.equal(
454 componentsOf(harness.simulation, npcId).combat?.targetEntityId ?? null,
455 null,
456 "passive npc must not retaliate"
457 );
458 }
459 finally
460 { harness.close(); }
461});
462
411test("melee swing only resolves at Chebyshev distance 1", () =>
463test("melee swing only resolves at Chebyshev distance 1", () =>
412{
464{
413 const harness = makeSimulation({ workerCount: 1 });
465 const harness = makeSimulation({ workerCount: 1 });
server/tests/courier.test.js +270 −8
@@ -1,13 +1,23 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
3 6 import { BlockType } from "../../shared/definitions/tiles.js";
4 7 import { ItemId } from "../../shared/definitions/items.js";
5 8 import { pigeonSpeedAtProgress, advanceCourierFlight } from "../../shared/courier/flight.js";
9 import { ensureCourierLegs } from "../../shared/courier/doorwayGraph.js";
10 import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
6 11 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
12 import { WorldDatabase } from "../src/persistence/worldDb.js";
13 import { StateDatabase } from "../src/persistence/stateDb.js";
14 import { Simulation } from "../src/simulation/simulation.js";
7 15 import {
8 16 makeCharacter,
9 17 makeSimulation,
10 stepTimes
18 stepTimes,
19 writeOpenChunk,
20 openChunkStrip
11 21 } from "./helpers/simulationHarness.js";
12 22
13 23 test("pigeon flight uses takeoff, cruise, then landing speeds", () =>
@@ -54,6 +64,103 @@ function placeBank (worldDb, tileX, tileY)
54 64 );
55 65 }
56 66
67 function countItem (slots, itemId)
68 {
69 return (slots ?? [])
70 .filter((slot) => slot?.itemId === itemId)
71 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
72 }
73
74 const CAVE_ID = "courier-cave";
75
76 function placeBlock (worldDb, tileX, tileY, block, dimensionId = OVERWORLD_ID)
77 {
78 const chunkX = Math.floor(tileX / 16);
79 const chunkY = Math.floor(tileY / 16);
80 const rev = worldDb.getActiveRevisionId();
81 const existing = worldDb.getChunkVersion(chunkX, chunkY, rev, dimensionId);
82 const chunkData = createEmptyChunkData();
83 chunkData.open = true;
84 if (existing?.data_blob)
85 {
86 const parsed = typeof existing.data_blob === "string"
87 ? JSON.parse(existing.data_blob)
88 : existing.data_blob;
89 chunkData.grounds = parsed.grounds ?? chunkData.grounds;
90 chunkData.blocks = parsed.blocks ?? chunkData.blocks;
91 chunkData.open = parsed.open ?? true;
92 }
93 const localX = tileX - chunkX * 16;
94 const localY = tileY - chunkY * 16;
95 chunkData.blocks[localY * 16 + localX] = block;
96 worldDb.saveChunkVersion(
97 chunkX,
98 chunkY,
99 rev,
100 true,
101 encodeChunkBlob(chunkData),
102 dimensionId
103 );
104 }
105
106 function placeDoorway (worldDb, tileX, tileY, targetDimensionId, targetTileX, targetTileY, dimensionId = OVERWORLD_ID)
107 {
108 placeBlock(worldDb, tileX, tileY, {
109 typeId: BlockType.doorway,
110 state: "door",
111 config: {
112 targetDimensionId,
113 tileX: targetTileX,
114 tileY: targetTileY
115 }
116 }, dimensionId);
117 }
118
119 function placeBankDim (worldDb, tileX, tileY, dimensionId = OVERWORLD_ID)
120 {
121 placeBlock(worldDb, tileX, tileY, { typeId: BlockType.bank, state: 0 }, dimensionId);
122 }
123
124 function makeDimCourierHarness ()
125 {
126 const dir = mkdtempSync(join(tmpdir(), "mmo-courier-dim-"));
127 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
128 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
129 openChunkStrip(worldDb, 2);
130 const rev = worldDb.getActiveRevisionId();
131 worldDb.saveDimension(rev, {
132 dimensionId: CAVE_ID,
133 displayName: "Courier Cave",
134 lightingMode: DimensionLightingMode.alwaysLit,
135 seasonMode: DimensionSeasonMode.summer,
136 defaultGroundTypeId: 1
137 });
138 const cave = createEmptyChunkData();
139 cave.open = true;
140 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
141 writeOpenChunk(worldDb, 0, 0);
142 writeOpenChunk(worldDb, 1, 0);
143 let now = 1_000;
144 const simulation = new Simulation(worldDb, stateDb, {
145 workerCount: 1,
146 workerMode: "inprocess",
147 now: () => now
148 });
149 return {
150 simulation,
151 worldDb,
152 stateDb,
153 advance (ms)
154 { now += ms; },
155 close ()
156 {
157 simulation.forceUnloadAll();
158 worldDb.close();
159 stateDb.close();
160 }
161 };
162 }
163
57 164 test("pigeon to bank deposits coin stacks into the sender vault", () =>
58 165 {
59 166 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -92,13 +199,6 @@ test("pigeon to bank deposits coin stacks into the sender vault", () =>
92 199 { harness.close(); }
93 200 });
94 201
95 function countItem (slots, itemId)
96 {
97 return (slots ?? [])
98 .filter((slot) => slot?.itemId === itemId)
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100 }
101
102 202 test("pigeon to offline player flies to the bank and credits the recipient vault", () =>
103 203 {
104 204 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -186,6 +286,7 @@ test("logging in after offline bank deposits sends a bank resting notice by pige
186 286 finally
187 287 { harness.close(); }
188 288 });
289
189 290 test("pigeon delivers an item to an online player inventory", () =>
190 291 {
191 292 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -321,3 +422,164 @@ test("pigeon to bank redeems a filled cheque into reserved goods", () =>
321 422 finally
322 423 { harness.close(); }
323 424 });
425
426 test("same-dimension pigeon still delivers with multi-leg schema", () =>
427 {
428 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
429 try
430 {
431 placeBank(harness.worldDb, 20, 8);
432 harness.simulation.reloadWorld();
433 harness.simulation.applySettings({
434 pigeonTakeoffTilesPerSec: 40,
435 pigeonCruiseTilesPerSec: 40,
436 pigeonLandingTilesPerSec: 40,
437 simulationTickHz: 20
438 });
439 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
440 const entityId = harness.simulation.spawnCharacter(1, character);
441 const bag = harness.simulation.bagOf(entityId);
442 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
443 const result = harness.simulation.dispatchPigeon({
444 characterId: character.character_id,
445 destination: { kind: "bank" },
446 cargo: { kind: "item", slotIndex: coinSlot, quantity: 3 }
447 });
448 assert.equal(result.transit.originDimensionId, OVERWORLD_ID);
449 assert.equal(result.transit.destDimensionId, OVERWORLD_ID);
450 assert.ok(Array.isArray(result.transit.legs));
451 assert.equal(result.transit.legs.length, 1);
452 assert.equal(result.transit.legs[0].kind, "fly");
453 stepTimes(harness.simulation, 80);
454 const after = harness.stateDb.getBag(character.character_id);
455 assert.equal(countItem(after.vault, ItemId.coins), 3);
456 }
457 finally
458 { harness.close(); }
459 });
460
461 test("cross-dimension pigeon flies through doorway portals", () =>
462 {
463 const harness = makeDimCourierHarness();
464 try
465 {
466 placeBankDim(harness.worldDb, 20, 8, OVERWORLD_ID);
467 placeDoorway(harness.worldDb, 4, 8, OVERWORLD_ID, 8, 8, CAVE_ID);
468 harness.simulation.reloadWorld();
469 harness.simulation.applySettings({
470 pigeonTakeoffTilesPerSec: 40,
471 pigeonCruiseTilesPerSec: 40,
472 pigeonLandingTilesPerSec: 40,
473 simulationTickHz: 20
474 });
475 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
476 harness.stateDb.saveCharacterPosition(character.character_id, 2, 8, "walk", CAVE_ID);
477 const entityId = harness.simulation.spawnCharacter(1, character);
478 assert.equal(harness.simulation.positionOf(entityId).dimensionId, CAVE_ID);
479 const bag = harness.simulation.bagOf(entityId);
480 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
481 const result = harness.simulation.dispatchPigeon({
482 characterId: character.character_id,
483 destination: { kind: "bank" },
484 cargo: { kind: "item", slotIndex: coinSlot, quantity: 2 }
485 });
486 assert.equal(result.transit.originDimensionId, CAVE_ID);
487 assert.equal(result.transit.destDimensionId, OVERWORLD_ID);
488 assert.ok(result.transit.legs.some((leg) => leg.kind === "portal"));
489 assert.ok(result.transit.legs.some((leg) => leg.kind === "fly"));
490 stepTimes(harness.simulation, 200);
491 const after = harness.stateDb.getBag(character.character_id);
492 assert.equal(countItem(after.vault, ItemId.coins), 2);
493 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
494 }
495 finally
496 { harness.close(); }
497 });
498
499 test("cross-dimension pigeon without doorway path uses fade/abstract fallback", () =>
500 {
501 const harness = makeDimCourierHarness();
502 try
503 {
504 placeBankDim(harness.worldDb, 20, 8, OVERWORLD_ID);
505 harness.simulation.reloadWorld();
506 harness.simulation.applySettings({
507 pigeonTakeoffTilesPerSec: 40,
508 pigeonCruiseTilesPerSec: 40,
509 pigeonLandingTilesPerSec: 40,
510 simulationTickHz: 20
511 });
512 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
513 harness.stateDb.saveCharacterPosition(character.character_id, 2, 8, "walk", CAVE_ID);
514 const entityId = harness.simulation.spawnCharacter(1, character);
515 const bag = harness.simulation.bagOf(entityId);
516 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
517 const result = harness.simulation.dispatchPigeon({
518 characterId: character.character_id,
519 destination: { kind: "bank" },
520 cargo: { kind: "item", slotIndex: coinSlot, quantity: 1 }
521 });
522 assert.ok(result.transit.legs.some((leg) => leg.kind === "abstract"));
523 assert.ok(!result.transit.legs.some((leg) => leg.kind === "portal"));
524 stepTimes(harness.simulation, 300);
525 const after = harness.stateDb.getBag(character.character_id);
526 assert.equal(countItem(after.vault, ItemId.coins), 1);
527 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
528 }
529 finally
530 { harness.close(); }
531 });
532
533 test("legacy courier_transits rows migrate to overworld single-fly legs", () =>
534 {
535 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
536 try
537 {
538 placeBank(harness.worldDb, 20, 8);
539 harness.simulation.reloadWorld();
540 harness.simulation.applySettings({
541 pigeonTakeoffTilesPerSec: 40,
542 pigeonCruiseTilesPerSec: 40,
543 pigeonLandingTilesPerSec: 40,
544 simulationTickHz: 20
545 });
546 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
547 harness.simulation.spawnCharacter(1, character);
548 const now = Date.now();
549 harness.stateDb.db.prepare(`
550 INSERT INTO courier_transits (
551 sender_character_id, destination_kind, destination_character_id, cargo_blob,
552 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
553 vault_character_id
554 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
555 `).run(
556 character.character_id,
557 "bank",
558 null,
559 JSON.stringify({ kind: "item", stack: { itemId: ItemId.coins, quantity: 4 } }),
560 2.5,
561 8.5,
562 20.5,
563 8.5,
564 0,
565 "in_transit",
566 null,
567 now,
568 now,
569 character.character_id
570 );
571 const listed = harness.stateDb.listActiveCourierTransits();
572 assert.equal(listed.length, 1);
573 assert.equal(listed[0].originDimensionId, OVERWORLD_ID);
574 assert.equal(listed[0].destDimensionId, OVERWORLD_ID);
575 assert.equal(listed[0].legs, null);
576 ensureCourierLegs(listed[0]);
577 assert.equal(listed[0].legs.length, 1);
578 stepTimes(harness.simulation, 80);
579 const after = harness.stateDb.getBag(character.character_id);
580 assert.equal(countItem(after.vault, ItemId.coins), 4);
581 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
582 }
583 finally
584 { harness.close(); }
585 });
@@ -1,13 +1,23 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
3import { BlockType } from "../../shared/definitions/tiles.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
7import { ItemId } from "../../shared/definitions/items.js";
5import { pigeonSpeedAtProgress, advanceCourierFlight } from "../../shared/courier/flight.js";
8import { pigeonSpeedAtProgress, advanceCourierFlight } from "../../shared/courier/flight.js";
9import { ensureCourierLegs } from "../../shared/courier/doorwayGraph.js";
10import { OVERWORLD_ID, DimensionLightingMode, DimensionSeasonMode } from "../../shared/world/dimensions.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
11import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
12import { WorldDatabase } from "../src/persistence/worldDb.js";
13import { StateDatabase } from "../src/persistence/stateDb.js";
14import { Simulation } from "../src/simulation/simulation.js";
7import {
15import {
8 makeCharacter,
16 makeCharacter,
9 makeSimulation,
17 makeSimulation,
10 stepTimes
18 stepTimes,
19 writeOpenChunk,
20 openChunkStrip
11} from "./helpers/simulationHarness.js";
21} from "./helpers/simulationHarness.js";
12
22
13test("pigeon flight uses takeoff, cruise, then landing speeds", () =>
23test("pigeon flight uses takeoff, cruise, then landing speeds", () =>
@@ -54,6 +64,103 @@ function placeBank (worldDb, tileX, tileY)
54 );
64 );
55}
65}
56
66
67function countItem (slots, itemId)
68{
69 return (slots ?? [])
70 .filter((slot) => slot?.itemId === itemId)
71 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
72}
73
74const CAVE_ID = "courier-cave";
75
76function placeBlock (worldDb, tileX, tileY, block, dimensionId = OVERWORLD_ID)
77{
78 const chunkX = Math.floor(tileX / 16);
79 const chunkY = Math.floor(tileY / 16);
80 const rev = worldDb.getActiveRevisionId();
81 const existing = worldDb.getChunkVersion(chunkX, chunkY, rev, dimensionId);
82 const chunkData = createEmptyChunkData();
83 chunkData.open = true;
84 if (existing?.data_blob)
85 {
86 const parsed = typeof existing.data_blob === "string"
87 ? JSON.parse(existing.data_blob)
88 : existing.data_blob;
89 chunkData.grounds = parsed.grounds ?? chunkData.grounds;
90 chunkData.blocks = parsed.blocks ?? chunkData.blocks;
91 chunkData.open = parsed.open ?? true;
92 }
93 const localX = tileX - chunkX * 16;
94 const localY = tileY - chunkY * 16;
95 chunkData.blocks[localY * 16 + localX] = block;
96 worldDb.saveChunkVersion(
97 chunkX,
98 chunkY,
99 rev,
100 true,
101 encodeChunkBlob(chunkData),
102 dimensionId
103 );
104}
105
106function placeDoorway (worldDb, tileX, tileY, targetDimensionId, targetTileX, targetTileY, dimensionId = OVERWORLD_ID)
107{
108 placeBlock(worldDb, tileX, tileY, {
109 typeId: BlockType.doorway,
110 state: "door",
111 config: {
112 targetDimensionId,
113 tileX: targetTileX,
114 tileY: targetTileY
115 }
116 }, dimensionId);
117}
118
119function placeBankDim (worldDb, tileX, tileY, dimensionId = OVERWORLD_ID)
120{
121 placeBlock(worldDb, tileX, tileY, { typeId: BlockType.bank, state: 0 }, dimensionId);
122}
123
124function makeDimCourierHarness ()
125{
126 const dir = mkdtempSync(join(tmpdir(), "mmo-courier-dim-"));
127 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
128 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
129 openChunkStrip(worldDb, 2);
130 const rev = worldDb.getActiveRevisionId();
131 worldDb.saveDimension(rev, {
132 dimensionId: CAVE_ID,
133 displayName: "Courier Cave",
134 lightingMode: DimensionLightingMode.alwaysLit,
135 seasonMode: DimensionSeasonMode.summer,
136 defaultGroundTypeId: 1
137 });
138 const cave = createEmptyChunkData();
139 cave.open = true;
140 worldDb.saveChunkVersion(0, 0, rev, true, encodeChunkBlob(cave), CAVE_ID);
141 writeOpenChunk(worldDb, 0, 0);
142 writeOpenChunk(worldDb, 1, 0);
143 let now = 1_000;
144 const simulation = new Simulation(worldDb, stateDb, {
145 workerCount: 1,
146 workerMode: "inprocess",
147 now: () => now
148 });
149 return {
150 simulation,
151 worldDb,
152 stateDb,
153 advance (ms)
154 { now += ms; },
155 close ()
156 {
157 simulation.forceUnloadAll();
158 worldDb.close();
159 stateDb.close();
160 }
161 };
162}
163
57test("pigeon to bank deposits coin stacks into the sender vault", () =>
164test("pigeon to bank deposits coin stacks into the sender vault", () =>
58{
165{
59 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
166 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -92,13 +199,6 @@ test("pigeon to bank deposits coin stacks into the sender vault", () =>
92 { harness.close(); }
199 { harness.close(); }
93});
200});
94
201
95function countItem (slots, itemId)
96{
97 return (slots ?? [])
98 .filter((slot) => slot?.itemId === itemId)
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100}
101
102test("pigeon to offline player flies to the bank and credits the recipient vault", () =>
202test("pigeon to offline player flies to the bank and credits the recipient vault", () =>
103{
203{
104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
204 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -186,6 +286,7 @@ test("logging in after offline bank deposits sends a bank resting notice by pige
186 finally
286 finally
187 { harness.close(); }
287 { harness.close(); }
188});
288});
289
189test("pigeon delivers an item to an online player inventory", () =>
290test("pigeon delivers an item to an online player inventory", () =>
190{
291{
191 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
292 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -321,3 +422,164 @@ test("pigeon to bank redeems a filled cheque into reserved goods", () =>
321 finally
422 finally
322 { harness.close(); }
423 { harness.close(); }
323});
424});
425
426test("same-dimension pigeon still delivers with multi-leg schema", () =>
427{
428 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
429 try
430 {
431 placeBank(harness.worldDb, 20, 8);
432 harness.simulation.reloadWorld();
433 harness.simulation.applySettings({
434 pigeonTakeoffTilesPerSec: 40,
435 pigeonCruiseTilesPerSec: 40,
436 pigeonLandingTilesPerSec: 40,
437 simulationTickHz: 20
438 });
439 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
440 const entityId = harness.simulation.spawnCharacter(1, character);
441 const bag = harness.simulation.bagOf(entityId);
442 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
443 const result = harness.simulation.dispatchPigeon({
444 characterId: character.character_id,
445 destination: { kind: "bank" },
446 cargo: { kind: "item", slotIndex: coinSlot, quantity: 3 }
447 });
448 assert.equal(result.transit.originDimensionId, OVERWORLD_ID);
449 assert.equal(result.transit.destDimensionId, OVERWORLD_ID);
450 assert.ok(Array.isArray(result.transit.legs));
451 assert.equal(result.transit.legs.length, 1);
452 assert.equal(result.transit.legs[0].kind, "fly");
453 stepTimes(harness.simulation, 80);
454 const after = harness.stateDb.getBag(character.character_id);
455 assert.equal(countItem(after.vault, ItemId.coins), 3);
456 }
457 finally
458 { harness.close(); }
459});
460
461test("cross-dimension pigeon flies through doorway portals", () =>
462{
463 const harness = makeDimCourierHarness();
464 try
465 {
466 placeBankDim(harness.worldDb, 20, 8, OVERWORLD_ID);
467 placeDoorway(harness.worldDb, 4, 8, OVERWORLD_ID, 8, 8, CAVE_ID);
468 harness.simulation.reloadWorld();
469 harness.simulation.applySettings({
470 pigeonTakeoffTilesPerSec: 40,
471 pigeonCruiseTilesPerSec: 40,
472 pigeonLandingTilesPerSec: 40,
473 simulationTickHz: 20
474 });
475 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
476 harness.stateDb.saveCharacterPosition(character.character_id, 2, 8, "walk", CAVE_ID);
477 const entityId = harness.simulation.spawnCharacter(1, character);
478 assert.equal(harness.simulation.positionOf(entityId).dimensionId, CAVE_ID);
479 const bag = harness.simulation.bagOf(entityId);
480 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
481 const result = harness.simulation.dispatchPigeon({
482 characterId: character.character_id,
483 destination: { kind: "bank" },
484 cargo: { kind: "item", slotIndex: coinSlot, quantity: 2 }
485 });
486 assert.equal(result.transit.originDimensionId, CAVE_ID);
487 assert.equal(result.transit.destDimensionId, OVERWORLD_ID);
488 assert.ok(result.transit.legs.some((leg) => leg.kind === "portal"));
489 assert.ok(result.transit.legs.some((leg) => leg.kind === "fly"));
490 stepTimes(harness.simulation, 200);
491 const after = harness.stateDb.getBag(character.character_id);
492 assert.equal(countItem(after.vault, ItemId.coins), 2);
493 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
494 }
495 finally
496 { harness.close(); }
497});
498
499test("cross-dimension pigeon without doorway path uses fade/abstract fallback", () =>
500{
501 const harness = makeDimCourierHarness();
502 try
503 {
504 placeBankDim(harness.worldDb, 20, 8, OVERWORLD_ID);
505 harness.simulation.reloadWorld();
506 harness.simulation.applySettings({
507 pigeonTakeoffTilesPerSec: 40,
508 pigeonCruiseTilesPerSec: 40,
509 pigeonLandingTilesPerSec: 40,
510 simulationTickHz: 20
511 });
512 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
513 harness.stateDb.saveCharacterPosition(character.character_id, 2, 8, "walk", CAVE_ID);
514 const entityId = harness.simulation.spawnCharacter(1, character);
515 const bag = harness.simulation.bagOf(entityId);
516 const coinSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
517 const result = harness.simulation.dispatchPigeon({
518 characterId: character.character_id,
519 destination: { kind: "bank" },
520 cargo: { kind: "item", slotIndex: coinSlot, quantity: 1 }
521 });
522 assert.ok(result.transit.legs.some((leg) => leg.kind === "abstract"));
523 assert.ok(!result.transit.legs.some((leg) => leg.kind === "portal"));
524 stepTimes(harness.simulation, 300);
525 const after = harness.stateDb.getBag(character.character_id);
526 assert.equal(countItem(after.vault, ItemId.coins), 1);
527 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
528 }
529 finally
530 { harness.close(); }
531});
532
533test("legacy courier_transits rows migrate to overworld single-fly legs", () =>
534{
535 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
536 try
537 {
538 placeBank(harness.worldDb, 20, 8);
539 harness.simulation.reloadWorld();
540 harness.simulation.applySettings({
541 pigeonTakeoffTilesPerSec: 40,
542 pigeonCruiseTilesPerSec: 40,
543 pigeonLandingTilesPerSec: 40,
544 simulationTickHz: 20
545 });
546 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
547 harness.simulation.spawnCharacter(1, character);
548 const now = Date.now();
549 harness.stateDb.db.prepare(`
550 INSERT INTO courier_transits (
551 sender_character_id, destination_kind, destination_character_id, cargo_blob,
552 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
553 vault_character_id
554 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
555 `).run(
556 character.character_id,
557 "bank",
558 null,
559 JSON.stringify({ kind: "item", stack: { itemId: ItemId.coins, quantity: 4 } }),
560 2.5,
561 8.5,
562 20.5,
563 8.5,
564 0,
565 "in_transit",
566 null,
567 now,
568 now,
569 character.character_id
570 );
571 const listed = harness.stateDb.listActiveCourierTransits();
572 assert.equal(listed.length, 1);
573 assert.equal(listed[0].originDimensionId, OVERWORLD_ID);
574 assert.equal(listed[0].destDimensionId, OVERWORLD_ID);
575 assert.equal(listed[0].legs, null);
576 ensureCourierLegs(listed[0]);
577 assert.equal(listed[0].legs.length, 1);
578 stepTimes(harness.simulation, 80);
579 const after = harness.stateDb.getBag(character.character_id);
580 assert.equal(countItem(after.vault, ItemId.coins), 4);
581 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
582 }
583 finally
584 { harness.close(); }
585});
server/tests/death.test.js +4 −2
@@ -391,11 +391,13 @@ test("mob kill entity-despawn is marked as combat death", () =>
391 391 const health = worker.world.ecs.get(handle, Component.health);
392 392 health.current = 1;
393 393 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
394 assert.ok(events.some((event) =>
394 const despawn = events.find((event) =>
395 395 event.type === "entity-despawn"
396 396 && event.entityId === ratId
397 397 && event.cause === "death"
398 ));
398 );
399 assert.ok(despawn);
400 assert.ok(despawn.dimensionId);
399 401 }
400 402 finally
401 403 { harness.close(); }
@@ -391,11 +391,13 @@ test("mob kill entity-despawn is marked as combat death", () =>
391 const health = worker.world.ecs.get(handle, Component.health);
391 const health = worker.world.ecs.get(handle, Component.health);
392 health.current = 1;
392 health.current = 1;
393 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
393 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
394 assert.ok(events.some((event) =>
394 const despawn = events.find((event) =>
395 event.type === "entity-despawn"
395 event.type === "entity-despawn"
396 && event.entityId === ratId
396 && event.entityId === ratId
397 && event.cause === "death"
397 && event.cause === "death"
398 ));
398 );
399 assert.ok(despawn);
400 assert.ok(despawn.dimensionId);
399 }
401 }
400 finally
402 finally
401 { harness.close(); }
403 { harness.close(); }
server/tests/dimension-interactions.test.js +122 −1
@@ -12,9 +12,12 @@ import { StateDatabase } from "../src/persistence/stateDb.js";
12 12 import { Simulation } from "../src/simulation/simulation.js";
13 13 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14 14 import { mobComponents } from "../src/simulation/spawners.js";
15 import { engageTarget, ensureMobCombat, stepCombat, stepAggression } from "../src/combat/service.js";
15 import { engageTarget, ensureMobCombat, stepCombat, stepAggression, applyDamageAndKill } from "../src/combat/service.js";
16 16 import { Component } from "../src/ecs/components.js";
17 import { eventInterestKeys } from "../src/gateway/eventInterest.js";
18 import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
17 19 import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
20 import { normalizeQuestDef } from "../../shared/quests/normalize.js";
18 21
19 22 const CAVE_ID = "test-cave";
20 23
@@ -147,3 +150,121 @@ test("melee combat ticks in a non-overworld dimension", () =>
147 150 finally
148 151 { harness.close(); }
149 152 });
153
154 test("mob kill entity-despawn carries cave dimensionId for interest", () =>
155 {
156 const harness = makeCaveHarness();
157 try
158 {
159 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
160 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
161 const playerId = harness.simulation.spawnCharacter(1, character);
162 const ratId = harness.simulation.spawnEntity(mobComponents({
163 tileX: 8,
164 tileY: 9,
165 mobTypeId: MobId.rat,
166 spawnerId: null,
167 dimensionId: CAVE_ID
168 }));
169 const worker = workerOf(harness.simulation, ratId);
170 const handle = worker.world.ecs.handleOf(ratId);
171 worker.world.ecs.get(handle, Component.health).current = 1;
172 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
173 const despawn = events.find((event) =>
174 event.type === "entity-despawn" && event.entityId === ratId && event.cause === "death"
175 );
176 assert.ok(despawn, "expected combat death despawn");
177 assert.equal(despawn.dimensionId, CAVE_ID);
178 // Entity is already gone — interest must not fall back to overworld.
179 const keys = eventInterestKeys(despawn, () => null);
180 assert.equal(keys.dimensionId, CAVE_ID);
181 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(9), CAVE_ID));
182 assert.notEqual(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(9), OVERWORLD_ID));
183 }
184 finally
185 { harness.close(); }
186 });
187
188 test("cave rat kill advances killCount quest progress", () =>
189 {
190 const harness = makeCaveHarness();
191 try
192 {
193 const quest = normalizeQuestDef({
194 questId: "kill-rats-cave",
195 title: "Kill Rats",
196 steps: [{
197 stepId: "step-1",
198 title: "Hunt",
199 objectives: [{
200 objectiveId: "obj-1",
201 text: "Kill 5 rats",
202 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 5 } }] }
203 }],
204 completionJournalText: "Done."
205 }]
206 });
207 const pending = harness.worldDb.ensurePendingRevision(1);
208 harness.worldDb.saveQuestDef(pending, quest);
209 harness.worldDb.promotePendingRevision();
210 harness.simulation.questContent.reload();
211
212 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
213 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
214 const playerId = harness.simulation.spawnCharacter(1, character);
215 harness.simulation.quests.startQuest(character.character_id, "kill-rats-cave", null, []);
216
217 const ratId = harness.simulation.spawnEntity(mobComponents({
218 tileX: 8,
219 tileY: 9,
220 mobTypeId: MobId.rat,
221 spawnerId: null,
222 dimensionId: CAVE_ID
223 }));
224 const worker = workerOf(harness.simulation, ratId);
225 worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;
226 const killEvents = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
227 const mobKilled = killEvents.find((event) => event.type === "mob-killed");
228 assert.ok(mobKilled);
229 const noteEvents = harness.simulation.quests.noteKill(character.character_id, {
230 mobTypeId: mobKilled.mobTypeId,
231 spawnerId: mobKilled.spawnerId
232 });
233 assert.ok(noteEvents.some((event) => event.type === "questsDirty"));
234 assert.equal(
235 harness.stateDb.getQuestState(character.character_id, "kill-rats-cave").progress?.counters?.["mob:rat"],
236 1
237 );
238 const snap = harness.simulation.quests.questSnapshot(character.character_id);
239 assert.equal(snap.quests[0].step.objectives[0].current, 1);
240 assert.equal(snap.quests[0].step.objectives[0].required, 5);
241 }
242 finally
243 { harness.close(); }
244 });
245
246 test("character logout despawn carries dimensionId for cave interest", () =>
247 {
248 const harness = makeCaveHarness();
249 try
250 {
251 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
252 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
253 const entityId = harness.simulation.spawnCharacter(1, character);
254 assert.equal(harness.simulation.positionOf(entityId).dimensionId, CAVE_ID);
255 harness.simulation.drainReplication();
256
257 harness.simulation.despawnCharacter(character.character_id);
258 const gone = harness.simulation.drainReplication();
259 const despawn = gone.find((event) =>
260 event.type === "entity-despawn" && event.entityId === entityId
261 );
262 assert.ok(despawn, "expected entity-despawn replication");
263 assert.equal(despawn.dimensionId, CAVE_ID);
264 const keys = eventInterestKeys(despawn, () => null);
265 assert.equal(keys.dimensionId, CAVE_ID);
266 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(8), CAVE_ID));
267 }
268 finally
269 { harness.close(); }
270 });
@@ -12,9 +12,12 @@ import { StateDatabase } from "../src/persistence/stateDb.js";
12import { Simulation } from "../src/simulation/simulation.js";
12import { Simulation } from "../src/simulation/simulation.js";
13import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
13import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
14import { mobComponents } from "../src/simulation/spawners.js";
14import { mobComponents } from "../src/simulation/spawners.js";
15import { engageTarget, ensureMobCombat, stepCombat, stepAggression } from "../src/combat/service.js";
15import { engageTarget, ensureMobCombat, stepCombat, stepAggression, applyDamageAndKill } from "../src/combat/service.js";
16import { Component } from "../src/ecs/components.js";
16import { Component } from "../src/ecs/components.js";
17import { eventInterestKeys } from "../src/gateway/eventInterest.js";
18import { chunkKey, tileToChunk } from "../src/world/coordinates.js";
17import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
19import { makeCharacter, openChunkStrip, writeOpenChunk } from "./helpers/simulationHarness.js";
20import { normalizeQuestDef } from "../../shared/quests/normalize.js";
18
21
19const CAVE_ID = "test-cave";
22const CAVE_ID = "test-cave";
20
23
@@ -147,3 +150,121 @@ test("melee combat ticks in a non-overworld dimension", () =>
147 finally
150 finally
148 { harness.close(); }
151 { harness.close(); }
149});
152});
153
154test("mob kill entity-despawn carries cave dimensionId for interest", () =>
155{
156 const harness = makeCaveHarness();
157 try
158 {
159 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
160 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
161 const playerId = harness.simulation.spawnCharacter(1, character);
162 const ratId = harness.simulation.spawnEntity(mobComponents({
163 tileX: 8,
164 tileY: 9,
165 mobTypeId: MobId.rat,
166 spawnerId: null,
167 dimensionId: CAVE_ID
168 }));
169 const worker = workerOf(harness.simulation, ratId);
170 const handle = worker.world.ecs.handleOf(ratId);
171 worker.world.ecs.get(handle, Component.health).current = 1;
172 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
173 const despawn = events.find((event) =>
174 event.type === "entity-despawn" && event.entityId === ratId && event.cause === "death"
175 );
176 assert.ok(despawn, "expected combat death despawn");
177 assert.equal(despawn.dimensionId, CAVE_ID);
178 // Entity is already gone — interest must not fall back to overworld.
179 const keys = eventInterestKeys(despawn, () => null);
180 assert.equal(keys.dimensionId, CAVE_ID);
181 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(9), CAVE_ID));
182 assert.notEqual(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(9), OVERWORLD_ID));
183 }
184 finally
185 { harness.close(); }
186});
187
188test("cave rat kill advances killCount quest progress", () =>
189{
190 const harness = makeCaveHarness();
191 try
192 {
193 const quest = normalizeQuestDef({
194 questId: "kill-rats-cave",
195 title: "Kill Rats",
196 steps: [{
197 stepId: "step-1",
198 title: "Hunt",
199 objectives: [{
200 objectiveId: "obj-1",
201 text: "Kill 5 rats",
202 when: { all: [{ condition: { kind: "killCount", mobTypeId: "rat", count: 5 } }] }
203 }],
204 completionJournalText: "Done."
205 }]
206 });
207 const pending = harness.worldDb.ensurePendingRevision(1);
208 harness.worldDb.saveQuestDef(pending, quest);
209 harness.worldDb.promotePendingRevision();
210 harness.simulation.questContent.reload();
211
212 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
213 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
214 const playerId = harness.simulation.spawnCharacter(1, character);
215 harness.simulation.quests.startQuest(character.character_id, "kill-rats-cave", null, []);
216
217 const ratId = harness.simulation.spawnEntity(mobComponents({
218 tileX: 8,
219 tileY: 9,
220 mobTypeId: MobId.rat,
221 spawnerId: null,
222 dimensionId: CAVE_ID
223 }));
224 const worker = workerOf(harness.simulation, ratId);
225 worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;
226 const killEvents = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
227 const mobKilled = killEvents.find((event) => event.type === "mob-killed");
228 assert.ok(mobKilled);
229 const noteEvents = harness.simulation.quests.noteKill(character.character_id, {
230 mobTypeId: mobKilled.mobTypeId,
231 spawnerId: mobKilled.spawnerId
232 });
233 assert.ok(noteEvents.some((event) => event.type === "questsDirty"));
234 assert.equal(
235 harness.stateDb.getQuestState(character.character_id, "kill-rats-cave").progress?.counters?.["mob:rat"],
236 1
237 );
238 const snap = harness.simulation.quests.questSnapshot(character.character_id);
239 assert.equal(snap.quests[0].step.objectives[0].current, 1);
240 assert.equal(snap.quests[0].step.objectives[0].required, 5);
241 }
242 finally
243 { harness.close(); }
244});
245
246test("character logout despawn carries dimensionId for cave interest", () =>
247{
248 const harness = makeCaveHarness();
249 try
250 {
251 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
252 harness.stateDb.saveCharacterPosition(character.character_id, 8, 8, "walk", CAVE_ID);
253 const entityId = harness.simulation.spawnCharacter(1, character);
254 assert.equal(harness.simulation.positionOf(entityId).dimensionId, CAVE_ID);
255 harness.simulation.drainReplication();
256
257 harness.simulation.despawnCharacter(character.character_id);
258 const gone = harness.simulation.drainReplication();
259 const despawn = gone.find((event) =>
260 event.type === "entity-despawn" && event.entityId === entityId
261 );
262 assert.ok(despawn, "expected entity-despawn replication");
263 assert.equal(despawn.dimensionId, CAVE_ID);
264 const keys = eventInterestKeys(despawn, () => null);
265 assert.equal(keys.dimensionId, CAVE_ID);
266 assert.equal(keys.toKey, chunkKey(tileToChunk(8), tileToChunk(8), CAVE_ID));
267 }
268 finally
269 { harness.close(); }
270});
server/tests/doorway-graph.test.js added +142 −0
@@ -0,0 +1,142 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 buildDoorwayGraph,
5 findDimensionPath,
6 planPortalLegs,
7 buildFallbackLegs,
8 ensureCourierLegs,
9 advanceAbstractTravel,
10 poseOnCourierLeg,
11 estimateAbstractDistance
12 } from "../../shared/courier/doorwayGraph.js";
13 import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
14
15 test("doorway graph BFS finds multi-hop dimension path and reconstructs edges", () =>
16 {
17 const graph = buildDoorwayGraph([
18 {
19 tileX: 10, tileY: 10, dimensionId: OVERWORLD_ID,
20 targetDimensionId: "cave", targetTileX: 2, targetTileY: 2
21 },
22 {
23 tileX: 4, tileY: 4, dimensionId: "cave",
24 targetDimensionId: "cellar", targetTileX: 8, targetTileY: 1
25 },
26 {
27 tileX: 99, tileY: 99, dimensionId: "island",
28 targetDimensionId: OVERWORLD_ID, targetTileX: 0, targetTileY: 0
29 }
30 ]);
31 assert.equal(graph.edges.length, 3);
32 assert.equal(graph.byFromDim.get(OVERWORLD_ID).length, 1);
33
34 const path = findDimensionPath(graph, OVERWORLD_ID, "cellar");
35 assert.ok(path);
36 assert.equal(path.length, 2);
37 assert.equal(path[0].toDimensionId, "cave");
38 assert.equal(path[1].toDimensionId, "cellar");
39 assert.equal(path[1].fromTileX, 4);
40
41 assert.equal(findDimensionPath(graph, OVERWORLD_ID, OVERWORLD_ID).length, 0);
42 assert.equal(findDimensionPath(graph, "cellar", OVERWORLD_ID), null);
43 });
44
45 test("planPortalLegs builds fly/portal/fly for cross-dimension path", () =>
46 {
47 const graph = buildDoorwayGraph([
48 {
49 tileX: 10, tileY: 8, dimensionId: OVERWORLD_ID,
50 targetDimensionId: "cave", targetTileX: 3, targetTileY: 3
51 }
52 ]);
53 const planned = planPortalLegs({
54 fromX: 1.5, fromY: 8.5, fromDimensionId: OVERWORLD_ID,
55 toX: 5.5, toY: 3.5, toDimensionId: "cave",
56 graph
57 });
58 assert.equal(planned.mode, "portal");
59 assert.equal(planned.legs.length, 3);
60 assert.equal(planned.legs[0].kind, "fly");
61 assert.equal(planned.legs[0].toX, 10.5);
62 assert.equal(planned.legs[1].kind, "portal");
63 assert.equal(planned.legs[1].toDimensionId, "cave");
64 assert.equal(planned.legs[1].toX, 3.5);
65 assert.equal(planned.legs[2].kind, "fly");
66 assert.equal(planned.legs[2].toX, 5.5);
67 });
68
69 test("planPortalLegs returns fallback mode when no doorway path", () =>
70 {
71 const graph = buildDoorwayGraph([]);
72 const planned = planPortalLegs({
73 fromX: 1, fromY: 1, fromDimensionId: "cave",
74 toX: 20, toY: 8, toDimensionId: OVERWORLD_ID,
75 graph
76 });
77 assert.equal(planned.mode, "fallback");
78 assert.equal(planned.legs, null);
79 });
80
81 test("buildFallbackLegs produces fade-out, abstract, fade-in", () =>
82 {
83 const simulating = new Set(["cave:1,1", "cave:0,1", "overworld:20,8", "overworld:19,8"]);
84 const isSimulating = (tx, ty, dim) => simulating.has(`${dim}:${tx},${ty}`);
85 const { mode, legs } = buildFallbackLegs({
86 fromX: 1.5, fromY: 1.5, fromDimensionId: "cave",
87 toX: 20.5, toY: 8.5, toDimensionId: OVERWORLD_ID,
88 isSimulating
89 });
90 assert.equal(mode, "fallback");
91 assert.ok(legs.length >= 2);
92 assert.equal(legs[0].kind, "fly");
93 assert.equal(legs[0].fromDimensionId, "cave");
94 const abstract = legs.find((leg) => leg.kind === "abstract");
95 assert.ok(abstract);
96 assert.ok(abstract.distance >= 0);
97 assert.equal(legs[legs.length - 1].kind, "fly");
98 assert.equal(legs[legs.length - 1].toDimensionId, OVERWORLD_ID);
99 assert.equal(legs[legs.length - 1].toX, 20.5);
100 });
101
102 test("ensureCourierLegs migrates legacy overworld rows", () =>
103 {
104 const transit = {
105 originX: 2.5,
106 originY: 8.5,
107 destX: 20.5,
108 destY: 8.5,
109 traveled: 3
110 };
111 ensureCourierLegs(transit);
112 assert.equal(transit.originDimensionId, OVERWORLD_ID);
113 assert.equal(transit.destDimensionId, OVERWORLD_ID);
114 assert.equal(transit.legs.length, 1);
115 assert.equal(transit.legs[0].kind, "fly");
116 assert.equal(transit.legIndex, 0);
117 assert.equal(transit.traveled, 3);
118 });
119
120 test("advanceAbstractTravel and poseOnCourierLeg helpers", () =>
121 {
122 const advanced = advanceAbstractTravel({
123 traveled: 0,
124 distance: 16,
125 dt: 1,
126 settings: { pigeonCruiseTilesPerSec: 8 }
127 });
128 assert.equal(advanced.speed, 8);
129 assert.equal(advanced.traveled, 8);
130 assert.equal(advanced.arrived, false);
131
132 const flyPose = poseOnCourierLeg({
133 kind: "fly",
134 fromDimensionId: OVERWORLD_ID,
135 fromX: 0, fromY: 0, toX: 10, toY: 0
136 }, 5);
137 assert.ok(Math.abs(flyPose.x - 5) < 1e-6);
138 assert.equal(poseOnCourierLeg({ kind: "abstract", distance: 10 }, 3), null);
139 assert.ok(estimateAbstractDistance({
140 fromX: 0, fromY: 0, toX: 10, toY: 0, crossDimension: true
141 }) >= 32);
142 });
@@ -0,0 +1,142 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 buildDoorwayGraph,
5 findDimensionPath,
6 planPortalLegs,
7 buildFallbackLegs,
8 ensureCourierLegs,
9 advanceAbstractTravel,
10 poseOnCourierLeg,
11 estimateAbstractDistance
12} from "../../shared/courier/doorwayGraph.js";
13import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
14
15test("doorway graph BFS finds multi-hop dimension path and reconstructs edges", () =>
16{
17 const graph = buildDoorwayGraph([
18 {
19 tileX: 10, tileY: 10, dimensionId: OVERWORLD_ID,
20 targetDimensionId: "cave", targetTileX: 2, targetTileY: 2
21 },
22 {
23 tileX: 4, tileY: 4, dimensionId: "cave",
24 targetDimensionId: "cellar", targetTileX: 8, targetTileY: 1
25 },
26 {
27 tileX: 99, tileY: 99, dimensionId: "island",
28 targetDimensionId: OVERWORLD_ID, targetTileX: 0, targetTileY: 0
29 }
30 ]);
31 assert.equal(graph.edges.length, 3);
32 assert.equal(graph.byFromDim.get(OVERWORLD_ID).length, 1);
33
34 const path = findDimensionPath(graph, OVERWORLD_ID, "cellar");
35 assert.ok(path);
36 assert.equal(path.length, 2);
37 assert.equal(path[0].toDimensionId, "cave");
38 assert.equal(path[1].toDimensionId, "cellar");
39 assert.equal(path[1].fromTileX, 4);
40
41 assert.equal(findDimensionPath(graph, OVERWORLD_ID, OVERWORLD_ID).length, 0);
42 assert.equal(findDimensionPath(graph, "cellar", OVERWORLD_ID), null);
43});
44
45test("planPortalLegs builds fly/portal/fly for cross-dimension path", () =>
46{
47 const graph = buildDoorwayGraph([
48 {
49 tileX: 10, tileY: 8, dimensionId: OVERWORLD_ID,
50 targetDimensionId: "cave", targetTileX: 3, targetTileY: 3
51 }
52 ]);
53 const planned = planPortalLegs({
54 fromX: 1.5, fromY: 8.5, fromDimensionId: OVERWORLD_ID,
55 toX: 5.5, toY: 3.5, toDimensionId: "cave",
56 graph
57 });
58 assert.equal(planned.mode, "portal");
59 assert.equal(planned.legs.length, 3);
60 assert.equal(planned.legs[0].kind, "fly");
61 assert.equal(planned.legs[0].toX, 10.5);
62 assert.equal(planned.legs[1].kind, "portal");
63 assert.equal(planned.legs[1].toDimensionId, "cave");
64 assert.equal(planned.legs[1].toX, 3.5);
65 assert.equal(planned.legs[2].kind, "fly");
66 assert.equal(planned.legs[2].toX, 5.5);
67});
68
69test("planPortalLegs returns fallback mode when no doorway path", () =>
70{
71 const graph = buildDoorwayGraph([]);
72 const planned = planPortalLegs({
73 fromX: 1, fromY: 1, fromDimensionId: "cave",
74 toX: 20, toY: 8, toDimensionId: OVERWORLD_ID,
75 graph
76 });
77 assert.equal(planned.mode, "fallback");
78 assert.equal(planned.legs, null);
79});
80
81test("buildFallbackLegs produces fade-out, abstract, fade-in", () =>
82{
83 const simulating = new Set(["cave:1,1", "cave:0,1", "overworld:20,8", "overworld:19,8"]);
84 const isSimulating = (tx, ty, dim) => simulating.has(`${dim}:${tx},${ty}`);
85 const { mode, legs } = buildFallbackLegs({
86 fromX: 1.5, fromY: 1.5, fromDimensionId: "cave",
87 toX: 20.5, toY: 8.5, toDimensionId: OVERWORLD_ID,
88 isSimulating
89 });
90 assert.equal(mode, "fallback");
91 assert.ok(legs.length >= 2);
92 assert.equal(legs[0].kind, "fly");
93 assert.equal(legs[0].fromDimensionId, "cave");
94 const abstract = legs.find((leg) => leg.kind === "abstract");
95 assert.ok(abstract);
96 assert.ok(abstract.distance >= 0);
97 assert.equal(legs[legs.length - 1].kind, "fly");
98 assert.equal(legs[legs.length - 1].toDimensionId, OVERWORLD_ID);
99 assert.equal(legs[legs.length - 1].toX, 20.5);
100});
101
102test("ensureCourierLegs migrates legacy overworld rows", () =>
103{
104 const transit = {
105 originX: 2.5,
106 originY: 8.5,
107 destX: 20.5,
108 destY: 8.5,
109 traveled: 3
110 };
111 ensureCourierLegs(transit);
112 assert.equal(transit.originDimensionId, OVERWORLD_ID);
113 assert.equal(transit.destDimensionId, OVERWORLD_ID);
114 assert.equal(transit.legs.length, 1);
115 assert.equal(transit.legs[0].kind, "fly");
116 assert.equal(transit.legIndex, 0);
117 assert.equal(transit.traveled, 3);
118});
119
120test("advanceAbstractTravel and poseOnCourierLeg helpers", () =>
121{
122 const advanced = advanceAbstractTravel({
123 traveled: 0,
124 distance: 16,
125 dt: 1,
126 settings: { pigeonCruiseTilesPerSec: 8 }
127 });
128 assert.equal(advanced.speed, 8);
129 assert.equal(advanced.traveled, 8);
130 assert.equal(advanced.arrived, false);
131
132 const flyPose = poseOnCourierLeg({
133 kind: "fly",
134 fromDimensionId: OVERWORLD_ID,
135 fromX: 0, fromY: 0, toX: 10, toY: 0
136 }, 5);
137 assert.ok(Math.abs(flyPose.x - 5) < 1e-6);
138 assert.equal(poseOnCourierLeg({ kind: "abstract", distance: 10 }, 3), null);
139 assert.ok(estimateAbstractDistance({
140 fromX: 0, fromY: 0, toX: 10, toY: 0, crossDimension: true
141 }) >= 32);
142});
server/tests/quest-kill-spawner.test.js added +90 −0
@@ -0,0 +1,90 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { MobId } from "../../shared/definitions/mobs.js";
4 import { normalizeQuestDef } from "../../shared/quests/normalize.js";
5 import { ConditionKind } from "../../shared/quests/conditions.js";
6 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7 import { mobComponents } from "../src/simulation/spawners.js";
8 import { applyDamageAndKill } from "../src/combat/service.js";
9 import { Component } from "../src/ecs/components.js";
10
11 function saveQuest (harness, raw)
12 {
13 const revisionId = harness.worldDb.getActiveRevisionId();
14 const quest = normalizeQuestDef(raw);
15 const pending = harness.worldDb.ensurePendingRevision(1);
16 harness.worldDb.saveQuestDef(pending, quest);
17 harness.worldDb.promotePendingRevision();
18 harness.simulation.questContent.reload();
19 return quest;
20 }
21
22 test("killMobFromSpawner counts only matching spawner kills", () =>
23 {
24 const harness = makeSimulation({ workerCount: 1 });
25 try
26 {
27 saveQuest(harness, {
28 questId: "spawner-rats",
29 title: "Spawner rats",
30 steps: [{
31 stepId: "step-1",
32 title: "Hunt",
33 objectives: [{
34 objectiveId: "obj-1",
35 text: "Kill 2 from rats-a",
36 when: {
37 all: [{
38 condition: {
39 kind: ConditionKind.killMobFromSpawner,
40 mobTypeId: MobId.rat,
41 spawnerId: "rats-a",
42 count: 2
43 }
44 }]
45 }
46 }],
47 completionJournalText: "Done."
48 }]
49 });
50 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
51 const playerId = harness.simulation.spawnCharacter(1, character);
52 harness.simulation.quests.startQuest(character.character_id, "spawner-rats", null, []);
53
54 function killRat (spawnerId)
55 {
56 const ratId = harness.simulation.spawnEntity(mobComponents({
57 tileX: 9,
58 tileY: 8,
59 mobTypeId: MobId.rat,
60 spawnerId
61 }));
62 const worker = harness.simulation.workers[
63 harness.simulation.entityRecord(ratId).workerId
64 ];
65 worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;
66 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
67 const killed = events.find((event) => event.type === "mob-killed");
68 harness.simulation.quests.noteKill(character.character_id, {
69 mobTypeId: killed.mobTypeId,
70 spawnerId: killed.spawnerId
71 });
72 }
73
74 killRat("rats-b");
75 assert.equal(
76 harness.stateDb.getQuestState(character.character_id, "spawner-rats").progress?.counters?.["spawner:rats-a"] ?? 0,
77 0
78 );
79 killRat("rats-a");
80 assert.equal(
81 harness.stateDb.getQuestState(character.character_id, "spawner-rats").progress?.counters?.["spawner:rats-a"],
82 1
83 );
84 const snap = harness.simulation.quests.questSnapshot(character.character_id);
85 assert.equal(snap.quests[0].step.objectives[0].current, 1);
86 assert.equal(snap.quests[0].step.objectives[0].required, 2);
87 }
88 finally
89 { harness.close(); }
90 });
@@ -0,0 +1,90 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { MobId } from "../../shared/definitions/mobs.js";
4import { normalizeQuestDef } from "../../shared/quests/normalize.js";
5import { ConditionKind } from "../../shared/quests/conditions.js";
6import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
7import { mobComponents } from "../src/simulation/spawners.js";
8import { applyDamageAndKill } from "../src/combat/service.js";
9import { Component } from "../src/ecs/components.js";
10
11function saveQuest (harness, raw)
12{
13 const revisionId = harness.worldDb.getActiveRevisionId();
14 const quest = normalizeQuestDef(raw);
15 const pending = harness.worldDb.ensurePendingRevision(1);
16 harness.worldDb.saveQuestDef(pending, quest);
17 harness.worldDb.promotePendingRevision();
18 harness.simulation.questContent.reload();
19 return quest;
20}
21
22test("killMobFromSpawner counts only matching spawner kills", () =>
23{
24 const harness = makeSimulation({ workerCount: 1 });
25 try
26 {
27 saveQuest(harness, {
28 questId: "spawner-rats",
29 title: "Spawner rats",
30 steps: [{
31 stepId: "step-1",
32 title: "Hunt",
33 objectives: [{
34 objectiveId: "obj-1",
35 text: "Kill 2 from rats-a",
36 when: {
37 all: [{
38 condition: {
39 kind: ConditionKind.killMobFromSpawner,
40 mobTypeId: MobId.rat,
41 spawnerId: "rats-a",
42 count: 2
43 }
44 }]
45 }
46 }],
47 completionJournalText: "Done."
48 }]
49 });
50 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
51 const playerId = harness.simulation.spawnCharacter(1, character);
52 harness.simulation.quests.startQuest(character.character_id, "spawner-rats", null, []);
53
54 function killRat (spawnerId)
55 {
56 const ratId = harness.simulation.spawnEntity(mobComponents({
57 tileX: 9,
58 tileY: 8,
59 mobTypeId: MobId.rat,
60 spawnerId
61 }));
62 const worker = harness.simulation.workers[
63 harness.simulation.entityRecord(ratId).workerId
64 ];
65 worker.world.ecs.get(worker.world.ecs.handleOf(ratId), Component.health).current = 1;
66 const events = applyDamageAndKill(worker.world, playerId, ratId, 1, harness.now());
67 const killed = events.find((event) => event.type === "mob-killed");
68 harness.simulation.quests.noteKill(character.character_id, {
69 mobTypeId: killed.mobTypeId,
70 spawnerId: killed.spawnerId
71 });
72 }
73
74 killRat("rats-b");
75 assert.equal(
76 harness.stateDb.getQuestState(character.character_id, "spawner-rats").progress?.counters?.["spawner:rats-a"] ?? 0,
77 0
78 );
79 killRat("rats-a");
80 assert.equal(
81 harness.stateDb.getQuestState(character.character_id, "spawner-rats").progress?.counters?.["spawner:rats-a"],
82 1
83 );
84 const snap = harness.simulation.quests.questSnapshot(character.character_id);
85 assert.equal(snap.quests[0].step.objectives[0].current, 1);
86 assert.equal(snap.quests[0].step.objectives[0].required, 2);
87 }
88 finally
89 { harness.close(); }
90});
server/tests/quests-conditions.test.js +16 −0
@@ -159,6 +159,22 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",
159 159 { current: 2, required: 3 }
160 160 );
161 161
162 const fromSpawner = normalizeConditionSet({
163 all: [{ condition: { kind: ConditionKind.killMobFromSpawner, mobTypeId: "rat", spawnerId: "rats-1", count: 4 } }]
164 });
165 assert.deepEqual(
166 countableObjectiveProgress(fromSpawner, {
167 killCount: (c) => (c.kind === ConditionKind.killMobFromSpawner && c.spawnerId === "rats-1" ? 1 : 0)
168 }),
169 { current: 1, required: 4 }
170 );
171 assert.equal(
172 evaluateConditionSet(fromSpawner, {
173 killCount: (c) => (c.spawnerId === "rats-1" ? 4 : 0)
174 }),
175 true
176 );
177
162 178 const skill = normalizeConditionSet({
163 179 all: [{ condition: { kind: ConditionKind.skillLevelAtLeast, skillId: "woodcutting", level: 20 } }]
164 180 });
@@ -159,6 +159,22 @@ test("countable objective progress for hasItem killCount and skillLevelAtLeast",
159 { current: 2, required: 3 }
159 { current: 2, required: 3 }
160 );
160 );
161
161
162 const fromSpawner = normalizeConditionSet({
163 all: [{ condition: { kind: ConditionKind.killMobFromSpawner, mobTypeId: "rat", spawnerId: "rats-1", count: 4 } }]
164 });
165 assert.deepEqual(
166 countableObjectiveProgress(fromSpawner, {
167 killCount: (c) => (c.kind === ConditionKind.killMobFromSpawner && c.spawnerId === "rats-1" ? 1 : 0)
168 }),
169 { current: 1, required: 4 }
170 );
171 assert.equal(
172 evaluateConditionSet(fromSpawner, {
173 killCount: (c) => (c.spawnerId === "rats-1" ? 4 : 0)
174 }),
175 true
176 );
177
162 const skill = normalizeConditionSet({
178 const skill = normalizeConditionSet({
163 all: [{ condition: { kind: ConditionKind.skillLevelAtLeast, skillId: "woodcutting", level: 20 } }]
179 all: [{ condition: { kind: ConditionKind.skillLevelAtLeast, skillId: "woodcutting", level: 20 } }]
164 });
180 });
server/tests/spawner-bounty.test.js +65 −0
@@ -237,6 +237,71 @@ test("aggressive humanoid stores aggro flag and zero bounty", () =>
237 237 });
238 238 assert.equal(components.spawnOrigin.aggressive, true);
239 239 assert.equal(components.spawnOrigin.bounty, 0);
240 assert.equal(components.spawnOrigin.passive, false);
241 });
242
243 test("passive humanoid stores passive flag when not aggressive", () =>
244 {
245 const config = normalizeSpawnerConfig({
246 mobTypeId: MobId.humanoid,
247 aggressive: false,
248 passive: true,
249 bounty: 10
250 }, "passive-1");
251 assert.equal(config.aggressive, false);
252 assert.equal(config.passive, true);
253 assert.equal(config.bounty, 10);
254
255 const cleared = normalizeSpawnerConfig({
256 mobTypeId: MobId.humanoid,
257 aggressive: true,
258 passive: true,
259 bounty: 10
260 }, "passive-cleared");
261 assert.equal(cleared.aggressive, true);
262 assert.equal(cleared.passive, false);
263 assert.equal(cleared.bounty, 0);
264
265 const components = mobComponents({
266 tileX: 8,
267 tileY: 8,
268 mobTypeId: MobId.humanoid,
269 spawnerId: "passive-npc",
270 level: 2,
271 bounty: 5,
272 aggressive: false,
273 passive: true,
274 displayName: "Pacifist",
275 sex: "female"
276 });
277 assert.equal(components.spawnOrigin.aggressive, false);
278 assert.equal(components.spawnOrigin.passive, true);
279 assert.equal(components.spawnOrigin.bounty, 5);
280 });
281
282 test("wildlife passive stores on spawn origin; aggressive wildlife clears it", () =>
283 {
284 const deer = normalizeSpawnerConfig({
285 mobTypeId: MobId.deer,
286 passive: true
287 }, "deer-passive");
288 assert.equal(deer.passive, true);
289
290 const rat = normalizeSpawnerConfig({
291 mobTypeId: MobId.rat,
292 passive: true
293 }, "rat-passive");
294 assert.equal(rat.passive, false);
295
296 const components = mobComponents({
297 tileX: 4,
298 tileY: 4,
299 mobTypeId: MobId.deer,
300 spawnerId: "deer-p",
301 passive: true
302 });
303 assert.equal(components.spawnOrigin.passive, true);
304 assert.equal(components.spawnOrigin.aggressive, false);
240 305 });
241 306
242 307 test("killing a bounty mob awards player bounty and can wake town guards", () =>
@@ -237,6 +237,71 @@ test("aggressive humanoid stores aggro flag and zero bounty", () =>
237 });
237 });
238 assert.equal(components.spawnOrigin.aggressive, true);
238 assert.equal(components.spawnOrigin.aggressive, true);
239 assert.equal(components.spawnOrigin.bounty, 0);
239 assert.equal(components.spawnOrigin.bounty, 0);
240 assert.equal(components.spawnOrigin.passive, false);
241});
242
243test("passive humanoid stores passive flag when not aggressive", () =>
244{
245 const config = normalizeSpawnerConfig({
246 mobTypeId: MobId.humanoid,
247 aggressive: false,
248 passive: true,
249 bounty: 10
250 }, "passive-1");
251 assert.equal(config.aggressive, false);
252 assert.equal(config.passive, true);
253 assert.equal(config.bounty, 10);
254
255 const cleared = normalizeSpawnerConfig({
256 mobTypeId: MobId.humanoid,
257 aggressive: true,
258 passive: true,
259 bounty: 10
260 }, "passive-cleared");
261 assert.equal(cleared.aggressive, true);
262 assert.equal(cleared.passive, false);
263 assert.equal(cleared.bounty, 0);
264
265 const components = mobComponents({
266 tileX: 8,
267 tileY: 8,
268 mobTypeId: MobId.humanoid,
269 spawnerId: "passive-npc",
270 level: 2,
271 bounty: 5,
272 aggressive: false,
273 passive: true,
274 displayName: "Pacifist",
275 sex: "female"
276 });
277 assert.equal(components.spawnOrigin.aggressive, false);
278 assert.equal(components.spawnOrigin.passive, true);
279 assert.equal(components.spawnOrigin.bounty, 5);
280});
281
282test("wildlife passive stores on spawn origin; aggressive wildlife clears it", () =>
283{
284 const deer = normalizeSpawnerConfig({
285 mobTypeId: MobId.deer,
286 passive: true
287 }, "deer-passive");
288 assert.equal(deer.passive, true);
289
290 const rat = normalizeSpawnerConfig({
291 mobTypeId: MobId.rat,
292 passive: true
293 }, "rat-passive");
294 assert.equal(rat.passive, false);
295
296 const components = mobComponents({
297 tileX: 4,
298 tileY: 4,
299 mobTypeId: MobId.deer,
300 spawnerId: "deer-p",
301 passive: true
302 });
303 assert.equal(components.spawnOrigin.passive, true);
304 assert.equal(components.spawnOrigin.aggressive, false);
240});
305});
241
306
242test("killing a bounty mob awards player bounty and can wake town guards", () =>
307test("killing a bounty mob awards player bounty and can wake town guards", () =>
shared/courier/doorwayGraph.js added +424 −0
@@ -0,0 +1,424 @@
1 /**
2 * Pure doorway-portal graph for courier cross-dimension routing.
3 * Edges are unidirectional (from doorway tile → configured target).
4 */
5
6 import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
7 import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
8
9 /**
10 * @typedef {{
11 * fromDimensionId: string,
12 * fromTileX: number,
13 * fromTileY: number,
14 * toDimensionId: string,
15 * toTileX: number,
16 * toTileY: number
17 * }} DoorwayEdge
18 */
19
20 /**
21 * @typedef {{
22 * kind: "fly" | "portal" | "abstract",
23 * fromDimensionId?: string,
24 * fromX?: number,
25 * fromY?: number,
26 * toDimensionId?: string,
27 * toX?: number,
28 * toY?: number,
29 * distance?: number
30 * }} CourierLeg
31 */
32
33 /**
34 * Build a directed doorway graph from scanned doorway tiles.
35 * @param {Array<{
36 * tileX: number,
37 * tileY: number,
38 * dimensionId?: string,
39 * targetDimensionId?: string,
40 * targetTileX?: number,
41 * targetTileY?: number
42 * }>} doorways
43 */
44 export function buildDoorwayGraph (doorways)
45 {
46 const edges = [];
47 /** @type {Map<string, DoorwayEdge[]>} */
48 const byFromDim = new Map();
49 for (const doorway of doorways ?? [])
50 {
51 const targetRaw = doorway?.targetDimensionId;
52 if (targetRaw == null || String(targetRaw).trim() === "")
53 { continue; }
54 const targetTileX = Number(doorway.targetTileX);
55 const targetTileY = Number(doorway.targetTileY);
56 if (!Number.isFinite(targetTileX) || !Number.isFinite(targetTileY))
57 { continue; }
58 /** @type {DoorwayEdge} */
59 const edge = {
60 fromDimensionId: normalizeDimensionId(doorway.dimensionId ?? OVERWORLD_ID),
61 fromTileX: doorway.tileX | 0,
62 fromTileY: doorway.tileY | 0,
63 toDimensionId: normalizeDimensionId(targetRaw),
64 toTileX: targetTileX | 0,
65 toTileY: targetTileY | 0
66 };
67 edges.push(edge);
68 const list = byFromDim.get(edge.fromDimensionId);
69 if (list)
70 { list.push(edge); }
71 else
72 { byFromDim.set(edge.fromDimensionId, [edge]); }
73 }
74 return { edges, byFromDim };
75 }
76
77 /**
78 * BFS over dimensions via doorway edges. Returns the doorway edge sequence,
79 * or null if unreachable. Same-dimension yields [].
80 * @param {{ byFromDim: Map<string, DoorwayEdge[]> }} graph
81 * @param {string} fromDimensionId
82 * @param {string} toDimensionId
83 * @returns {DoorwayEdge[] | null}
84 */
85 export function findDimensionPath (graph, fromDimensionId, toDimensionId)
86 {
87 const fromDim = normalizeDimensionId(fromDimensionId);
88 const toDim = normalizeDimensionId(toDimensionId);
89 if (fromDim === toDim)
90 { return []; }
91 const byFromDim = graph?.byFromDim ?? new Map();
92 const queue = [fromDim];
93 const visited = new Set([fromDim]);
94 /** @type {Map<string, DoorwayEdge>} */
95 const cameVia = new Map();
96 let head = 0;
97 while (head < queue.length)
98 {
99 const current = queue[head++];
100 for (const edge of byFromDim.get(current) ?? [])
101 {
102 const next = edge.toDimensionId;
103 if (visited.has(next))
104 { continue; }
105 visited.add(next);
106 cameVia.set(next, edge);
107 if (next === toDim)
108 {
109 const path = [];
110 let dim = toDim;
111 while (dim !== fromDim)
112 {
113 const via = cameVia.get(dim);
114 if (!via)
115 { return null; }
116 path.push(via);
117 dim = via.fromDimensionId;
118 }
119 path.reverse();
120 return path;
121 }
122 queue.push(next);
123 }
124 }
125 return null;
126 }
127
128 function flyLeg (fromDimensionId, fromX, fromY, toDimensionId, toX, toY)
129 {
130 return {
131 kind: "fly",
132 fromDimensionId: normalizeDimensionId(fromDimensionId),
133 fromX,
134 fromY,
135 toDimensionId: normalizeDimensionId(toDimensionId),
136 toX,
137 toY
138 };
139 }
140
141 function portalLeg (edge)
142 {
143 return {
144 kind: "portal",
145 fromDimensionId: edge.fromDimensionId,
146 fromX: edge.fromTileX + 0.5,
147 fromY: edge.fromTileY + 0.5,
148 toDimensionId: edge.toDimensionId,
149 toX: edge.toTileX + 0.5,
150 toY: edge.toTileY + 0.5
151 };
152 }
153
154 /**
155 * Plan courier legs from origin to destination using the doorway graph.
156 * Same-dim → single fly. Cross-dim with path → fly/portal/fly….
157 * Cross-dim with no path → { mode: "fallback", legs: null } (caller builds fade legs).
158 */
159 export function planPortalLegs ({
160 fromX,
161 fromY,
162 fromDimensionId = OVERWORLD_ID,
163 toX,
164 toY,
165 toDimensionId = OVERWORLD_ID,
166 graph
167 })
168 {
169 const fromDim = normalizeDimensionId(fromDimensionId);
170 const toDim = normalizeDimensionId(toDimensionId);
171 if (fromDim === toDim)
172 {
173 return {
174 mode: "direct",
175 legs: [flyLeg(fromDim, fromX, fromY, toDim, toX, toY)]
176 };
177 }
178 const doorPath = findDimensionPath(graph, fromDim, toDim);
179 if (!doorPath)
180 {
181 return { mode: "fallback", legs: null };
182 }
183 /** @type {CourierLeg[]} */
184 const legs = [];
185 let cx = fromX;
186 let cy = fromY;
187 let cd = fromDim;
188 for (const edge of doorPath)
189 {
190 const enterX = edge.fromTileX + 0.5;
191 const enterY = edge.fromTileY + 0.5;
192 legs.push(flyLeg(cd, cx, cy, cd, enterX, enterY));
193 legs.push(portalLeg(edge));
194 cx = edge.toTileX + 0.5;
195 cy = edge.toTileY + 0.5;
196 cd = edge.toDimensionId;
197 }
198 legs.push(flyLeg(cd, cx, cy, toDim, toX, toY));
199 return { mode: "portal", legs };
200 }
201
202 /**
203 * Walk from (x,y) along unit direction until `stop(tileX, tileY)` is true.
204 * Returns the first tile-center where stop is true, or the last sample if never.
205 */
206 export function walkUntilStop ({
207 x,
208 y,
209 dirX,
210 dirY,
211 stop,
212 maxSteps = 96,
213 step = 1
214 })
215 {
216 let px = x;
217 let py = y;
218 const len = Math.hypot(dirX, dirY);
219 const ux = len > 1e-9 ? dirX / len : 1;
220 const uy = len > 1e-9 ? dirY / len : 0;
221 for (let i = 0; i < maxSteps; i++)
222 {
223 px += ux * step;
224 py += uy * step;
225 if (stop(Math.floor(px), Math.floor(py)))
226 { return { x: px, y: py, steps: i + 1 }; }
227 }
228 return { x: px, y: py, steps: maxSteps };
229 }
230
231 export function estimateAbstractDistance ({
232 fromX,
233 fromY,
234 toX,
235 toY,
236 fadeOutDist = 0,
237 fadeInDist = 0,
238 crossDimension = false
239 })
240 {
241 const direct = Math.hypot(toX - fromX, toY - fromY);
242 const budget = crossDimension ? Math.max(direct, 32) : direct;
243 return Math.max(0, budget - fadeOutDist - fadeInDist);
244 }
245
246 /**
247 * Build fade-out → abstract → fade-in legs when no doorway path exists.
248 * `isSimulating(tileX, tileY, dimensionId)` must not force-load regions.
249 */
250 export function buildFallbackLegs ({
251 fromX,
252 fromY,
253 fromDimensionId = OVERWORLD_ID,
254 toX,
255 toY,
256 toDimensionId = OVERWORLD_ID,
257 isSimulating,
258 settings = DEFAULT_WORLD_SETTINGS
259 })
260 {
261 void settings;
262 const fromDim = normalizeDimensionId(fromDimensionId);
263 const toDim = normalizeDimensionId(toDimensionId);
264 const awayX = fromX - toX;
265 const awayY = fromY - toY;
266 const awayLen = Math.hypot(awayX, awayY);
267 const outDirX = awayLen > 1e-9 ? awayX / awayLen : 1;
268 const outDirY = awayLen > 1e-9 ? awayY / awayLen : 0;
269
270 /** @type {CourierLeg[]} */
271 const legs = [];
272 let fadeOutEndX = fromX;
273 let fadeOutEndY = fromY;
274 let fadeOutDist = 0;
275 if (typeof isSimulating === "function"
276 && isSimulating(Math.floor(fromX), Math.floor(fromY), fromDim))
277 {
278 const exit = walkUntilStop({
279 x: fromX,
280 y: fromY,
281 dirX: outDirX,
282 dirY: outDirY,
283 stop: (tx, ty) => !isSimulating(tx, ty, fromDim)
284 });
285 fadeOutEndX = exit.x;
286 fadeOutEndY = exit.y;
287 fadeOutDist = Math.hypot(fadeOutEndX - fromX, fadeOutEndY - fromY);
288 legs.push(flyLeg(fromDim, fromX, fromY, fromDim, fadeOutEndX, fadeOutEndY));
289 }
290
291 const approachX = toX - fromX;
292 const approachY = toY - fromY;
293 const approachLen = Math.hypot(approachX, approachY);
294 const backDirX = approachLen > 1e-9 ? -approachX / approachLen : -1;
295 const backDirY = approachLen > 1e-9 ? -approachY / approachLen : 0;
296
297 let fadeInStartX = toX;
298 let fadeInStartY = toY;
299 let fadeInDist = 0;
300 const destSimulating = typeof isSimulating === "function"
301 && isSimulating(Math.floor(toX), Math.floor(toY), toDim);
302 if (destSimulating)
303 {
304 const entry = walkUntilStop({
305 x: toX,
306 y: toY,
307 dirX: backDirX,
308 dirY: backDirY,
309 stop: (tx, ty) => !isSimulating(tx, ty, toDim)
310 });
311 fadeInStartX = entry.x;
312 fadeInStartY = entry.y;
313 fadeInDist = Math.hypot(toX - fadeInStartX, toY - fadeInStartY);
314 }
315
316 const abstractDistance = estimateAbstractDistance({
317 fromX,
318 fromY,
319 toX,
320 toY,
321 fadeOutDist,
322 fadeInDist,
323 crossDimension: fromDim !== toDim
324 });
325 legs.push({
326 kind: "abstract",
327 fromDimensionId: fromDim,
328 fromX: fadeOutEndX,
329 fromY: fadeOutEndY,
330 toDimensionId: toDim,
331 toX: fadeInStartX,
332 toY: fadeInStartY,
333 distance: abstractDistance
334 });
335 legs.push(flyLeg(toDim, fadeInStartX, fadeInStartY, toDim, toX, toY));
336 return { mode: "fallback", legs };
337 }
338
339 /**
340 * Advance an abstract (invisible) travel leg at cruise speed.
341 */
342 export function advanceAbstractTravel ({
343 traveled,
344 distance,
345 dt,
346 settings = DEFAULT_WORLD_SETTINGS
347 })
348 {
349 const total = Math.max(0, distance ?? 0);
350 const cruise = Math.max(0.25, settings.pigeonCruiseTilesPerSec ?? 8);
351 if (!(total > 0))
352 {
353 return {
354 traveled: 0,
355 arrived: true,
356 speed: 0,
357 total: 0
358 };
359 }
360 const nextTraveled = Math.min(total, (traveled || 0) + cruise * Math.max(0, dt));
361 return {
362 traveled: nextTraveled,
363 arrived: nextTraveled >= total - 1e-6,
364 speed: cruise,
365 total
366 };
367 }
368
369 /**
370 * Pose along the current leg given traveled distance.
371 * Abstract legs have no visible pose (returns null).
372 */
373 export function poseOnCourierLeg (leg, traveled = 0)
374 {
375 if (!leg)
376 { return null; }
377 if (leg.kind === "abstract")
378 { return null; }
379 if (leg.kind === "portal")
380 {
381 return {
382 x: leg.toX,
383 y: leg.toY,
384 dimensionId: normalizeDimensionId(leg.toDimensionId ?? OVERWORLD_ID)
385 };
386 }
387 const fromX = leg.fromX;
388 const fromY = leg.fromY;
389 const toX = leg.toX;
390 const toY = leg.toY;
391 const total = Math.hypot(toX - fromX, toY - fromY);
392 const t = total < 1e-6 ? 1 : Math.min(1, Math.max(0, (traveled || 0) / total));
393 return {
394 x: fromX + (toX - fromX) * t,
395 y: fromY + (toY - fromY) * t,
396 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
397 };
398 }
399
400 /**
401 * Normalize / migrate a transit's legs. Old rows without legs become a single fly.
402 */
403 export function ensureCourierLegs (transit)
404 {
405 if (Array.isArray(transit.legs) && transit.legs.length > 0)
406 {
407 transit.legIndex = Math.max(0, Math.min(transit.legIndex | 0, transit.legs.length - 1));
408 return transit;
409 }
410 const fromDim = normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID);
411 const toDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
412 transit.legs = [flyLeg(
413 fromDim,
414 transit.originX,
415 transit.originY,
416 toDim,
417 transit.destX,
418 transit.destY
419 )];
420 transit.legIndex = 0;
421 transit.originDimensionId = fromDim;
422 transit.destDimensionId = toDim;
423 return transit;
424 }
@@ -0,0 +1,424 @@
1/**
2 * Pure doorway-portal graph for courier cross-dimension routing.
3 * Edges are unidirectional (from doorway tile → configured target).
4 */
5
6import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
7import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js";
8
9/**
10 * @typedef {{
11 * fromDimensionId: string,
12 * fromTileX: number,
13 * fromTileY: number,
14 * toDimensionId: string,
15 * toTileX: number,
16 * toTileY: number
17 * }} DoorwayEdge
18 */
19
20/**
21 * @typedef {{
22 * kind: "fly" | "portal" | "abstract",
23 * fromDimensionId?: string,
24 * fromX?: number,
25 * fromY?: number,
26 * toDimensionId?: string,
27 * toX?: number,
28 * toY?: number,
29 * distance?: number
30 * }} CourierLeg
31 */
32
33/**
34 * Build a directed doorway graph from scanned doorway tiles.
35 * @param {Array<{
36 * tileX: number,
37 * tileY: number,
38 * dimensionId?: string,
39 * targetDimensionId?: string,
40 * targetTileX?: number,
41 * targetTileY?: number
42 * }>} doorways
43 */
44export function buildDoorwayGraph (doorways)
45{
46 const edges = [];
47 /** @type {Map<string, DoorwayEdge[]>} */
48 const byFromDim = new Map();
49 for (const doorway of doorways ?? [])
50 {
51 const targetRaw = doorway?.targetDimensionId;
52 if (targetRaw == null || String(targetRaw).trim() === "")
53 { continue; }
54 const targetTileX = Number(doorway.targetTileX);
55 const targetTileY = Number(doorway.targetTileY);
56 if (!Number.isFinite(targetTileX) || !Number.isFinite(targetTileY))
57 { continue; }
58 /** @type {DoorwayEdge} */
59 const edge = {
60 fromDimensionId: normalizeDimensionId(doorway.dimensionId ?? OVERWORLD_ID),
61 fromTileX: doorway.tileX | 0,
62 fromTileY: doorway.tileY | 0,
63 toDimensionId: normalizeDimensionId(targetRaw),
64 toTileX: targetTileX | 0,
65 toTileY: targetTileY | 0
66 };
67 edges.push(edge);
68 const list = byFromDim.get(edge.fromDimensionId);
69 if (list)
70 { list.push(edge); }
71 else
72 { byFromDim.set(edge.fromDimensionId, [edge]); }
73 }
74 return { edges, byFromDim };
75}
76
77/**
78 * BFS over dimensions via doorway edges. Returns the doorway edge sequence,
79 * or null if unreachable. Same-dimension yields [].
80 * @param {{ byFromDim: Map<string, DoorwayEdge[]> }} graph
81 * @param {string} fromDimensionId
82 * @param {string} toDimensionId
83 * @returns {DoorwayEdge[] | null}
84 */
85export function findDimensionPath (graph, fromDimensionId, toDimensionId)
86{
87 const fromDim = normalizeDimensionId(fromDimensionId);
88 const toDim = normalizeDimensionId(toDimensionId);
89 if (fromDim === toDim)
90 { return []; }
91 const byFromDim = graph?.byFromDim ?? new Map();
92 const queue = [fromDim];
93 const visited = new Set([fromDim]);
94 /** @type {Map<string, DoorwayEdge>} */
95 const cameVia = new Map();
96 let head = 0;
97 while (head < queue.length)
98 {
99 const current = queue[head++];
100 for (const edge of byFromDim.get(current) ?? [])
101 {
102 const next = edge.toDimensionId;
103 if (visited.has(next))
104 { continue; }
105 visited.add(next);
106 cameVia.set(next, edge);
107 if (next === toDim)
108 {
109 const path = [];
110 let dim = toDim;
111 while (dim !== fromDim)
112 {
113 const via = cameVia.get(dim);
114 if (!via)
115 { return null; }
116 path.push(via);
117 dim = via.fromDimensionId;
118 }
119 path.reverse();
120 return path;
121 }
122 queue.push(next);
123 }
124 }
125 return null;
126}
127
128function flyLeg (fromDimensionId, fromX, fromY, toDimensionId, toX, toY)
129{
130 return {
131 kind: "fly",
132 fromDimensionId: normalizeDimensionId(fromDimensionId),
133 fromX,
134 fromY,
135 toDimensionId: normalizeDimensionId(toDimensionId),
136 toX,
137 toY
138 };
139}
140
141function portalLeg (edge)
142{
143 return {
144 kind: "portal",
145 fromDimensionId: edge.fromDimensionId,
146 fromX: edge.fromTileX + 0.5,
147 fromY: edge.fromTileY + 0.5,
148 toDimensionId: edge.toDimensionId,
149 toX: edge.toTileX + 0.5,
150 toY: edge.toTileY + 0.5
151 };
152}
153
154/**
155 * Plan courier legs from origin to destination using the doorway graph.
156 * Same-dim → single fly. Cross-dim with path → fly/portal/fly….
157 * Cross-dim with no path → { mode: "fallback", legs: null } (caller builds fade legs).
158 */
159export function planPortalLegs ({
160 fromX,
161 fromY,
162 fromDimensionId = OVERWORLD_ID,
163 toX,
164 toY,
165 toDimensionId = OVERWORLD_ID,
166 graph
167})
168{
169 const fromDim = normalizeDimensionId(fromDimensionId);
170 const toDim = normalizeDimensionId(toDimensionId);
171 if (fromDim === toDim)
172 {
173 return {
174 mode: "direct",
175 legs: [flyLeg(fromDim, fromX, fromY, toDim, toX, toY)]
176 };
177 }
178 const doorPath = findDimensionPath(graph, fromDim, toDim);
179 if (!doorPath)
180 {
181 return { mode: "fallback", legs: null };
182 }
183 /** @type {CourierLeg[]} */
184 const legs = [];
185 let cx = fromX;
186 let cy = fromY;
187 let cd = fromDim;
188 for (const edge of doorPath)
189 {
190 const enterX = edge.fromTileX + 0.5;
191 const enterY = edge.fromTileY + 0.5;
192 legs.push(flyLeg(cd, cx, cy, cd, enterX, enterY));
193 legs.push(portalLeg(edge));
194 cx = edge.toTileX + 0.5;
195 cy = edge.toTileY + 0.5;
196 cd = edge.toDimensionId;
197 }
198 legs.push(flyLeg(cd, cx, cy, toDim, toX, toY));
199 return { mode: "portal", legs };
200}
201
202/**
203 * Walk from (x,y) along unit direction until `stop(tileX, tileY)` is true.
204 * Returns the first tile-center where stop is true, or the last sample if never.
205 */
206export function walkUntilStop ({
207 x,
208 y,
209 dirX,
210 dirY,
211 stop,
212 maxSteps = 96,
213 step = 1
214})
215{
216 let px = x;
217 let py = y;
218 const len = Math.hypot(dirX, dirY);
219 const ux = len > 1e-9 ? dirX / len : 1;
220 const uy = len > 1e-9 ? dirY / len : 0;
221 for (let i = 0; i < maxSteps; i++)
222 {
223 px += ux * step;
224 py += uy * step;
225 if (stop(Math.floor(px), Math.floor(py)))
226 { return { x: px, y: py, steps: i + 1 }; }
227 }
228 return { x: px, y: py, steps: maxSteps };
229}
230
231export function estimateAbstractDistance ({
232 fromX,
233 fromY,
234 toX,
235 toY,
236 fadeOutDist = 0,
237 fadeInDist = 0,
238 crossDimension = false
239})
240{
241 const direct = Math.hypot(toX - fromX, toY - fromY);
242 const budget = crossDimension ? Math.max(direct, 32) : direct;
243 return Math.max(0, budget - fadeOutDist - fadeInDist);
244}
245
246/**
247 * Build fade-out → abstract → fade-in legs when no doorway path exists.
248 * `isSimulating(tileX, tileY, dimensionId)` must not force-load regions.
249 */
250export function buildFallbackLegs ({
251 fromX,
252 fromY,
253 fromDimensionId = OVERWORLD_ID,
254 toX,
255 toY,
256 toDimensionId = OVERWORLD_ID,
257 isSimulating,
258 settings = DEFAULT_WORLD_SETTINGS
259})
260{
261 void settings;
262 const fromDim = normalizeDimensionId(fromDimensionId);
263 const toDim = normalizeDimensionId(toDimensionId);
264 const awayX = fromX - toX;
265 const awayY = fromY - toY;
266 const awayLen = Math.hypot(awayX, awayY);
267 const outDirX = awayLen > 1e-9 ? awayX / awayLen : 1;
268 const outDirY = awayLen > 1e-9 ? awayY / awayLen : 0;
269
270 /** @type {CourierLeg[]} */
271 const legs = [];
272 let fadeOutEndX = fromX;
273 let fadeOutEndY = fromY;
274 let fadeOutDist = 0;
275 if (typeof isSimulating === "function"
276 && isSimulating(Math.floor(fromX), Math.floor(fromY), fromDim))
277 {
278 const exit = walkUntilStop({
279 x: fromX,
280 y: fromY,
281 dirX: outDirX,
282 dirY: outDirY,
283 stop: (tx, ty) => !isSimulating(tx, ty, fromDim)
284 });
285 fadeOutEndX = exit.x;
286 fadeOutEndY = exit.y;
287 fadeOutDist = Math.hypot(fadeOutEndX - fromX, fadeOutEndY - fromY);
288 legs.push(flyLeg(fromDim, fromX, fromY, fromDim, fadeOutEndX, fadeOutEndY));
289 }
290
291 const approachX = toX - fromX;
292 const approachY = toY - fromY;
293 const approachLen = Math.hypot(approachX, approachY);
294 const backDirX = approachLen > 1e-9 ? -approachX / approachLen : -1;
295 const backDirY = approachLen > 1e-9 ? -approachY / approachLen : 0;
296
297 let fadeInStartX = toX;
298 let fadeInStartY = toY;
299 let fadeInDist = 0;
300 const destSimulating = typeof isSimulating === "function"
301 && isSimulating(Math.floor(toX), Math.floor(toY), toDim);
302 if (destSimulating)
303 {
304 const entry = walkUntilStop({
305 x: toX,
306 y: toY,
307 dirX: backDirX,
308 dirY: backDirY,
309 stop: (tx, ty) => !isSimulating(tx, ty, toDim)
310 });
311 fadeInStartX = entry.x;
312 fadeInStartY = entry.y;
313 fadeInDist = Math.hypot(toX - fadeInStartX, toY - fadeInStartY);
314 }
315
316 const abstractDistance = estimateAbstractDistance({
317 fromX,
318 fromY,
319 toX,
320 toY,
321 fadeOutDist,
322 fadeInDist,
323 crossDimension: fromDim !== toDim
324 });
325 legs.push({
326 kind: "abstract",
327 fromDimensionId: fromDim,
328 fromX: fadeOutEndX,
329 fromY: fadeOutEndY,
330 toDimensionId: toDim,
331 toX: fadeInStartX,
332 toY: fadeInStartY,
333 distance: abstractDistance
334 });
335 legs.push(flyLeg(toDim, fadeInStartX, fadeInStartY, toDim, toX, toY));
336 return { mode: "fallback", legs };
337}
338
339/**
340 * Advance an abstract (invisible) travel leg at cruise speed.
341 */
342export function advanceAbstractTravel ({
343 traveled,
344 distance,
345 dt,
346 settings = DEFAULT_WORLD_SETTINGS
347})
348{
349 const total = Math.max(0, distance ?? 0);
350 const cruise = Math.max(0.25, settings.pigeonCruiseTilesPerSec ?? 8);
351 if (!(total > 0))
352 {
353 return {
354 traveled: 0,
355 arrived: true,
356 speed: 0,
357 total: 0
358 };
359 }
360 const nextTraveled = Math.min(total, (traveled || 0) + cruise * Math.max(0, dt));
361 return {
362 traveled: nextTraveled,
363 arrived: nextTraveled >= total - 1e-6,
364 speed: cruise,
365 total
366 };
367}
368
369/**
370 * Pose along the current leg given traveled distance.
371 * Abstract legs have no visible pose (returns null).
372 */
373export function poseOnCourierLeg (leg, traveled = 0)
374{
375 if (!leg)
376 { return null; }
377 if (leg.kind === "abstract")
378 { return null; }
379 if (leg.kind === "portal")
380 {
381 return {
382 x: leg.toX,
383 y: leg.toY,
384 dimensionId: normalizeDimensionId(leg.toDimensionId ?? OVERWORLD_ID)
385 };
386 }
387 const fromX = leg.fromX;
388 const fromY = leg.fromY;
389 const toX = leg.toX;
390 const toY = leg.toY;
391 const total = Math.hypot(toX - fromX, toY - fromY);
392 const t = total < 1e-6 ? 1 : Math.min(1, Math.max(0, (traveled || 0) / total));
393 return {
394 x: fromX + (toX - fromX) * t,
395 y: fromY + (toY - fromY) * t,
396 dimensionId: normalizeDimensionId(leg.fromDimensionId ?? OVERWORLD_ID)
397 };
398}
399
400/**
401 * Normalize / migrate a transit's legs. Old rows without legs become a single fly.
402 */
403export function ensureCourierLegs (transit)
404{
405 if (Array.isArray(transit.legs) && transit.legs.length > 0)
406 {
407 transit.legIndex = Math.max(0, Math.min(transit.legIndex | 0, transit.legs.length - 1));
408 return transit;
409 }
410 const fromDim = normalizeDimensionId(transit.originDimensionId ?? OVERWORLD_ID);
411 const toDim = normalizeDimensionId(transit.destDimensionId ?? OVERWORLD_ID);
412 transit.legs = [flyLeg(
413 fromDim,
414 transit.originX,
415 transit.originY,
416 toDim,
417 transit.destX,
418 transit.destY
419 )];
420 transit.legIndex = 0;
421 transit.originDimensionId = fromDim;
422 transit.destDimensionId = toDim;
423 return transit;
424}
shared/definitions/mobs.js +6 −0
@@ -510,6 +510,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
510 510 bounty,
511 511 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
512 512 aggressive: false,
513 /** When set (and Aggressive is off): mob takes hits but does not retaliate. */
514 passive: false,
513 515 sex: "male",
514 516 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
515 517 equipment: townGuard
@@ -729,6 +731,9 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
729 731 const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
730 732 const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
731 733 const aggressive = bodyNpc ? !!merged.aggressive : false;
734 // Passive only when Aggressive is off (spawner flag or wildlife mob def).
735 const defAggressive = !bodyNpc && !!mobDefinition(effectiveMob)?.aggressive;
736 const passive = !aggressive && !defAggressive && !!merged.passive;
732 737 const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
733 738 return {
734 739 spawnerId: String(merged.spawnerId),
@@ -754,6 +759,7 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
754 759 level,
755 760 bounty,
756 761 aggressive,
762 passive,
757 763 sex,
758 764 displayName,
759 765 equipment: normalizeEquipment(merged.equipment),
@@ -510,6 +510,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
510 bounty,
510 bounty,
511 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
511 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
512 aggressive: false,
512 aggressive: false,
513 /** When set (and Aggressive is off): mob takes hits but does not retaliate. */
514 passive: false,
513 sex: "male",
515 sex: "male",
514 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
516 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
515 equipment: townGuard
517 equipment: townGuard
@@ -729,6 +731,9 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
729 const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
731 const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
730 const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
732 const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
731 const aggressive = bodyNpc ? !!merged.aggressive : false;
733 const aggressive = bodyNpc ? !!merged.aggressive : false;
734 // Passive only when Aggressive is off (spawner flag or wildlife mob def).
735 const defAggressive = !bodyNpc && !!mobDefinition(effectiveMob)?.aggressive;
736 const passive = !aggressive && !defAggressive && !!merged.passive;
732 const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
737 const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
733 return {
738 return {
734 spawnerId: String(merged.spawnerId),
739 spawnerId: String(merged.spawnerId),
@@ -754,6 +759,7 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
754 level,
759 level,
755 bounty,
760 bounty,
756 aggressive,
761 aggressive,
762 passive,
757 sex,
763 sex,
758 displayName,
764 displayName,
759 equipment: normalizeEquipment(merged.equipment),
765 equipment: normalizeEquipment(merged.equipment),
shared/quests/conditions.js +2 −0
@@ -21,6 +21,7 @@ export const ConditionKind = Object.freeze({
21 21 staminaPercentAtLeast: "staminaPercentAtLeast",
22 22 skillLevelAtLeast: "skillLevelAtLeast",
23 23 killCount: "killCount",
24 killMobFromSpawner: "killMobFromSpawner",
24 25 interactBlock: "interactBlock"
25 26 });
26 27
@@ -238,6 +239,7 @@ export function evaluateCondition (condition, ctx)
238 239 case ConditionKind.skillLevelAtLeast:
239 240 return (ctx.skillLevel?.(condition.skillId) ?? 1) >= skillRequirementThreshold(condition);
240 241 case ConditionKind.killCount:
242 case ConditionKind.killMobFromSpawner:
241 243 return (ctx.killCount?.(condition) ?? 0) >= Math.max(1, Number(condition.count) || 1);
242 244 case ConditionKind.interactBlock:
243 245 return sameDimension(condition, ctx) && !!ctx.interactBlockDone?.(condition);
@@ -21,6 +21,7 @@ export const ConditionKind = Object.freeze({
21 staminaPercentAtLeast: "staminaPercentAtLeast",
21 staminaPercentAtLeast: "staminaPercentAtLeast",
22 skillLevelAtLeast: "skillLevelAtLeast",
22 skillLevelAtLeast: "skillLevelAtLeast",
23 killCount: "killCount",
23 killCount: "killCount",
24 killMobFromSpawner: "killMobFromSpawner",
24 interactBlock: "interactBlock"
25 interactBlock: "interactBlock"
25});
26});
26
27
@@ -238,6 +239,7 @@ export function evaluateCondition (condition, ctx)
238 case ConditionKind.skillLevelAtLeast:
239 case ConditionKind.skillLevelAtLeast:
239 return (ctx.skillLevel?.(condition.skillId) ?? 1) >= skillRequirementThreshold(condition);
240 return (ctx.skillLevel?.(condition.skillId) ?? 1) >= skillRequirementThreshold(condition);
240 case ConditionKind.killCount:
241 case ConditionKind.killCount:
242 case ConditionKind.killMobFromSpawner:
241 return (ctx.killCount?.(condition) ?? 0) >= Math.max(1, Number(condition.count) || 1);
243 return (ctx.killCount?.(condition) ?? 0) >= Math.max(1, Number(condition.count) || 1);
242 case ConditionKind.interactBlock:
244 case ConditionKind.interactBlock:
243 return sameDimension(condition, ctx) && !!ctx.interactBlockDone?.(condition);
245 return sameDimension(condition, ctx) && !!ctx.interactBlockDone?.(condition);
shared/quests/objectiveProgress.js +2 −2
@@ -1,7 +1,7 @@
1 1 import { ConditionKind, skillRequirementThreshold } from "./conditions.js";
2 2
3 3 /**
4 * Progress for countable objective conditions (hasItem, killCount, skillLevelAtLeast).
4 * Progress for countable objective conditions (hasItem, killCount, killMobFromSpawner, skillLevelAtLeast).
5 5 * Uses the first non-negated countable clause in the ConditionSet.
6 6 * @returns {{ current: number, required: number } | null}
7 7 */
@@ -33,7 +33,7 @@ export function countableConditionProgress (condition, ctx)
33 33 const current = Math.max(0, ctx.countItem?.(condition.itemId) ?? 0);
34 34 return { current: Math.min(current, required), required };
35 35 }
36 if (kind === ConditionKind.killCount)
36 if (kind === ConditionKind.killCount || kind === ConditionKind.killMobFromSpawner)
37 37 {
38 38 const required = Math.max(1, Number(condition.count) || 1);
39 39 const current = Math.max(0, ctx.killCount?.(condition) ?? 0);
@@ -1,7 +1,7 @@
1import { ConditionKind, skillRequirementThreshold } from "./conditions.js";
1import { ConditionKind, skillRequirementThreshold } from "./conditions.js";
2
2
3/**
3/**
4 * Progress for countable objective conditions (hasItem, killCount, skillLevelAtLeast).
4 * Progress for countable objective conditions (hasItem, killCount, killMobFromSpawner, skillLevelAtLeast).
5 * Uses the first non-negated countable clause in the ConditionSet.
5 * Uses the first non-negated countable clause in the ConditionSet.
6 * @returns {{ current: number, required: number } | null}
6 * @returns {{ current: number, required: number } | null}
7 */
7 */
@@ -33,7 +33,7 @@ export function countableConditionProgress (condition, ctx)
33 const current = Math.max(0, ctx.countItem?.(condition.itemId) ?? 0);
33 const current = Math.max(0, ctx.countItem?.(condition.itemId) ?? 0);
34 return { current: Math.min(current, required), required };
34 return { current: Math.min(current, required), required };
35 }
35 }
36 if (kind === ConditionKind.killCount)
36 if (kind === ConditionKind.killCount || kind === ConditionKind.killMobFromSpawner)
37 {
37 {
38 const required = Math.max(1, Number(condition.count) || 1);
38 const required = Math.max(1, Number(condition.count) || 1);
39 const current = Math.max(0, ctx.killCount?.(condition) ?? 0);
39 const current = Math.max(0, ctx.killCount?.(condition) ?? 0);