BlueGit

timfa questward

Improve zoom/editor performance and fix shopkeeper defaults.

Relayout chunks on zoom instead of rebaking, batch wheel zoom and chunk rebuilds, default shopkeepers to buysItems so paper and other goods can be sold, and preset town guard spawner level/bounty/equipment.

timfa Tim Falken · pushed by timfa

Authored 2026-08-28 · 2 months ago

Hash
aa1251ac3fb3a49d5ae1b0f11e6812306cee23f0
Parent
2bf77fcf
6 files changed +242 −63
client/src/editor/main.js +16 −3
@@ -734,9 +734,22 @@ function zoomEditor (direction)
734 734 { return; }
735 735 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
736 736 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
737 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
738 useNearestNeighbour(scene, game.images);
739 frameNeighborhood();
737 scheduleEditorZoom();
738 }
739
740 let editorZoomRaf = 0;
741 function scheduleEditorZoom ()
742 {
743 if (editorZoomRaf)
744 { return; }
745 editorZoomRaf = requestAnimationFrame(() =>
746 {
747 editorZoomRaf = 0;
748 if (!view)
749 { return; }
750 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
751 frameNeighborhood();
752 });
740 753 }
741 754
742 755 function requestChunks (coords)
@@ -734,9 +734,22 @@ function zoomEditor (direction)
734 { return; }
734 { return; }
735 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
735 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
736 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
736 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
737 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
737 scheduleEditorZoom();
738 useNearestNeighbour(scene, game.images);
738}
739 frameNeighborhood();
739
740let editorZoomRaf = 0;
741function scheduleEditorZoom ()
742{
743 if (editorZoomRaf)
744 { return; }
745 editorZoomRaf = requestAnimationFrame(() =>
746 {
747 editorZoomRaf = 0;
748 if (!view)
749 { return; }
750 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
751 frameNeighborhood();
752 });
740}
753}
741
754
742function requestChunks (coords)
755function requestChunks (coords)
client/src/play/main.js +40 −28
@@ -67,6 +67,8 @@ let toasts;
67 67 let questsUi;
68 68 let dialogueUi;
69 69 let shop;
70 let playZoomRaf = 0;
71 let playZoomDelta = 0;
70 72 let market;
71 73 let bounty;
72 74 let barber;
@@ -955,8 +957,18 @@ function startPlay (payload)
955 957 {
956 958 if (!playing || uiBlocked())
957 959 { return; }
958 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
959 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
960 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
961 if (playZoomRaf)
962 { return; }
963 playZoomRaf = requestAnimationFrame(() =>
964 {
965 playZoomRaf = 0;
966 if (!view || !playZoomDelta)
967 { return; }
968 view.setZoom(view.zoom + playZoomDelta);
969 playZoomDelta = 0;
970 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
971 });
960 972 }, { passive: true });
961 973 scene.canvas.addEventListener("contextmenu", (event) =>
962 974 {
@@ -1401,39 +1413,39 @@ async function main ()
1401 1413 crafting?.refresh();
1402 1414 break;
1403 1415 case MessageType.combatHit:
1404 {
1405 const applyHit = () =>
1406 1416 {
1407 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1408 view?.flashDamage(message.targetId);
1409 view?.spawnDamageNumber(message.targetId, message.damage);
1410 if (message.targetId === view?.localEntityId)
1417 const applyHit = () =>
1411 1418 {
1412 healthUi?.apply({
1413 current: message.health,
1414 max: message.maxHealth
1415 });
1416 }
1417 };
1418 if (!view?.deferCombatHit?.(message, applyHit))
1419 { applyHit(); }
1420 break;
1421 }
1419 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1420 view?.flashDamage(message.targetId);
1421 view?.spawnDamageNumber(message.targetId, message.damage);
1422 if (message.targetId === view?.localEntityId)
1423 {
1424 healthUi?.apply({
1425 current: message.health,
1426 max: message.maxHealth
1427 });
1428 }
1429 };
1430 if (!view?.deferCombatHit?.(message, applyHit))
1431 { applyHit(); }
1432 break;
1433 }
1422 1434 case MessageType.combatMiss:
1423 1435 view?.markProjectileMiss?.(message);
1424 1436 break;
1425 1437 case MessageType.combatBlock:
1426 {
1427 const applyBlock = () =>
1428 1438 {
1429 view?.flashDamage(message.targetId);
1430 if (message.health != null)
1431 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1432 };
1433 if (!view?.deferCombatHit?.(message, applyBlock))
1434 { applyBlock(); }
1435 break;
1436 }
1439 const applyBlock = () =>
1440 {
1441 view?.flashDamage(message.targetId);
1442 if (message.health != null)
1443 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1444 };
1445 if (!view?.deferCombatHit?.(message, applyBlock))
1446 { applyBlock(); }
1447 break;
1448 }
1437 1449 case MessageType.entityHealth:
1438 1450 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1439 1451 if (message.entityId === view?.localEntityId)
@@ -67,6 +67,8 @@ let toasts;
67let questsUi;
67let questsUi;
68let dialogueUi;
68let dialogueUi;
69let shop;
69let shop;
70let playZoomRaf = 0;
71let playZoomDelta = 0;
70let market;
72let market;
71let bounty;
73let bounty;
72let barber;
74let barber;
@@ -955,8 +957,18 @@ function startPlay (payload)
955 {
957 {
956 if (!playing || uiBlocked())
958 if (!playing || uiBlocked())
957 { return; }
959 { return; }
958 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
960 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
959 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
961 if (playZoomRaf)
962 { return; }
963 playZoomRaf = requestAnimationFrame(() =>
964 {
965 playZoomRaf = 0;
966 if (!view || !playZoomDelta)
967 { return; }
968 view.setZoom(view.zoom + playZoomDelta);
969 playZoomDelta = 0;
970 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
971 });
960 }, { passive: true });
972 }, { passive: true });
961 scene.canvas.addEventListener("contextmenu", (event) =>
973 scene.canvas.addEventListener("contextmenu", (event) =>
962 {
974 {
@@ -1401,39 +1413,39 @@ async function main ()
1401 crafting?.refresh();
1413 crafting?.refresh();
1402 break;
1414 break;
1403 case MessageType.combatHit:
1415 case MessageType.combatHit:
1404 {
1405 const applyHit = () =>
1406 {
1416 {
1407 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1417 const applyHit = () =>
1408 view?.flashDamage(message.targetId);
1409 view?.spawnDamageNumber(message.targetId, message.damage);
1410 if (message.targetId === view?.localEntityId)
1411 {
1418 {
1412 healthUi?.apply({
1419 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1413 current: message.health,
1420 view?.flashDamage(message.targetId);
1414 max: message.maxHealth
1421 view?.spawnDamageNumber(message.targetId, message.damage);
1415 });
1422 if (message.targetId === view?.localEntityId)
1416 }
1423 {
1417 };
1424 healthUi?.apply({
1418 if (!view?.deferCombatHit?.(message, applyHit))
1425 current: message.health,
1419 { applyHit(); }
1426 max: message.maxHealth
1420 break;
1427 });
1421 }
1428 }
1429 };
1430 if (!view?.deferCombatHit?.(message, applyHit))
1431 { applyHit(); }
1432 break;
1433 }
1422 case MessageType.combatMiss:
1434 case MessageType.combatMiss:
1423 view?.markProjectileMiss?.(message);
1435 view?.markProjectileMiss?.(message);
1424 break;
1436 break;
1425 case MessageType.combatBlock:
1437 case MessageType.combatBlock:
1426 {
1427 const applyBlock = () =>
1428 {
1438 {
1429 view?.flashDamage(message.targetId);
1439 const applyBlock = () =>
1430 if (message.health != null)
1440 {
1431 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1441 view?.flashDamage(message.targetId);
1432 };
1442 if (message.health != null)
1433 if (!view?.deferCombatHit?.(message, applyBlock))
1443 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1434 { applyBlock(); }
1444 };
1435 break;
1445 if (!view?.deferCombatHit?.(message, applyBlock))
1436 }
1446 { applyBlock(); }
1447 break;
1448 }
1437 case MessageType.entityHealth:
1449 case MessageType.entityHealth:
1438 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1450 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1439 if (message.entityId === view?.localEntityId)
1451 if (message.entityId === view?.localEntityId)
client/src/render/worldView.js +76 −28
@@ -7,13 +7,15 @@ import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb }
7 7 import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8 8 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9 9 import { bakeChunkAtlases } from "./chunkBake.js";
10 import {
10 import
11 {
11 12 frameworkImageFromCanvas,
12 13 invalidateCanvasTexture
13 14 } from "./canvasSprite.js";
14 import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15 import { setNearestFilter } from "./sprites.js";
15 16 import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16 import {
17 import
18 {
17 19 OVERWORLD_ID,
18 20 normalizeDimensionId,
19 21 normalizeLightingMode,
@@ -365,7 +367,10 @@ function getTightFitLitSpriteShader ()
365 367
366 368 export class WorldView
367 369 {
368 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
370 #chunkRebuildKeys = new Set();
371 #chunkRebuildRaf = 0;
372
373 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
369 374 {
370 375 this.game = game;
371 376 this.scene = scene;
@@ -1118,10 +1123,7 @@ export class WorldView
1118 1123 const max = limits.max ?? 4;
1119 1124 this.zoom = Math.min(max, Math.max(min, zoom));
1120 1125 for (const snapshot of this.chunks.values())
1121 {
1122 this.#layoutBakedChunk(snapshot);
1123 this.#rebuildChunk(snapshot);
1124 }
1126 { this.#relayoutChunk(snapshot); }
1125 1127 const size = this.tileSize();
1126 1128 for (const entity of this.entities.values())
1127 1129 {
@@ -1140,11 +1142,9 @@ export class WorldView
1140 1142 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1141 1143 }
1142 1144 this.#rebuildAllEdges();
1143 this.#redrawPreview();
1144 1145 this.#relayoutEditorSpawners();
1145 1146 this.#relayoutSpawnRangeHighlight();
1146 1147 this.#relayoutSpellTargetHighlight();
1147 applyNearestToAllTextures(this.scene, this.game.images);
1148 1148 }
1149 1149
1150 1150 tileSize ()
@@ -1573,7 +1573,7 @@ export class WorldView
1573 1573 { snapshot.blocks[index] = block; }
1574 1574 if (light !== undefined)
1575 1575 { snapshot.light[index] = light; }
1576 this.#rebuildChunk(snapshot);
1576 this.#scheduleChunkRebuild(snapshot);
1577 1577 }
1578 1578
1579 1579 /**
@@ -1741,31 +1741,30 @@ export class WorldView
1741 1741
1742 1742 setTilePreview (tileX, tileY, override)
1743 1743 {
1744 const next = { tileX, tileY, ...override };
1745 if (this.#previewEqual(this.preview, next))
1746 { return; }
1744 1747 const previous = this.preview;
1745 this.preview = { tileX, tileY, ...override };
1748 this.preview = next;
1746 1749 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1747 1750 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1748 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1749 if (snapshot)
1750 { this.#rebuildChunk(snapshot); }
1751 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
1751 1752 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1752 1753 {
1753 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1754 if (prevSnapshot && prevSnapshot !== snapshot)
1755 { this.#rebuildChunk(prevSnapshot); }
1754 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
1755 if (prevKey !== `${chunkX},${chunkY}`)
1756 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
1756 1757 }
1757 1758 }
1758 1759
1759 1760 clearTilePreview ()
1760 1761 {
1762 if (!this.preview)
1763 { return; }
1761 1764 const previous = this.preview;
1762 1765 this.preview = null;
1763 if (previous)
1764 {
1765 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1766 if (snapshot)
1767 { this.#rebuildChunk(snapshot); }
1768 }
1766 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1767 this.#scheduleChunkRebuild(snapshot);
1769 1768 }
1770 1769
1771 1770 #lerpMs (gait)
@@ -2460,9 +2459,22 @@ export class WorldView
2460 2459 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2461 2460 {
2462 2461 this.#bakeAndPlaceChunk(snapshot);
2462 this.#relayoutChunkTiles(snapshot);
2463 if (this.softTerrain && refreshSoftNeighbors)
2464 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2465 }
2466
2467 #relayoutChunk (snapshot)
2468 {
2469 this.#layoutBakedChunk(snapshot);
2470 this.#relayoutChunkTiles(snapshot);
2471 }
2472
2473 #relayoutChunkTiles (snapshot)
2474 {
2475 const baked = this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`);
2463 2476 const tall = new Set(
2464 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
2465 .map((entry) => `${entry.tileX},${entry.tileY}`)
2477 (baked?.tallBlocks ?? []).map((entry) => `${entry.tileX},${entry.tileY}`)
2466 2478 );
2467 2479 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2468 2480 {
@@ -2473,8 +2485,44 @@ export class WorldView
2473 2485 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2474 2486 }
2475 2487 }
2476 if (this.softTerrain && refreshSoftNeighbors)
2477 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2488 }
2489
2490 #scheduleChunkRebuild (snapshot)
2491 {
2492 if (!snapshot)
2493 { return; }
2494 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2495 if (this.#chunkRebuildRaf)
2496 { return; }
2497 this.#chunkRebuildRaf = requestAnimationFrame(() =>
2498 {
2499 this.#chunkRebuildRaf = 0;
2500 const keys = [...this.#chunkRebuildKeys];
2501 this.#chunkRebuildKeys.clear();
2502 for (const key of keys)
2503 {
2504 const snap = this.chunks.get(key);
2505 if (snap)
2506 { this.#rebuildChunk(snap); }
2507 }
2508 });
2509 }
2510
2511 #previewEqual (a, b)
2512 {
2513 if (a === b)
2514 { return true; }
2515 if (!a || !b)
2516 { return false; }
2517 return a.tileX === b.tileX
2518 && a.tileY === b.tileY
2519 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
2520 && this.#previewPart(a.block) === this.#previewPart(b.block);
2521 }
2522
2523 #previewPart (value)
2524 {
2525 return value === undefined ? undefined : JSON.stringify(value);
2478 2526 }
2479 2527
2480 2528 #rebuildSoftTerrainNeighborChunks (snapshot)
@@ -7,13 +7,15 @@ import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb }
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
10import {
10import
11{
11 frameworkImageFromCanvas,
12 frameworkImageFromCanvas,
12 invalidateCanvasTexture
13 invalidateCanvasTexture
13} from "./canvasSprite.js";
14} from "./canvasSprite.js";
14import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15import { setNearestFilter } from "./sprites.js";
15import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16import {
17import
18{
17 OVERWORLD_ID,
19 OVERWORLD_ID,
18 normalizeDimensionId,
20 normalizeDimensionId,
19 normalizeLightingMode,
21 normalizeLightingMode,
@@ -365,7 +367,10 @@ function getTightFitLitSpriteShader ()
365
367
366export class WorldView
368export class WorldView
367{
369{
368 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
370 #chunkRebuildKeys = new Set();
371 #chunkRebuildRaf = 0;
372
373 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
369 {
374 {
370 this.game = game;
375 this.game = game;
371 this.scene = scene;
376 this.scene = scene;
@@ -1118,10 +1123,7 @@ export class WorldView
1118 const max = limits.max ?? 4;
1123 const max = limits.max ?? 4;
1119 this.zoom = Math.min(max, Math.max(min, zoom));
1124 this.zoom = Math.min(max, Math.max(min, zoom));
1120 for (const snapshot of this.chunks.values())
1125 for (const snapshot of this.chunks.values())
1121 {
1126 { this.#relayoutChunk(snapshot); }
1122 this.#layoutBakedChunk(snapshot);
1123 this.#rebuildChunk(snapshot);
1124 }
1125 const size = this.tileSize();
1127 const size = this.tileSize();
1126 for (const entity of this.entities.values())
1128 for (const entity of this.entities.values())
1127 {
1129 {
@@ -1140,11 +1142,9 @@ export class WorldView
1140 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1142 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1141 }
1143 }
1142 this.#rebuildAllEdges();
1144 this.#rebuildAllEdges();
1143 this.#redrawPreview();
1144 this.#relayoutEditorSpawners();
1145 this.#relayoutEditorSpawners();
1145 this.#relayoutSpawnRangeHighlight();
1146 this.#relayoutSpawnRangeHighlight();
1146 this.#relayoutSpellTargetHighlight();
1147 this.#relayoutSpellTargetHighlight();
1147 applyNearestToAllTextures(this.scene, this.game.images);
1148 }
1148 }
1149
1149
1150 tileSize ()
1150 tileSize ()
@@ -1573,7 +1573,7 @@ export class WorldView
1573 { snapshot.blocks[index] = block; }
1573 { snapshot.blocks[index] = block; }
1574 if (light !== undefined)
1574 if (light !== undefined)
1575 { snapshot.light[index] = light; }
1575 { snapshot.light[index] = light; }
1576 this.#rebuildChunk(snapshot);
1576 this.#scheduleChunkRebuild(snapshot);
1577 }
1577 }
1578
1578
1579 /**
1579 /**
@@ -1741,31 +1741,30 @@ export class WorldView
1741
1741
1742 setTilePreview (tileX, tileY, override)
1742 setTilePreview (tileX, tileY, override)
1743 {
1743 {
1744 const next = { tileX, tileY, ...override };
1745 if (this.#previewEqual(this.preview, next))
1746 { return; }
1744 const previous = this.preview;
1747 const previous = this.preview;
1745 this.preview = { tileX, tileY, ...override };
1748 this.preview = next;
1746 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1749 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1747 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1750 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1748 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1751 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
1749 if (snapshot)
1750 { this.#rebuildChunk(snapshot); }
1751 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1752 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1752 {
1753 {
1753 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1754 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
1754 if (prevSnapshot && prevSnapshot !== snapshot)
1755 if (prevKey !== `${chunkX},${chunkY}`)
1755 { this.#rebuildChunk(prevSnapshot); }
1756 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
1756 }
1757 }
1757 }
1758 }
1758
1759
1759 clearTilePreview ()
1760 clearTilePreview ()
1760 {
1761 {
1762 if (!this.preview)
1763 { return; }
1761 const previous = this.preview;
1764 const previous = this.preview;
1762 this.preview = null;
1765 this.preview = null;
1763 if (previous)
1766 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1764 {
1767 this.#scheduleChunkRebuild(snapshot);
1765 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1766 if (snapshot)
1767 { this.#rebuildChunk(snapshot); }
1768 }
1769 }
1768 }
1770
1769
1771 #lerpMs (gait)
1770 #lerpMs (gait)
@@ -2460,9 +2459,22 @@ export class WorldView
2460 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2459 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2461 {
2460 {
2462 this.#bakeAndPlaceChunk(snapshot);
2461 this.#bakeAndPlaceChunk(snapshot);
2462 this.#relayoutChunkTiles(snapshot);
2463 if (this.softTerrain && refreshSoftNeighbors)
2464 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2465 }
2466
2467 #relayoutChunk (snapshot)
2468 {
2469 this.#layoutBakedChunk(snapshot);
2470 this.#relayoutChunkTiles(snapshot);
2471 }
2472
2473 #relayoutChunkTiles (snapshot)
2474 {
2475 const baked = this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`);
2463 const tall = new Set(
2476 const tall = new Set(
2464 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
2477 (baked?.tallBlocks ?? []).map((entry) => `${entry.tileX},${entry.tileY}`)
2465 .map((entry) => `${entry.tileX},${entry.tileY}`)
2466 );
2478 );
2467 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2479 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2468 {
2480 {
@@ -2473,8 +2485,44 @@ export class WorldView
2473 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2485 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2474 }
2486 }
2475 }
2487 }
2476 if (this.softTerrain && refreshSoftNeighbors)
2488 }
2477 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2489
2490 #scheduleChunkRebuild (snapshot)
2491 {
2492 if (!snapshot)
2493 { return; }
2494 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2495 if (this.#chunkRebuildRaf)
2496 { return; }
2497 this.#chunkRebuildRaf = requestAnimationFrame(() =>
2498 {
2499 this.#chunkRebuildRaf = 0;
2500 const keys = [...this.#chunkRebuildKeys];
2501 this.#chunkRebuildKeys.clear();
2502 for (const key of keys)
2503 {
2504 const snap = this.chunks.get(key);
2505 if (snap)
2506 { this.#rebuildChunk(snap); }
2507 }
2508 });
2509 }
2510
2511 #previewEqual (a, b)
2512 {
2513 if (a === b)
2514 { return true; }
2515 if (!a || !b)
2516 { return false; }
2517 return a.tileX === b.tileX
2518 && a.tileY === b.tileY
2519 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
2520 && this.#previewPart(a.block) === this.#previewPart(b.block);
2521 }
2522
2523 #previewPart (value)
2524 {
2525 return value === undefined ? undefined : JSON.stringify(value);
2478 }
2526 }
2479
2527
2480 #rebuildSoftTerrainNeighborChunks (snapshot)
2528 #rebuildSoftTerrainNeighborChunks (snapshot)
server/tests/shop.test.js +74 −0
@@ -126,6 +126,80 @@ test("humanoid spawner config keeps sex equipment sells quantities and buysItems
126 126 assert.equal(config.maxAlive, 1);
127 127 });
128 128
129 test("shopkeeper with default buysItems accepts paper from the player", () =>
130 {
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const data = createEmptyChunkData();
135 data.open = true;
136 data.spawners = [{
137 localX: 9,
138 localY: 8,
139 config: {
140 mobTypeId: MobId.humanoid,
141 maxAlive: 1,
142 spawnRangeTiles: 0,
143 maxWanderRangeTiles: 0,
144 displayName: "Stationer"
145 }
146 }];
147 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
148 harness.simulation.reloadWorld();
149
150 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
151 const slots = emptySlots(INVENTORY_SLOTS);
152 slots[0] = { itemId: ItemId.paper, quantity: 3 };
153 harness.stateDb.saveBag(character.character_id, {
154 inventory: slots,
155 equipment: emptyEquipment(),
156 vault: [],
157 vaultReserved: []
158 });
159 const playerId = harness.simulation.spawnCharacter(1, character);
160 harness.simulation.step();
161 harness.advance(50);
162 harness.simulation.step();
163
164 const record = harness.simulation.entityRecord(playerId);
165 const worker = harness.simulation.workers[record.workerId];
166 let npcId = null;
167 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
168 {
169 if (entity.creature.mobTypeId === MobId.humanoid)
170 {
171 npcId = entity.entityId;
172 break;
173 }
174 }
175 assert.ok(npcId);
176 const npcHandle = worker.world.ecs.handleOf(npcId);
177 const shop = worker.world.ecs.get(npcHandle, Component.shop);
178 assert.equal(shop.buysItems, true);
179 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
180 const playerHandle = worker.world.ecs.handleOf(playerId);
181 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
182 playerPos.tileX = npcPos.tileX;
183 playerPos.tileY = npcPos.tileY;
184
185 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
186 harness.simulation.enqueue(1, {
187 type: "sell-to-shop",
188 characterId: character.character_id,
189 npcEntityId: npcId,
190 slotIndex: 0,
191 quantity: 1
192 });
193 const sold = harness.simulation.step();
194 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
195 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
196 assert.equal(inv.slots[0]?.quantity, 2);
197 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.paper));
198 }
199 finally
200 { harness.close(); }
201 });
202
129 203 test("humanoid spawner equipment can store clothing dye color", () =>
130 204 {
131 205 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
@@ -126,6 +126,80 @@ test("humanoid spawner config keeps sex equipment sells quantities and buysItems
126 assert.equal(config.maxAlive, 1);
126 assert.equal(config.maxAlive, 1);
127});
127});
128
128
129test("shopkeeper with default buysItems accepts paper from the player", () =>
130{
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const data = createEmptyChunkData();
135 data.open = true;
136 data.spawners = [{
137 localX: 9,
138 localY: 8,
139 config: {
140 mobTypeId: MobId.humanoid,
141 maxAlive: 1,
142 spawnRangeTiles: 0,
143 maxWanderRangeTiles: 0,
144 displayName: "Stationer"
145 }
146 }];
147 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
148 harness.simulation.reloadWorld();
149
150 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
151 const slots = emptySlots(INVENTORY_SLOTS);
152 slots[0] = { itemId: ItemId.paper, quantity: 3 };
153 harness.stateDb.saveBag(character.character_id, {
154 inventory: slots,
155 equipment: emptyEquipment(),
156 vault: [],
157 vaultReserved: []
158 });
159 const playerId = harness.simulation.spawnCharacter(1, character);
160 harness.simulation.step();
161 harness.advance(50);
162 harness.simulation.step();
163
164 const record = harness.simulation.entityRecord(playerId);
165 const worker = harness.simulation.workers[record.workerId];
166 let npcId = null;
167 for (const entity of worker.world.ecs.query(Component.shop, Component.creature))
168 {
169 if (entity.creature.mobTypeId === MobId.humanoid)
170 {
171 npcId = entity.entityId;
172 break;
173 }
174 }
175 assert.ok(npcId);
176 const npcHandle = worker.world.ecs.handleOf(npcId);
177 const shop = worker.world.ecs.get(npcHandle, Component.shop);
178 assert.equal(shop.buysItems, true);
179 const npcPos = worker.world.ecs.get(npcHandle, Component.position);
180 const playerHandle = worker.world.ecs.handleOf(playerId);
181 const playerPos = worker.world.ecs.get(playerHandle, Component.position);
182 playerPos.tileX = npcPos.tileX;
183 playerPos.tileY = npcPos.tileY;
184
185 const beforeCoins = countCoinsInSlots(worker.world.ecs.get(playerHandle, Component.inventory).slots);
186 harness.simulation.enqueue(1, {
187 type: "sell-to-shop",
188 characterId: character.character_id,
189 npcEntityId: npcId,
190 slotIndex: 0,
191 quantity: 1
192 });
193 const sold = harness.simulation.step();
194 assert.equal(sold.events.some((event) => event.type === "command-error"), false, JSON.stringify(sold.events));
195 const inv = worker.world.ecs.get(playerHandle, Component.inventory);
196 assert.equal(inv.slots[0]?.quantity, 2);
197 assert.ok(countCoinsInSlots(inv.slots) >= beforeCoins + shopBuyFromPlayerPrice(ItemId.paper));
198 }
199 finally
200 { harness.close(); }
201});
202
129test("humanoid spawner equipment can store clothing dye color", () =>
203test("humanoid spawner equipment can store clothing dye color", () =>
130{
204{
131 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
205 const dyeColor = { r: 0.2, g: 0.4, b: 0.8 };
server/tests/spawner-bounty.test.js +20 −0
@@ -23,6 +23,26 @@ test("spawner config defaults bounty 0 and level 1", () =>
23 23 assert.deepEqual(config.spells, []);
24 24 });
25 25
26 test("town guard spawner defaults level, bounty, and equipment", () =>
27 {
28 const config = normalizeSpawnerConfig({ mobTypeId: MobId.townGuard }, "guard-1");
29 assert.equal(config.level, 30);
30 assert.equal(config.bounty, 500);
31 assert.equal(config.equipment.head, 100);
32 assert.equal(config.equipment.chest, 97);
33 assert.equal(config.equipment.legs, 92);
34 assert.equal(config.equipment.boots, 99);
35 assert.equal(config.equipment.weapon, 245);
36 });
37
38 test("shopkeeper spawners buy from players by default", () =>
39 {
40 const config = normalizeSpawnerConfig({ mobTypeId: MobId.humanoid }, "shop-1");
41 assert.equal(config.buysItems, true);
42 const guard = normalizeSpawnerConfig({ mobTypeId: MobId.townGuard }, "guard-1");
43 assert.equal(guard.buysItems, false);
44 });
45
26 46 test("spawner config keeps bounty, level, and spells", () =>
27 47 {
28 48 const config = normalizeSpawnerConfig({
@@ -23,6 +23,26 @@ test("spawner config defaults bounty 0 and level 1", () =>
23 assert.deepEqual(config.spells, []);
23 assert.deepEqual(config.spells, []);
24});
24});
25
25
26test("town guard spawner defaults level, bounty, and equipment", () =>
27{
28 const config = normalizeSpawnerConfig({ mobTypeId: MobId.townGuard }, "guard-1");
29 assert.equal(config.level, 30);
30 assert.equal(config.bounty, 500);
31 assert.equal(config.equipment.head, 100);
32 assert.equal(config.equipment.chest, 97);
33 assert.equal(config.equipment.legs, 92);
34 assert.equal(config.equipment.boots, 99);
35 assert.equal(config.equipment.weapon, 245);
36});
37
38test("shopkeeper spawners buy from players by default", () =>
39{
40 const config = normalizeSpawnerConfig({ mobTypeId: MobId.humanoid }, "shop-1");
41 assert.equal(config.buysItems, true);
42 const guard = normalizeSpawnerConfig({ mobTypeId: MobId.townGuard }, "guard-1");
43 assert.equal(guard.buysItems, false);
44});
45
26test("spawner config keeps bounty, level, and spells", () =>
46test("spawner config keeps bounty, level, and spells", () =>
27{
47{
28 const config = normalizeSpawnerConfig({
48 const config = normalizeSpawnerConfig({
shared/definitions/mobs.js +16 −4
@@ -2,6 +2,8 @@ import { spriteImageName } from "./tileSprites.js";
2 2 import { centralExchangeStaffCount } from "../market/exchange.js";
3 3 import { LeatherItemId } from "./leatherItems.js";
4 4 import { RangedItemId } from "./rangedItems.js";
5 import { ArmourItemId } from "./armourItems.js";
6 import { WoodItemId } from "./woodItems.js";
5 7 import { ItemId } from "./items.js";
6 8
7 9 export const MobId = Object.freeze({
@@ -245,6 +247,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
245 247 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
246 248 const townGuard = mobTypeId === MobId.townGuard;
247 249 const centralExchange = mobTypeId === MobId.centralExchange;
250 const shopkeeper = mobTypeId === MobId.humanoid;
248 251 const bodyNpc = humanoid || townGuard || centralExchange;
249 252 return {
250 253 spawnerId,
@@ -254,16 +257,25 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
254 257 : (bodyNpc ? 1 : 3),
255 258 spawnRangeTiles: bodyNpc ? 1 : 4,
256 259 maxWanderRangeTiles: bodyNpc ? 1 : 8,
257 level: 1,
258 bounty: 0,
260 level: townGuard ? 30 : 1,
261 bounty: townGuard ? 500 : 0,
259 262 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
260 263 aggressive: false,
261 264 sex: "male",
262 265 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
263 equipment: emptySpawnerEquipment(),
266 equipment: townGuard
267 ? {
268 head: ArmourItemId.ironHelmet,
269 chest: ArmourItemId.ironChestplate,
270 legs: ArmourItemId.bronzeGreaves,
271 boots: ArmourItemId.ironBoots,
272 weapon: WoodItemId.oakQuarterstaff,
273 offhand: null
274 }
275 : emptySpawnerEquipment(),
264 276 sells: [],
265 277 spells: [],
266 buysItems: false,
278 buysItems: shopkeeper,
267 279 hiddenDiscount: 0.9,
268 280 centralExchange,
269 281 townGuard,
@@ -2,6 +2,8 @@ import { spriteImageName } from "./tileSprites.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
3import { LeatherItemId } from "./leatherItems.js";
3import { LeatherItemId } from "./leatherItems.js";
4import { RangedItemId } from "./rangedItems.js";
4import { RangedItemId } from "./rangedItems.js";
5import { ArmourItemId } from "./armourItems.js";
6import { WoodItemId } from "./woodItems.js";
5import { ItemId } from "./items.js";
7import { ItemId } from "./items.js";
6
8
7export const MobId = Object.freeze({
9export const MobId = Object.freeze({
@@ -245,6 +247,7 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
245 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
247 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
246 const townGuard = mobTypeId === MobId.townGuard;
248 const townGuard = mobTypeId === MobId.townGuard;
247 const centralExchange = mobTypeId === MobId.centralExchange;
249 const centralExchange = mobTypeId === MobId.centralExchange;
250 const shopkeeper = mobTypeId === MobId.humanoid;
248 const bodyNpc = humanoid || townGuard || centralExchange;
251 const bodyNpc = humanoid || townGuard || centralExchange;
249 return {
252 return {
250 spawnerId,
253 spawnerId,
@@ -254,16 +257,25 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
254 : (bodyNpc ? 1 : 3),
257 : (bodyNpc ? 1 : 3),
255 spawnRangeTiles: bodyNpc ? 1 : 4,
258 spawnRangeTiles: bodyNpc ? 1 : 4,
256 maxWanderRangeTiles: bodyNpc ? 1 : 8,
259 maxWanderRangeTiles: bodyNpc ? 1 : 8,
257 level: 1,
260 level: townGuard ? 30 : 1,
258 bounty: 0,
261 bounty: townGuard ? 500 : 0,
259 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
262 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
260 aggressive: false,
263 aggressive: false,
261 sex: "male",
264 sex: "male",
262 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
265 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
263 equipment: emptySpawnerEquipment(),
266 equipment: townGuard
267 ? {
268 head: ArmourItemId.ironHelmet,
269 chest: ArmourItemId.ironChestplate,
270 legs: ArmourItemId.bronzeGreaves,
271 boots: ArmourItemId.ironBoots,
272 weapon: WoodItemId.oakQuarterstaff,
273 offhand: null
274 }
275 : emptySpawnerEquipment(),
264 sells: [],
276 sells: [],
265 spells: [],
277 spells: [],
266 buysItems: false,
278 buysItems: shopkeeper,
267 hiddenDiscount: 0.9,
279 hiddenDiscount: 0.9,
268 centralExchange,
280 centralExchange,
269 townGuard,
281 townGuard,