BlueGit

timfa questward

Add melee combat, follow, chunk bake, and courier pigeon prep.

Ship stick melee auto-attack with engage/retaliate, context-menu Follow that reuses the target trail, client chunk atlases for immobile tiles, and rename ambient doves into untargetable courier pigeons.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
b33181e8d3331a0647895018ee83ecf8913148e6
Parent
4874d49c
32 files changed +2723 −308
client/assets/fx/melee-swipe/melee-swipe.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/rat/rat.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/doves/dove/dove-flying.png client/assets/pigeons/pigeon/pigeon-flying.png renamed +0 −0
client/editor.html +1 −1
@@ -36,7 +36,7 @@
36 36 </div>
37 37 <div id="spawner-config">
38 38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option></select></label>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option><option value="rat">Rat</option></select></label>
40 40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
42 42 </div>
@@ -36,7 +36,7 @@
36 </div>
36 </div>
37 <div id="spawner-config">
37 <div id="spawner-config">
38 <p>Spawner (used when painting a new spawner tile)</p>
38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option></select></label>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option><option value="rat">Rat</option></select></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
42 </div>
42 </div>
client/scripts/write-placeholder-assets.mjs +8 −0
@@ -42,8 +42,16 @@ solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]
42 42 solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43 43 solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44 44 solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45 solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
45 46 overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46 47 overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47 48 torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
48 49
50 {
51 const image = makeRgba(24, 8, [0, 0, 0, 0]);
52 fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);
53 fillRect(image, 0, 3, 24, 2, [255, 245, 200, 255]);
54 writeRgbaPng(join(root, "fx", "melee-swipe", "melee-swipe.png"), 24, 8, image.pixels);
55 }
56
49 57 console.log("Wrote placeholder sprites under client/assets.");
@@ -42,8 +42,16 @@ solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]
42solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
42solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
43solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
44solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
45overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
48torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
48
49
50{
51 const image = makeRgba(24, 8, [0, 0, 0, 0]);
52 fillRect(image, 1, 2, 22, 4, [240, 220, 160, 220]);
53 fillRect(image, 0, 3, 24, 2, [255, 245, 200, 255]);
54 writeRgbaPng(join(root, "fx", "melee-swipe", "melee-swipe.png"), 24, 8, image.pixels);
55}
56
49console.log("Wrote placeholder sprites under client/assets.");
57console.log("Wrote placeholder sprites under client/assets.");
client/src/play/contextMenu.js added +53 −0
@@ -0,0 +1,53 @@
1 export function initContextMenu ({ root = document.body } = {})
2 {
3 const menu = document.createElement("div");
4 menu.id = "context-menu";
5 menu.hidden = true;
6 root.append(menu);
7
8 function hide ()
9 {
10 menu.hidden = true;
11 menu.replaceChildren();
12 }
13
14 document.addEventListener("mousedown", (event) =>
15 {
16 if (!menu.hidden && !menu.contains(event.target))
17 { hide(); }
18 });
19
20 window.addEventListener("blur", hide);
21 window.addEventListener("resize", hide);
22
23 return {
24 hide,
25 isOpen: () => !menu.hidden,
26 show (clientX, clientY, items)
27 {
28 menu.replaceChildren();
29 for (const item of items)
30 {
31 const button = document.createElement("button");
32 button.type = "button";
33 button.textContent = item.label;
34 button.addEventListener("click", (event) =>
35 {
36 event.preventDefault();
37 event.stopPropagation();
38 hide();
39 item.onSelect?.();
40 });
41 menu.append(button);
42 }
43 menu.hidden = false;
44 const pad = 8;
45 const width = menu.offsetWidth || 160;
46 const height = menu.offsetHeight || 80;
47 const left = Math.min(window.innerWidth - width - pad, Math.max(pad, clientX));
48 const top = Math.min(window.innerHeight - height - pad, Math.max(pad, clientY));
49 menu.style.left = `${left}px`;
50 menu.style.top = `${top}px`;
51 }
52 };
53 }
@@ -0,0 +1,53 @@
1export function initContextMenu ({ root = document.body } = {})
2{
3 const menu = document.createElement("div");
4 menu.id = "context-menu";
5 menu.hidden = true;
6 root.append(menu);
7
8 function hide ()
9 {
10 menu.hidden = true;
11 menu.replaceChildren();
12 }
13
14 document.addEventListener("mousedown", (event) =>
15 {
16 if (!menu.hidden && !menu.contains(event.target))
17 { hide(); }
18 });
19
20 window.addEventListener("blur", hide);
21 window.addEventListener("resize", hide);
22
23 return {
24 hide,
25 isOpen: () => !menu.hidden,
26 show (clientX, clientY, items)
27 {
28 menu.replaceChildren();
29 for (const item of items)
30 {
31 const button = document.createElement("button");
32 button.type = "button";
33 button.textContent = item.label;
34 button.addEventListener("click", (event) =>
35 {
36 event.preventDefault();
37 event.stopPropagation();
38 hide();
39 item.onSelect?.();
40 });
41 menu.append(button);
42 }
43 menu.hidden = false;
44 const pad = 8;
45 const width = menu.offsetWidth || 160;
46 const height = menu.offsetHeight || 80;
47 const left = Math.min(window.innerWidth - width - pad, Math.max(pad, clientX));
48 const top = Math.min(window.innerHeight - height - pad, Math.max(pad, clientY));
49 menu.style.left = `${left}px`;
50 menu.style.top = `${top}px`;
51 }
52 };
53}
client/src/play/main.js +128 −16
@@ -6,6 +6,7 @@ import { WorldView } from "../render/worldView.js";
6 6 import { initSocial } from "./social.js";
7 7 import { initChat } from "./chat.js";
8 8 import { initInventory } from "./inventory.js";
9 import { initContextMenu } from "./contextMenu.js";
9 10
10 11 const game = new Game();
11 12 const hud = document.getElementById("hud");
@@ -24,6 +25,7 @@ let catalog = { grounds: {}, blocks: {} };
24 25 let social;
25 26 let chat;
26 27 let inventory;
28 let contextMenu;
27 29
28 30 function showError (message)
29 31 {
@@ -59,6 +61,104 @@ function renderCharacters (characters)
59 61 }
60 62 }
61 63
64 function uiBlocked ()
65 {
66 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isOpen() || contextMenu?.isOpen());
67 }
68
69 function handleLeftClick (mouseX, mouseY)
70 {
71 const entity = view.entityAtScreen(mouseX, mouseY);
72 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
73 {
74 if (entity.characterId)
75 {
76 social.inspect(entity);
77 return;
78 }
79 if (entity.talkable)
80 {
81 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
82 return;
83 }
84 if (entity.hostile)
85 {
86 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
87 return;
88 }
89 }
90
91 const tile = view.screenToTile(mouseX, mouseY);
92 const local = view.entities.get(view.localEntityId);
93 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
94 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
95 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
96 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
97 { socket.send({ type: MessageType.openBank }); }
98 else
99 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
100 }
101
102 function handleRightClick (event, mouseX, mouseY)
103 {
104 event.preventDefault();
105 const entity = view.entityAtScreen(mouseX, mouseY);
106 const tile = view.screenToTile(mouseX, mouseY);
107 const items = [];
108
109 if (entity && entity.entityId !== view.localEntityId)
110 {
111 const targetName = entityLabel(entity);
112 items.push({
113 label: "Walk here",
114 onSelect: () => socket.send({ type: MessageType.moveTo, tileX: entity.tileX, tileY: entity.tileY })
115 });
116 items.push({
117 label: `Follow ${targetName}`,
118 onSelect: () => socket.send({ type: MessageType.follow, targetEntityId: entity.entityId })
119 });
120 if (!entity.untargetable)
121 {
122 if (entity.talkable)
123 {
124 items.push({
125 label: "Talk",
126 onSelect: () => socket.send({ type: MessageType.interact, targetEntityId: entity.entityId })
127 });
128 }
129 if (entity.characterId)
130 {
131 items.push({
132 label: `${targetName} info`,
133 onSelect: () => social.inspect(entity)
134 });
135 }
136 items.push({
137 label: `Attack ${targetName}`,
138 onSelect: () => socket.send({ type: MessageType.attack, targetEntityId: entity.entityId })
139 });
140 }
141 }
142 else
143 {
144 items.push({
145 label: "Walk here",
146 onSelect: () => socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY })
147 });
148 }
149
150 contextMenu.show(event.clientX, event.clientY, items);
151 }
152
153 function entityLabel (entity)
154 {
155 const first = (entity?.firstName ?? "").trim();
156 const last = (entity?.lastName ?? "").trim();
157 if (first && last)
158 { return `${first} ${last}`; }
159 return first || "target";
160 }
161
62 162 function startPlay (payload)
63 163 {
64 164 playing = true;
@@ -76,27 +176,13 @@ function startPlay (payload)
76 176 const ticker = new GameObject(0, 0, null, 10);
77 177 ticker.update = (dt) =>
78 178 {
79 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking() && !chat?.isBlocking() && !inventory?.isOpen())
179 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !uiBlocked())
80 180 {
81 181 const canvas = scene.canvas;
82 182 const rect = canvas.getBoundingClientRect();
83 183 const mouseX = GameInput.mousePosition.x - rect.left;
84 184 const mouseY = GameInput.mousePosition.y - rect.top;
85 const entity = view.entityAtScreen(mouseX, mouseY);
86 if (entity && entity.entityId !== view.localEntityId && entity.characterId)
87 { social.inspect(entity); }
88 else
89 {
90 const tile = view.screenToTile(mouseX, mouseY);
91 const local = view.entities.get(view.localEntityId);
92 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
93 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
94 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
95 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
96 { socket.send({ type: MessageType.openBank }); }
97 else
98 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
99 }
185 handleLeftClick(mouseX, mouseY);
100 186 }
101 187 if (GameInput.isPressed(82) && !chat?.isOpen())
102 188 {
@@ -125,6 +211,13 @@ function startPlay (payload)
125 211 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
126 212 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
127 213 }, { passive: true });
214 scene.canvas.addEventListener("contextmenu", (event) =>
215 {
216 if (!playing || uiBlocked())
217 { return; }
218 const rect = scene.canvas.getBoundingClientRect();
219 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
220 });
128 221 }
129 222 view.setSettings(payload.settings ?? view.settings);
130 223 chat?.syncSettings();
@@ -149,6 +242,7 @@ async function main ()
149 242 applySpriteSheets(game.images, catalog);
150 243 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
151 244 inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
245 contextMenu = initContextMenu();
152 246 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
153 247 chat = initChat({
154 248 socket: { send (payload) { socket.send(payload); } },
@@ -185,6 +279,11 @@ async function main ()
185 279 break;
186 280 case MessageType.entityMove:
187 281 view?.moveEntity(message);
282 if (message.entityId === view?.localEntityId && message.gait)
283 {
284 gait = message.gait;
285 document.getElementById("gait").textContent = gait;
286 }
188 287 break;
189 288 case MessageType.entityDespawn:
190 289 view?.despawnEntity(message.entityId);
@@ -218,6 +317,18 @@ async function main ()
218 317 case MessageType.friends:
219 318 social?.handleFriends(message);
220 319 break;
320 case MessageType.combatSwing:
321 view?.spawnCombatSwing(message);
322 break;
323 case MessageType.combatHit:
324 view?.addDynamicLight({
325 worldX: (message.tileX ?? 0) + 0.5,
326 worldY: (message.tileY ?? 0) + 0.5,
327 radiusTiles: 2,
328 intensity: 0.4,
329 durationMs: 180
330 });
331 break;
221 332 case MessageType.error:
222 333 showError(message.message);
223 334 social?.showError(message.message);
@@ -246,6 +357,7 @@ document.getElementById("leave").addEventListener("click", () =>
246 357 social?.reset();
247 358 chat?.reset();
248 359 inventory?.reset();
360 contextMenu?.hide();
249 361 overlay.hidden = false;
250 362 hud.hidden = true;
251 363 });
@@ -6,6 +6,7 @@ import { WorldView } from "../render/worldView.js";
6import { initSocial } from "./social.js";
6import { initSocial } from "./social.js";
7import { initChat } from "./chat.js";
7import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
8import { initInventory } from "./inventory.js";
9import { initContextMenu } from "./contextMenu.js";
9
10
10const game = new Game();
11const game = new Game();
11const hud = document.getElementById("hud");
12const hud = document.getElementById("hud");
@@ -24,6 +25,7 @@ let catalog = { grounds: {}, blocks: {} };
24let social;
25let social;
25let chat;
26let chat;
26let inventory;
27let inventory;
28let contextMenu;
27
29
28function showError (message)
30function showError (message)
29{
31{
@@ -59,6 +61,104 @@ function renderCharacters (characters)
59 }
61 }
60}
62}
61
63
64function uiBlocked ()
65{
66 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isOpen() || contextMenu?.isOpen());
67}
68
69function handleLeftClick (mouseX, mouseY)
70{
71 const entity = view.entityAtScreen(mouseX, mouseY);
72 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
73 {
74 if (entity.characterId)
75 {
76 social.inspect(entity);
77 return;
78 }
79 if (entity.talkable)
80 {
81 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
82 return;
83 }
84 if (entity.hostile)
85 {
86 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
87 return;
88 }
89 }
90
91 const tile = view.screenToTile(mouseX, mouseY);
92 const local = view.entities.get(view.localEntityId);
93 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
94 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
95 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
96 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
97 { socket.send({ type: MessageType.openBank }); }
98 else
99 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
100}
101
102function handleRightClick (event, mouseX, mouseY)
103{
104 event.preventDefault();
105 const entity = view.entityAtScreen(mouseX, mouseY);
106 const tile = view.screenToTile(mouseX, mouseY);
107 const items = [];
108
109 if (entity && entity.entityId !== view.localEntityId)
110 {
111 const targetName = entityLabel(entity);
112 items.push({
113 label: "Walk here",
114 onSelect: () => socket.send({ type: MessageType.moveTo, tileX: entity.tileX, tileY: entity.tileY })
115 });
116 items.push({
117 label: `Follow ${targetName}`,
118 onSelect: () => socket.send({ type: MessageType.follow, targetEntityId: entity.entityId })
119 });
120 if (!entity.untargetable)
121 {
122 if (entity.talkable)
123 {
124 items.push({
125 label: "Talk",
126 onSelect: () => socket.send({ type: MessageType.interact, targetEntityId: entity.entityId })
127 });
128 }
129 if (entity.characterId)
130 {
131 items.push({
132 label: `${targetName} info`,
133 onSelect: () => social.inspect(entity)
134 });
135 }
136 items.push({
137 label: `Attack ${targetName}`,
138 onSelect: () => socket.send({ type: MessageType.attack, targetEntityId: entity.entityId })
139 });
140 }
141 }
142 else
143 {
144 items.push({
145 label: "Walk here",
146 onSelect: () => socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY })
147 });
148 }
149
150 contextMenu.show(event.clientX, event.clientY, items);
151}
152
153function entityLabel (entity)
154{
155 const first = (entity?.firstName ?? "").trim();
156 const last = (entity?.lastName ?? "").trim();
157 if (first && last)
158 { return `${first} ${last}`; }
159 return first || "target";
160}
161
62function startPlay (payload)
162function startPlay (payload)
63{
163{
64 playing = true;
164 playing = true;
@@ -76,27 +176,13 @@ function startPlay (payload)
76 const ticker = new GameObject(0, 0, null, 10);
176 const ticker = new GameObject(0, 0, null, 10);
77 ticker.update = (dt) =>
177 ticker.update = (dt) =>
78 {
178 {
79 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking() && !chat?.isBlocking() && !inventory?.isOpen())
179 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !uiBlocked())
80 {
180 {
81 const canvas = scene.canvas;
181 const canvas = scene.canvas;
82 const rect = canvas.getBoundingClientRect();
182 const rect = canvas.getBoundingClientRect();
83 const mouseX = GameInput.mousePosition.x - rect.left;
183 const mouseX = GameInput.mousePosition.x - rect.left;
84 const mouseY = GameInput.mousePosition.y - rect.top;
184 const mouseY = GameInput.mousePosition.y - rect.top;
85 const entity = view.entityAtScreen(mouseX, mouseY);
185 handleLeftClick(mouseX, mouseY);
86 if (entity && entity.entityId !== view.localEntityId && entity.characterId)
87 { social.inspect(entity); }
88 else
89 {
90 const tile = view.screenToTile(mouseX, mouseY);
91 const local = view.entities.get(view.localEntityId);
92 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
93 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
94 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
95 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
96 { socket.send({ type: MessageType.openBank }); }
97 else
98 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
99 }
100 }
186 }
101 if (GameInput.isPressed(82) && !chat?.isOpen())
187 if (GameInput.isPressed(82) && !chat?.isOpen())
102 {
188 {
@@ -125,6 +211,13 @@ function startPlay (payload)
125 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
211 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
126 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
212 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
127 }, { passive: true });
213 }, { passive: true });
214 scene.canvas.addEventListener("contextmenu", (event) =>
215 {
216 if (!playing || uiBlocked())
217 { return; }
218 const rect = scene.canvas.getBoundingClientRect();
219 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
220 });
128 }
221 }
129 view.setSettings(payload.settings ?? view.settings);
222 view.setSettings(payload.settings ?? view.settings);
130 chat?.syncSettings();
223 chat?.syncSettings();
@@ -149,6 +242,7 @@ async function main ()
149 applySpriteSheets(game.images, catalog);
242 applySpriteSheets(game.images, catalog);
150 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
243 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
151 inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
244 inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
245 contextMenu = initContextMenu();
152 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
246 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
153 chat = initChat({
247 chat = initChat({
154 socket: { send (payload) { socket.send(payload); } },
248 socket: { send (payload) { socket.send(payload); } },
@@ -185,6 +279,11 @@ async function main ()
185 break;
279 break;
186 case MessageType.entityMove:
280 case MessageType.entityMove:
187 view?.moveEntity(message);
281 view?.moveEntity(message);
282 if (message.entityId === view?.localEntityId && message.gait)
283 {
284 gait = message.gait;
285 document.getElementById("gait").textContent = gait;
286 }
188 break;
287 break;
189 case MessageType.entityDespawn:
288 case MessageType.entityDespawn:
190 view?.despawnEntity(message.entityId);
289 view?.despawnEntity(message.entityId);
@@ -218,6 +317,18 @@ async function main ()
218 case MessageType.friends:
317 case MessageType.friends:
219 social?.handleFriends(message);
318 social?.handleFriends(message);
220 break;
319 break;
320 case MessageType.combatSwing:
321 view?.spawnCombatSwing(message);
322 break;
323 case MessageType.combatHit:
324 view?.addDynamicLight({
325 worldX: (message.tileX ?? 0) + 0.5,
326 worldY: (message.tileY ?? 0) + 0.5,
327 radiusTiles: 2,
328 intensity: 0.4,
329 durationMs: 180
330 });
331 break;
221 case MessageType.error:
332 case MessageType.error:
222 showError(message.message);
333 showError(message.message);
223 social?.showError(message.message);
334 social?.showError(message.message);
@@ -246,6 +357,7 @@ document.getElementById("leave").addEventListener("click", () =>
246 social?.reset();
357 social?.reset();
247 chat?.reset();
358 chat?.reset();
248 inventory?.reset();
359 inventory?.reset();
360 contextMenu?.hide();
249 overlay.hidden = false;
361 overlay.hidden = false;
250 hud.hidden = true;
362 hud.hidden = true;
251});
363});
client/src/render/chunkBake.js added +200 −0
@@ -0,0 +1,200 @@
1 import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5 /**
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
8 */
9 export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10 {
11 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
13 const ground = makeCanvas(width, height);
14 const bloom = makeCanvas(width, height);
15 const blockRows = [];
16 for (let row = 0; row < CHUNK_SIZE; row++)
17 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
18
19 const groundCtx = ground.getContext("2d");
20 const bloomCtx = bloom.getContext("2d");
21 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
22 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
23 {
24 ctx.imageSmoothingEnabled = false;
25 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
26 }
27
28 const tallBlocks = [];
29 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32 for (let localY = 0; localY < CHUNK_SIZE; localY++)
33 {
34 for (let localX = 0; localX < CHUNK_SIZE; localX++)
35 {
36 const index = localY * CHUNK_SIZE + localX;
37 const tileX = baseTileX + localX;
38 const tileY = baseTileY + localY;
39 let groundEntry = snapshot.grounds[index];
40 let blockEntry = snapshot.blocks[index];
41 if (preview && preview.tileX === tileX && preview.tileY === tileY)
42 {
43 if (preview.ground !== undefined)
44 { groundEntry = preview.ground; }
45 if (preview.block !== undefined)
46 { blockEntry = preview.block; }
47 }
48
49 const dx = localX * SPRITE_SIZE_PX;
50 const dy = localY * SPRITE_SIZE_PX;
51 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 if (groundBloom)
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
57
58 const blockName = blockSpriteName(catalog, blockEntry);
59 if (!blockName)
60 { continue; }
61 const blockMeta = blockCatalogMeta(catalog, blockEntry);
62 if (isBakeable(images[blockName], blockMeta))
63 {
64 blit(blockCtxs[localY], images[blockName], dx, 0);
65 const blockBloom = blockBloomName(catalog, blockEntry);
66 if (blockBloom)
67 { blit(bloomCtx, images[blockBloom], dx, dy); }
68 }
69 else
70 {
71 tallBlocks.push({
72 tileX,
73 tileY,
74 sprite: blockName,
75 bloom: blockBloomName(catalog, blockEntry)
76 });
77 }
78 }
79 }
80
81 return { ground, blockRows, bloom, tallBlocks };
82 }
83
84 export function isBakeable (sprite, meta = null)
85 {
86 if (!sprite?.g_image)
87 { return false; }
88 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
89 { return false; }
90 if ((meta?.frames ?? 1) > 1)
91 { return false; }
92 if ((meta?.animationSpeed ?? 0) > 0)
93 { return false; }
94 return true;
95 }
96
97 export function frameworkImageFromCanvas (canvas)
98 {
99 const fw = new image(canvas, 1, 1, false);
100 fw.cacheWidth = -1;
101 fw.cacheHeight = -1;
102 return fw;
103 }
104
105 export function invalidateCanvasTexture (scene, canvas)
106 {
107 const glContext = scene?.glContext;
108 if (!glContext?.textures || !canvas)
109 { return; }
110 const texture = glContext.textures.get(canvas);
111 if (!texture)
112 { return; }
113 glContext.gl.deleteTexture(texture);
114 glContext.textures.delete(canvas);
115 }
116
117 function makeCanvas (width, height)
118 {
119 const canvas = document.createElement("canvas");
120 canvas.width = width;
121 canvas.height = height;
122 return canvas;
123 }
124
125 function blit (ctx, sprite, dx, dy)
126 {
127 if (!sprite?.g_image)
128 { return; }
129 const sub = sprite.getSubImage(0);
130 ctx.drawImage(
131 sprite.g_image,
132 sub.sx,
133 sub.sy,
134 sub.sw,
135 sub.sh,
136 dx,
137 dy,
138 SPRITE_SIZE_PX,
139 SPRITE_SIZE_PX
140 );
141 }
142
143 function groundSpriteName (catalog, ground)
144 {
145 const entry = normalizeGround(ground);
146 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
147 const states = catalog.grounds?.[def.key]?.states ?? [];
148 const state = resolveState(states, entry.state);
149 return spriteImageName("ground", def.key, state);
150 }
151
152 function blockSpriteName (catalog, block)
153 {
154 const entry = normalizeBlock(block);
155 if (!entry)
156 { return null; }
157 const def = BLOCK_DEFINITIONS[entry.typeId];
158 if (!def)
159 { return null; }
160 const states = catalog.blocks?.[def.key]?.states ?? [];
161 const state = resolveState(states, entry.state);
162 return spriteImageName("block", def.key, state);
163 }
164
165 function groundBloomName (catalog, ground)
166 {
167 const entry = normalizeGround(ground);
168 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
169 const type = catalog.grounds?.[def.key];
170 const state = resolveState(type?.states ?? [], entry.state);
171 if (!state || !type?.blooms?.[state])
172 { return null; }
173 return bloomImageName("ground", def.key, state);
174 }
175
176 function blockBloomName (catalog, block)
177 {
178 const entry = normalizeBlock(block);
179 if (!entry)
180 { return null; }
181 const def = BLOCK_DEFINITIONS[entry.typeId];
182 if (!def)
183 { return null; }
184 const type = catalog.blocks?.[def.key];
185 const state = resolveState(type?.states ?? [], entry.state);
186 if (!state || !type?.blooms?.[state])
187 { return null; }
188 return bloomImageName("block", def.key, state);
189 }
190
191 function blockCatalogMeta (catalog, block)
192 {
193 const entry = normalizeBlock(block);
194 if (!entry)
195 { return null; }
196 const def = BLOCK_DEFINITIONS[entry.typeId];
197 if (!def)
198 { return null; }
199 return catalog.blocks?.[def.key] ?? null;
200 }
@@ -0,0 +1,200 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5/**
6 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7 * Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
8 */
9export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10{
11 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
13 const ground = makeCanvas(width, height);
14 const bloom = makeCanvas(width, height);
15 const blockRows = [];
16 for (let row = 0; row < CHUNK_SIZE; row++)
17 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
18
19 const groundCtx = ground.getContext("2d");
20 const bloomCtx = bloom.getContext("2d");
21 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
22 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
23 {
24 ctx.imageSmoothingEnabled = false;
25 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
26 }
27
28 const tallBlocks = [];
29 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32 for (let localY = 0; localY < CHUNK_SIZE; localY++)
33 {
34 for (let localX = 0; localX < CHUNK_SIZE; localX++)
35 {
36 const index = localY * CHUNK_SIZE + localX;
37 const tileX = baseTileX + localX;
38 const tileY = baseTileY + localY;
39 let groundEntry = snapshot.grounds[index];
40 let blockEntry = snapshot.blocks[index];
41 if (preview && preview.tileX === tileX && preview.tileY === tileY)
42 {
43 if (preview.ground !== undefined)
44 { groundEntry = preview.ground; }
45 if (preview.block !== undefined)
46 { blockEntry = preview.block; }
47 }
48
49 const dx = localX * SPRITE_SIZE_PX;
50 const dy = localY * SPRITE_SIZE_PX;
51 const groundName = groundSpriteName(catalog, groundEntry);
52 blit(groundCtx, images[groundName], dx, dy);
53
54 const groundBloom = groundBloomName(catalog, groundEntry);
55 if (groundBloom)
56 { blit(bloomCtx, images[groundBloom], dx, dy); }
57
58 const blockName = blockSpriteName(catalog, blockEntry);
59 if (!blockName)
60 { continue; }
61 const blockMeta = blockCatalogMeta(catalog, blockEntry);
62 if (isBakeable(images[blockName], blockMeta))
63 {
64 blit(blockCtxs[localY], images[blockName], dx, 0);
65 const blockBloom = blockBloomName(catalog, blockEntry);
66 if (blockBloom)
67 { blit(bloomCtx, images[blockBloom], dx, dy); }
68 }
69 else
70 {
71 tallBlocks.push({
72 tileX,
73 tileY,
74 sprite: blockName,
75 bloom: blockBloomName(catalog, blockEntry)
76 });
77 }
78 }
79 }
80
81 return { ground, blockRows, bloom, tallBlocks };
82}
83
84export function isBakeable (sprite, meta = null)
85{
86 if (!sprite?.g_image)
87 { return false; }
88 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
89 { return false; }
90 if ((meta?.frames ?? 1) > 1)
91 { return false; }
92 if ((meta?.animationSpeed ?? 0) > 0)
93 { return false; }
94 return true;
95}
96
97export function frameworkImageFromCanvas (canvas)
98{
99 const fw = new image(canvas, 1, 1, false);
100 fw.cacheWidth = -1;
101 fw.cacheHeight = -1;
102 return fw;
103}
104
105export function invalidateCanvasTexture (scene, canvas)
106{
107 const glContext = scene?.glContext;
108 if (!glContext?.textures || !canvas)
109 { return; }
110 const texture = glContext.textures.get(canvas);
111 if (!texture)
112 { return; }
113 glContext.gl.deleteTexture(texture);
114 glContext.textures.delete(canvas);
115}
116
117function makeCanvas (width, height)
118{
119 const canvas = document.createElement("canvas");
120 canvas.width = width;
121 canvas.height = height;
122 return canvas;
123}
124
125function blit (ctx, sprite, dx, dy)
126{
127 if (!sprite?.g_image)
128 { return; }
129 const sub = sprite.getSubImage(0);
130 ctx.drawImage(
131 sprite.g_image,
132 sub.sx,
133 sub.sy,
134 sub.sw,
135 sub.sh,
136 dx,
137 dy,
138 SPRITE_SIZE_PX,
139 SPRITE_SIZE_PX
140 );
141}
142
143function groundSpriteName (catalog, ground)
144{
145 const entry = normalizeGround(ground);
146 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
147 const states = catalog.grounds?.[def.key]?.states ?? [];
148 const state = resolveState(states, entry.state);
149 return spriteImageName("ground", def.key, state);
150}
151
152function blockSpriteName (catalog, block)
153{
154 const entry = normalizeBlock(block);
155 if (!entry)
156 { return null; }
157 const def = BLOCK_DEFINITIONS[entry.typeId];
158 if (!def)
159 { return null; }
160 const states = catalog.blocks?.[def.key]?.states ?? [];
161 const state = resolveState(states, entry.state);
162 return spriteImageName("block", def.key, state);
163}
164
165function groundBloomName (catalog, ground)
166{
167 const entry = normalizeGround(ground);
168 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
169 const type = catalog.grounds?.[def.key];
170 const state = resolveState(type?.states ?? [], entry.state);
171 if (!state || !type?.blooms?.[state])
172 { return null; }
173 return bloomImageName("ground", def.key, state);
174}
175
176function blockBloomName (catalog, block)
177{
178 const entry = normalizeBlock(block);
179 if (!entry)
180 { return null; }
181 const def = BLOCK_DEFINITIONS[entry.typeId];
182 if (!def)
183 { return null; }
184 const type = catalog.blocks?.[def.key];
185 const state = resolveState(type?.states ?? [], entry.state);
186 if (!state || !type?.blooms?.[state])
187 { return null; }
188 return bloomImageName("block", def.key, state);
189}
190
191function blockCatalogMeta (catalog, block)
192{
193 const entry = normalizeBlock(block);
194 if (!entry)
195 { return null; }
196 const def = BLOCK_DEFINITIONS[entry.typeId];
197 if (!def)
198 { return null; }
199 return catalog.blocks?.[def.key] ?? null;
200}
client/src/render/worldView.js +374 −113
@@ -1,14 +1,19 @@
1 1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 import { bloomCompanionName, bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
2 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4 3 import { itemSpriteName } from "/shared/definitions/items.js";
5 4 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5 import {
6 bakeChunkAtlases,
7 frameworkImageFromCanvas,
8 invalidateCanvasTexture
9 } from "./chunkBake.js";
6 10
7 11 const LAYER_GROUND = 0;
8 const LAYER_SHADE = 500000;
9 12 const LAYER_EDGE = 900000;
10 13 const SORT_BLOCK = 1;
11 const SORT_ENTITY = 2;
14 const SORT_SHADE = 2;
15 const SORT_ENTITY = 3;
16 const SORT_SPRITE_SHADE = 4;
12 17 const RENDER_LAYER_BLOOM = "bloom";
13 18
14 19 export class WorldView
@@ -21,6 +26,7 @@ export class WorldView
21 26 this.preview = null;
22 27 this.zoom = 2;
23 28 this.chunks = new Map();
29 this.bakedChunks = new Map();
24 30 this.tiles = new Map();
25 31 this.entities = new Map();
26 32 this.groundItems = new Map();
@@ -30,6 +36,8 @@ export class WorldView
30 36 this.worldHour = 12;
31 37 this.nightPreview = null;
32 38 this.followPlayer = true;
39 this.dynamicLights = [];
40 this.swipes = [];
33 41 this.#syncBloomLayer();
34 42 }
35 43
@@ -78,15 +86,15 @@ export class WorldView
78 86 {
79 87 const key = `${chunkX},${chunkY}`;
80 88 this.chunks.delete(key);
89 this.#destroyBakedChunk(key);
81 90 this.#destroyEdges(key);
82 91 for (const [tileKey, objects] of [...this.tiles.entries()])
83 92 {
84 93 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
85 94 {
86 objects.ground?.destroy();
87 objects.groundBloom?.destroy();
88 95 objects.block?.destroy();
89 96 objects.blockBloom?.destroy();
97 objects.spriteShade?.destroy();
90 98 objects.shade?.destroy();
91 99 this.tiles.delete(tileKey);
92 100 }
@@ -121,13 +129,28 @@ export class WorldView
121 129 this.#upsertEntity(payload);
122 130 return;
123 131 }
132 const size = this.tileSize();
124 133 existing.fromX = existing.visualX;
125 134 existing.fromY = existing.visualY;
126 135 existing.tileX = payload.tileX;
127 136 existing.tileY = payload.tileY;
128 137 existing.gait = payload.gait;
138 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
139 if (payload.worldX != null && payload.worldY != null)
140 {
141 existing.worldX = payload.worldX;
142 existing.worldY = payload.worldY;
143 existing.targetX = payload.worldX * size;
144 existing.targetY = payload.worldY * size;
145 }
146 else
147 {
148 const pivot = tilePivot(payload.tileX, payload.tileY, size);
149 existing.targetX = pivot.x;
150 existing.targetY = pivot.y;
151 }
129 152 existing.lerpStarted = performance.now();
130 existing.lerpMs = this.#lerpMs(payload.gait);
153 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
131 154 }
132 155
133 156 despawnEntity (entityId)
@@ -136,6 +159,7 @@ export class WorldView
136 159 if (!existing)
137 160 { return; }
138 161 existing.object?.destroy();
162 existing.spriteShade?.destroy();
139 163 for (const overlay of existing.overlays ?? [])
140 164 { overlay.destroy(); }
141 165 for (const overlay of existing.bloomOverlays ?? [])
@@ -199,7 +223,14 @@ export class WorldView
199 223 const max = limits.max ?? 4;
200 224 this.zoom = Math.min(max, Math.max(min, zoom));
201 225 for (const snapshot of this.chunks.values())
202 { this.#rebuildChunk(snapshot); }
226 {
227 this.#layoutBakedChunk(snapshot);
228 for (let localY = 0; localY < CHUNK_SIZE; localY++)
229 {
230 for (let localX = 0; localX < CHUNK_SIZE; localX++)
231 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
232 }
233 }
203 234 const size = this.tileSize();
204 235 for (const entity of this.entities.values())
205 236 {
@@ -207,6 +238,8 @@ export class WorldView
207 238 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
208 239 entity.fromX = entity.visualX;
209 240 entity.fromY = entity.visualY;
241 entity.targetX = entity.visualX;
242 entity.targetY = entity.visualY;
210 243 entity.lerpStarted = null;
211 244 this.#placeEntity(entity);
212 245 }
@@ -287,10 +320,12 @@ export class WorldView
287 320 const size = this.tileSize();
288 321 for (const entity of this.entities.values())
289 322 {
290 const target = tilePivot(entity.tileX, entity.tileY, size);
323 const target = entity.targetX != null && entity.targetY != null
324 ? { x: entity.targetX, y: entity.targetY }
325 : tilePivot(entity.tileX, entity.tileY, size);
291 326 if (entity.lerpStarted != null)
292 327 {
293 const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs);
328 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
294 329 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
295 330 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
296 331 if (t >= 1)
@@ -304,10 +339,46 @@ export class WorldView
304 339 this.#placeEntity(entity);
305 340 }
306 341
342 this.#updateSwipes(now);
307 343 this.#centerCamera();
308 344 this.#updateShade(deltaTime);
309 345 }
310 346
347 spawnCombatSwing (payload)
348 {
349 const attacker = this.entities.get(payload.attackerId);
350 const target = this.entities.get(payload.targetId);
351 if (!attacker || !target)
352 { return; }
353 const midX = (attacker.visualX + target.visualX) / 2;
354 const midY = (attacker.visualY + target.visualY) / 2;
355 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
356 const spriteName = "fx:melee-swipe:melee-swipe";
357 const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1);
358 if (object.transform)
359 { object.transform.rotation = angle; }
360 this.scene.addObject(object);
361 this.swipes.push({ object, until: performance.now() + 500 });
362 this.addDynamicLight({
363 worldX: (attacker.tileX + target.tileX) / 2 + 0.5,
364 worldY: (attacker.tileY + target.tileY) / 2 + 0.5,
365 radiusTiles: 2.5,
366 intensity: 0.55,
367 durationMs: 220
368 });
369 }
370
371 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
372 {
373 this.dynamicLights.push({
374 worldX,
375 worldY,
376 radiusTiles,
377 intensity,
378 until: performance.now() + durationMs
379 });
380 }
381
311 382 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
312 383 {
313 384 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
@@ -320,16 +391,24 @@ export class WorldView
320 391 { snapshot.blocks[index] = block; }
321 392 if (light !== undefined)
322 393 { snapshot.light[index] = light; }
323 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
394 this.#rebuildChunk(snapshot);
324 395 }
325 396
326 397 setTilePreview (tileX, tileY, override)
327 398 {
328 399 const previous = this.preview;
329 400 this.preview = { tileX, tileY, ...override };
401 const chunkX = Math.floor(tileX / CHUNK_SIZE);
402 const chunkY = Math.floor(tileY / CHUNK_SIZE);
403 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
404 if (snapshot)
405 { this.#rebuildChunk(snapshot); }
330 406 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
331 { this.#drawTile(previous.tileX, previous.tileY); }
332 this.#drawTile(tileX, tileY);
407 {
408 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
409 if (prevSnapshot && prevSnapshot !== snapshot)
410 { this.#rebuildChunk(prevSnapshot); }
411 }
333 412 }
334 413
335 414 clearTilePreview ()
@@ -337,7 +416,11 @@ export class WorldView
337 416 const previous = this.preview;
338 417 this.preview = null;
339 418 if (previous)
340 { this.#drawTile(previous.tileX, previous.tileY); }
419 {
420 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
421 if (snapshot)
422 { this.#rebuildChunk(snapshot); }
423 }
341 424 }
342 425
343 426 #lerpMs (gait)
@@ -370,6 +453,7 @@ export class WorldView
370 453 ?? bodySpriteName(payload.sex);
371 454 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
372 455 this.scene.addObject(object);
456 this.#startIdleAnimation(object);
373 457 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
374 458 this.entities.set(payload.entityId, entity);
375 459 }
@@ -379,16 +463,35 @@ export class WorldView
379 463 entity.gait = payload.gait;
380 464 entity.sex = payload.sex ?? entity.sex;
381 465 entity.characterId = payload.characterId ?? entity.characterId ?? null;
466 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
467 entity.hostile = !!payload.hostile;
468 entity.talkable = !!payload.talkable;
469 entity.untargetable = !!payload.untargetable;
470 entity.freeFlight = !!payload.freeFlight;
382 471 if (payload.firstName)
383 472 { entity.firstName = payload.firstName; }
384 473 if (payload.lastName)
385 474 { entity.lastName = payload.lastName; }
386 475 entity.firstName = entity.firstName ?? "";
387 476 entity.lastName = entity.lastName ?? "";
388 entity.visualX = pivot.x;
389 entity.visualY = pivot.y;
390 entity.fromX = pivot.x;
391 entity.fromY = pivot.y;
477 if (payload.worldX != null && payload.worldY != null)
478 {
479 entity.worldX = payload.worldX;
480 entity.worldY = payload.worldY;
481 entity.visualX = payload.worldX * size;
482 entity.visualY = payload.worldY * size;
483 entity.targetX = entity.visualX;
484 entity.targetY = entity.visualY;
485 }
486 else
487 {
488 entity.visualX = pivot.x;
489 entity.visualY = pivot.y;
490 entity.targetX = pivot.x;
491 entity.targetY = pivot.y;
492 }
493 entity.fromX = entity.visualX;
494 entity.fromY = entity.visualY;
392 495 if (payload.layers)
393 496 { this.#applyLayers(entity, payload.layers); }
394 497 this.#placeEntity(entity);
@@ -399,7 +502,10 @@ export class WorldView
399 502 const base = layers[0]?.sprite
400 503 ?? bodySpriteName(entity.sex);
401 504 if (this.game.images[base])
402 { entity.object.renderer.sprite = this.game.images[base]; }
505 {
506 entity.object.renderer.sprite = this.game.images[base];
507 this.#startIdleAnimation(entity.object);
508 }
403 509 for (const overlay of entity.overlays ?? [])
404 510 { overlay.destroy(); }
405 511 for (const overlay of entity.bloomOverlays ?? [])
@@ -432,24 +538,142 @@ export class WorldView
432 538 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
433 539 for (const overlay of entity.bloomOverlays ?? [])
434 540 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
541 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
435 542 }
436 543
437 544 #rebuildChunk (snapshot)
438 545 {
546 this.#bakeAndPlaceChunk(snapshot);
547 const tall = new Set(
548 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
549 .map((entry) => `${entry.tileX},${entry.tileY}`)
550 );
439 551 for (let localY = 0; localY < CHUNK_SIZE; localY++)
440 552 {
441 553 for (let localX = 0; localX < CHUNK_SIZE; localX++)
442 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
554 {
555 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
556 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
557 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
558 }
443 559 }
444 560 }
445 561
446 562 #redrawPreview ()
447 563 {
448 if (this.preview)
449 { this.#drawTile(this.preview.tileX, this.preview.tileY); }
564 if (!this.preview)
565 { return; }
566 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
567 if (snapshot)
568 { this.#rebuildChunk(snapshot); }
569 }
570
571 #bakeAndPlaceChunk (snapshot)
572 {
573 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
574 const atlases = bakeChunkAtlases({
575 snapshot,
576 catalog: this.catalog,
577 images: this.game.images,
578 preview: this.preview
579 });
580 let baked = this.bakedChunks.get(key);
581 if (!baked)
582 {
583 baked = {
584 groundCanvas: atlases.ground,
585 blockCanvases: atlases.blockRows,
586 bloomCanvas: atlases.bloom,
587 groundImage: frameworkImageFromCanvas(atlases.ground),
588 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
589 bloomImage: frameworkImageFromCanvas(atlases.bloom),
590 groundObject: null,
591 blockObjects: [],
592 bloomObject: null,
593 tallBlocks: atlases.tallBlocks
594 };
595 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
596 this.scene.addObject(baked.groundObject);
597 for (let row = 0; row < CHUNK_SIZE; row++)
598 {
599 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
600 this.scene.addObject(object);
601 baked.blockObjects.push(object);
602 }
603 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
604 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
605 this.scene.addObject(baked.bloomObject);
606 this.bakedChunks.set(key, baked);
607 }
608 else
609 {
610 copyCanvas(atlases.ground, baked.groundCanvas);
611 for (let row = 0; row < CHUNK_SIZE; row++)
612 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
613 copyCanvas(atlases.bloom, baked.bloomCanvas);
614 invalidateCanvasTexture(this.scene, baked.groundCanvas);
615 for (const canvas of baked.blockCanvases)
616 { invalidateCanvasTexture(this.scene, canvas); }
617 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
618 baked.tallBlocks = atlases.tallBlocks;
619 }
620 this.#layoutBakedChunk(snapshot);
450 621 }
451 622
452 #drawTile (tileX, tileY)
623 #layoutBakedChunk (snapshot)
624 {
625 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
626 const baked = this.bakedChunks.get(key);
627 if (!baked)
628 { return; }
629 const size = this.tileSize();
630 const left = snapshot.chunkX * CHUNK_SIZE * size;
631 const top = snapshot.chunkY * CHUNK_SIZE * size;
632 const chunkPx = CHUNK_SIZE * size;
633 baked.groundObject.transform.position.x = left + chunkPx / 2;
634 baked.groundObject.transform.position.y = top + chunkPx / 2;
635 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
636 baked.groundObject.layer = LAYER_GROUND;
637
638 for (let row = 0; row < CHUNK_SIZE; row++)
639 {
640 const object = baked.blockObjects[row];
641 const rowY = top + row * size + size / 2;
642 object.transform.position.x = left + chunkPx / 2;
643 object.transform.position.y = rowY;
644 object.transform.size = new vector(chunkPx, size);
645 object.layer = ySortLayer(rowY, SORT_BLOCK);
646 }
647
648 baked.bloomObject.transform.position.x = left + chunkPx / 2;
649 baked.bloomObject.transform.position.y = top + chunkPx / 2;
650 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
651 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
652 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
653 this.#markSortDirty();
654 setNearestFilter(this.scene, baked.groundCanvas);
655 for (const canvas of baked.blockCanvases)
656 { setNearestFilter(this.scene, canvas); }
657 setNearestFilter(this.scene, baked.bloomCanvas);
658 }
659
660 #destroyBakedChunk (key)
661 {
662 const baked = this.bakedChunks.get(key);
663 if (!baked)
664 { return; }
665 baked.groundObject?.destroy();
666 for (const object of baked.blockObjects ?? [])
667 { object.destroy(); }
668 baked.bloomObject?.destroy();
669 invalidateCanvasTexture(this.scene, baked.groundCanvas);
670 for (const canvas of baked.blockCanvases ?? [])
671 { invalidateCanvasTexture(this.scene, canvas); }
672 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
673 this.bakedChunks.delete(key);
674 }
675
676 #drawTile (tileX, tileY, forceTall = null)
453 677 {
454 678 const chunkX = Math.floor(tileX / CHUNK_SIZE);
455 679 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -463,116 +687,90 @@ export class WorldView
463 687 let objects = this.tiles.get(key);
464 688 if (!objects)
465 689 {
466 objects = { chunkX, chunkY };
690 objects = { chunkX, chunkY, tileX, tileY };
467 691 this.tiles.set(key, objects);
468 692 }
469
470 let ground = snapshot.grounds[index];
471 let block = snapshot.blocks[index];
472 const preview = this.preview;
473 if (preview && preview.tileX === tileX && preview.tileY === tileY)
474 {
475 if (preview.ground !== undefined)
476 { ground = preview.ground; }
477 if (preview.block !== undefined)
478 { block = preview.block; }
479 }
693 objects.tileX = tileX;
694 objects.tileY = tileY;
695 objects.chunkX = chunkX;
696 objects.chunkY = chunkY;
480 697
481 698 const size = this.tileSize();
482 699 const pivot = tilePivot(tileX, tileY, size);
483 const groundName = this.#groundSpriteName(ground);
484 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
485 if (objects.ground)
486 {
487 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
488 objects.ground.layer = LAYER_GROUND;
489 }
490 objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, this.#groundBloomName(ground), pivot);
700 objects.light = snapshot.light[index] ?? 0;
701 const previousShade = objects.shade;
702 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
703 if (objects.shade && objects.shade !== previousShade)
704 { objects.shade.renderer.alpha = 0; }
491 705
492 const blockName = this.#blockSpriteName(block);
493 if (blockName)
706 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
707 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
708 const isTall = forceTall === true || !!tallEntry;
709 if (isTall && tallEntry)
494 710 {
495 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
711 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
496 712 if (objects.block)
497 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); }
713 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
714 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
715 objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
498 716 }
499 else if (objects.block)
717 else
500 718 {
501 objects.block.destroy();
502 objects.block = null;
719 if (objects.block)
720 {
721 objects.block.destroy();
722 objects.block = null;
723 }
724 if (objects.blockBloom)
725 {
726 objects.blockBloom.destroy();
727 objects.blockBloom = null;
728 }
729 if (objects.spriteShade)
730 {
731 objects.spriteShade.destroy();
732 objects.spriteShade = null;
733 }
503 734 }
504 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, this.#blockBloomName(block), pivot);
505
506 objects.light = snapshot.light[index] ?? 0;
507 const previousShade = objects.shade;
508 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
509 if (objects.shade && objects.shade !== previousShade)
510 { objects.shade.renderer.alpha = 0; }
511 735 }
512 736
513 #groundSpriteName (ground)
514 {
515 const entry = normalizeGround(ground);
516 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
517 const states = this.catalog.grounds?.[def.key]?.states ?? [];
518 const state = resolveState(states, entry.state);
519 return spriteImageName("ground", def.key, state);
520 }
521
522 #blockSpriteName (block)
523 {
524 const entry = normalizeBlock(block);
525 if (!entry)
526 { return null; }
527 const def = BLOCK_DEFINITIONS[entry.typeId];
528 if (!def)
529 { return null; }
530 const states = this.catalog.blocks?.[def.key]?.states ?? [];
531 const state = resolveState(states, entry.state);
532 return spriteImageName("block", def.key, state);
533 }
534
535 #groundBloomName (ground)
536 {
537 const entry = normalizeGround(ground);
538 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
539 const type = this.catalog.grounds?.[def.key];
540 const state = resolveState(type?.states ?? [], entry.state);
541 if (!state || !type?.blooms?.[state])
542 { return null; }
543 return bloomImageName("ground", def.key, state);
544 }
545
546 #blockBloomName (block)
547 {
548 const entry = normalizeBlock(block);
549 if (!entry)
550 { return null; }
551 const def = BLOCK_DEFINITIONS[entry.typeId];
552 if (!def)
553 { return null; }
554 const type = this.catalog.blocks?.[def.key];
555 const state = resolveState(type?.states ?? [], entry.state);
556 if (!state || !type?.blooms?.[state])
557 { return null; }
558 return bloomImageName("block", def.key, state);
559 }
560
561 #placeBloomOverlay (existing, name, pivot)
737 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
562 738 {
563 739 if (!name)
564 740 {
565 741 existing?.destroy();
566 742 return null;
567 743 }
568 const object = this.#ensureSprite(existing, name, SORT_BLOCK);
744 const object = this.#ensureSprite(existing, name, sortOrder);
569 745 if (!object)
570 746 { return null; }
571 747 object.renderer.layer = RENDER_LAYER_BLOOM;
572 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
748 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
573 749 return object;
574 750 }
575 751
752 #placeSpriteShade (existing, targetObject, pivotX, pivotY)
753 {
754 if (!targetObject?.renderer?.sprite)
755 {
756 existing?.destroy();
757 return null;
758 }
759 const shade = this.#ensureSprite(existing, "night-shade", SORT_SPRITE_SHADE);
760 if (!shade)
761 { return null; }
762 const sprite = targetObject.renderer.sprite;
763 const zoom = this.zoom;
764 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
765 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
766 shade.transform.position.x = center.x;
767 shade.transform.position.y = center.y;
768 shade.transform.size = new vector(draw.w, draw.h);
769 shade.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
770 this.#markSortDirty();
771 return shade;
772 }
773
576 774 #tileFill (existing, name, x, y, layer)
577 775 {
578 776 existing = this.#ensureSprite(existing, name, layer);
@@ -615,12 +813,18 @@ export class WorldView
615 813 existing?.destroy();
616 814 existing = new GameObject(0, 0, sprite, layer);
617 815 this.scene.addObject(existing);
618 if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
619 { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
816 this.#startIdleAnimation(existing);
620 817 }
621 818 return existing;
622 819 }
623 820
821 #startIdleAnimation (object)
822 {
823 const sprite = object?.renderer?.sprite;
824 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
825 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
826 }
827
624 828 #neighborClosed (snapshot, dir, dx, dy)
625 829 {
626 830 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
@@ -716,15 +920,50 @@ export class WorldView
716 920 {
717 921 const hour = this.nightPreview ?? this.worldHour;
718 922 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
923 const now = performance.now();
924 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
719 925 for (const objects of this.tiles.values())
720 926 {
721 if (!objects.shade)
927 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
928 let dynamic = 0;
929 for (const light of this.dynamicLights)
930 {
931 const dx = (objects.tileX + 0.5) - light.worldX;
932 const dy = (objects.tileY + 0.5) - light.worldY;
933 const dist = Math.hypot(dx, dy);
934 if (dist >= light.radiusTiles)
935 { continue; }
936 const falloff = 1 - dist / light.radiusTiles;
937 dynamic = Math.max(dynamic, falloff * light.intensity);
938 }
939 const intensity = Math.max(baked, dynamic);
940 const alpha = ambientDark * (1 - intensity);
941 objects.shadeAlpha = alpha;
942 if (objects.shade)
943 { objects.shade.renderer.alpha = alpha; }
944 if (objects.spriteShade)
945 { objects.spriteShade.renderer.alpha = alpha; }
946 }
947 for (const entity of this.entities.values())
948 {
949 if (!entity.spriteShade)
722 950 { continue; }
723 const intensity = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
724 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
951 const tile = this.tiles.get(`${entity.tileX},${entity.tileY}`);
952 entity.spriteShade.renderer.alpha = tile?.shadeAlpha ?? 0;
725 953 }
726 954 }
727 955
956 #updateSwipes (now)
957 {
958 this.swipes = this.swipes.filter((swipe) =>
959 {
960 if (swipe.until > now)
961 { return true; }
962 swipe.object?.destroy();
963 return false;
964 });
965 }
966
728 967 #syncBloomLayer ()
729 968 {
730 969 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
@@ -771,3 +1010,25 @@ function lerp (a, b, t)
771 1010 {
772 1011 return a + (b - a) * Math.min(1, Math.max(0, t));
773 1012 }
1013
1014 function copyCanvas (source, dest)
1015 {
1016 const ctx = dest.getContext("2d");
1017 ctx.imageSmoothingEnabled = false;
1018 ctx.clearRect(0, 0, dest.width, dest.height);
1019 ctx.drawImage(source, 0, 0);
1020 }
1021
1022 function setNearestFilter (scene, canvas)
1023 {
1024 const glContext = scene?.glContext;
1025 if (!glContext || !canvas)
1026 { return; }
1027 const texture = glContext.getTexture(canvas);
1028 if (!texture)
1029 { return; }
1030 const gl = glContext.gl;
1031 gl.bindTexture(gl.TEXTURE_2D, texture);
1032 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1033 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1034 }
@@ -1,14 +1,19 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { bloomCompanionName, bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { itemSpriteName } from "/shared/definitions/items.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
5import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5import {
6 bakeChunkAtlases,
7 frameworkImageFromCanvas,
8 invalidateCanvasTexture
9} from "./chunkBake.js";
6
10
7const LAYER_GROUND = 0;
11const LAYER_GROUND = 0;
8const LAYER_SHADE = 500000;
9const LAYER_EDGE = 900000;
12const LAYER_EDGE = 900000;
10const SORT_BLOCK = 1;
13const SORT_BLOCK = 1;
11const SORT_ENTITY = 2;
14const SORT_SHADE = 2;
15const SORT_ENTITY = 3;
16const SORT_SPRITE_SHADE = 4;
12const RENDER_LAYER_BLOOM = "bloom";
17const RENDER_LAYER_BLOOM = "bloom";
13
18
14export class WorldView
19export class WorldView
@@ -21,6 +26,7 @@ export class WorldView
21 this.preview = null;
26 this.preview = null;
22 this.zoom = 2;
27 this.zoom = 2;
23 this.chunks = new Map();
28 this.chunks = new Map();
29 this.bakedChunks = new Map();
24 this.tiles = new Map();
30 this.tiles = new Map();
25 this.entities = new Map();
31 this.entities = new Map();
26 this.groundItems = new Map();
32 this.groundItems = new Map();
@@ -30,6 +36,8 @@ export class WorldView
30 this.worldHour = 12;
36 this.worldHour = 12;
31 this.nightPreview = null;
37 this.nightPreview = null;
32 this.followPlayer = true;
38 this.followPlayer = true;
39 this.dynamicLights = [];
40 this.swipes = [];
33 this.#syncBloomLayer();
41 this.#syncBloomLayer();
34 }
42 }
35
43
@@ -78,15 +86,15 @@ export class WorldView
78 {
86 {
79 const key = `${chunkX},${chunkY}`;
87 const key = `${chunkX},${chunkY}`;
80 this.chunks.delete(key);
88 this.chunks.delete(key);
89 this.#destroyBakedChunk(key);
81 this.#destroyEdges(key);
90 this.#destroyEdges(key);
82 for (const [tileKey, objects] of [...this.tiles.entries()])
91 for (const [tileKey, objects] of [...this.tiles.entries()])
83 {
92 {
84 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
93 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
85 {
94 {
86 objects.ground?.destroy();
87 objects.groundBloom?.destroy();
88 objects.block?.destroy();
95 objects.block?.destroy();
89 objects.blockBloom?.destroy();
96 objects.blockBloom?.destroy();
97 objects.spriteShade?.destroy();
90 objects.shade?.destroy();
98 objects.shade?.destroy();
91 this.tiles.delete(tileKey);
99 this.tiles.delete(tileKey);
92 }
100 }
@@ -121,13 +129,28 @@ export class WorldView
121 this.#upsertEntity(payload);
129 this.#upsertEntity(payload);
122 return;
130 return;
123 }
131 }
132 const size = this.tileSize();
124 existing.fromX = existing.visualX;
133 existing.fromX = existing.visualX;
125 existing.fromY = existing.visualY;
134 existing.fromY = existing.visualY;
126 existing.tileX = payload.tileX;
135 existing.tileX = payload.tileX;
127 existing.tileY = payload.tileY;
136 existing.tileY = payload.tileY;
128 existing.gait = payload.gait;
137 existing.gait = payload.gait;
138 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
139 if (payload.worldX != null && payload.worldY != null)
140 {
141 existing.worldX = payload.worldX;
142 existing.worldY = payload.worldY;
143 existing.targetX = payload.worldX * size;
144 existing.targetY = payload.worldY * size;
145 }
146 else
147 {
148 const pivot = tilePivot(payload.tileX, payload.tileY, size);
149 existing.targetX = pivot.x;
150 existing.targetY = pivot.y;
151 }
129 existing.lerpStarted = performance.now();
152 existing.lerpStarted = performance.now();
130 existing.lerpMs = this.#lerpMs(payload.gait);
153 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
131 }
154 }
132
155
133 despawnEntity (entityId)
156 despawnEntity (entityId)
@@ -136,6 +159,7 @@ export class WorldView
136 if (!existing)
159 if (!existing)
137 { return; }
160 { return; }
138 existing.object?.destroy();
161 existing.object?.destroy();
162 existing.spriteShade?.destroy();
139 for (const overlay of existing.overlays ?? [])
163 for (const overlay of existing.overlays ?? [])
140 { overlay.destroy(); }
164 { overlay.destroy(); }
141 for (const overlay of existing.bloomOverlays ?? [])
165 for (const overlay of existing.bloomOverlays ?? [])
@@ -199,7 +223,14 @@ export class WorldView
199 const max = limits.max ?? 4;
223 const max = limits.max ?? 4;
200 this.zoom = Math.min(max, Math.max(min, zoom));
224 this.zoom = Math.min(max, Math.max(min, zoom));
201 for (const snapshot of this.chunks.values())
225 for (const snapshot of this.chunks.values())
202 { this.#rebuildChunk(snapshot); }
226 {
227 this.#layoutBakedChunk(snapshot);
228 for (let localY = 0; localY < CHUNK_SIZE; localY++)
229 {
230 for (let localX = 0; localX < CHUNK_SIZE; localX++)
231 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
232 }
233 }
203 const size = this.tileSize();
234 const size = this.tileSize();
204 for (const entity of this.entities.values())
235 for (const entity of this.entities.values())
205 {
236 {
@@ -207,6 +238,8 @@ export class WorldView
207 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
238 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
208 entity.fromX = entity.visualX;
239 entity.fromX = entity.visualX;
209 entity.fromY = entity.visualY;
240 entity.fromY = entity.visualY;
241 entity.targetX = entity.visualX;
242 entity.targetY = entity.visualY;
210 entity.lerpStarted = null;
243 entity.lerpStarted = null;
211 this.#placeEntity(entity);
244 this.#placeEntity(entity);
212 }
245 }
@@ -287,10 +320,12 @@ export class WorldView
287 const size = this.tileSize();
320 const size = this.tileSize();
288 for (const entity of this.entities.values())
321 for (const entity of this.entities.values())
289 {
322 {
290 const target = tilePivot(entity.tileX, entity.tileY, size);
323 const target = entity.targetX != null && entity.targetY != null
324 ? { x: entity.targetX, y: entity.targetY }
325 : tilePivot(entity.tileX, entity.tileY, size);
291 if (entity.lerpStarted != null)
326 if (entity.lerpStarted != null)
292 {
327 {
293 const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs);
328 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
294 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
329 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
295 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
330 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
296 if (t >= 1)
331 if (t >= 1)
@@ -304,10 +339,46 @@ export class WorldView
304 this.#placeEntity(entity);
339 this.#placeEntity(entity);
305 }
340 }
306
341
342 this.#updateSwipes(now);
307 this.#centerCamera();
343 this.#centerCamera();
308 this.#updateShade(deltaTime);
344 this.#updateShade(deltaTime);
309 }
345 }
310
346
347 spawnCombatSwing (payload)
348 {
349 const attacker = this.entities.get(payload.attackerId);
350 const target = this.entities.get(payload.targetId);
351 if (!attacker || !target)
352 { return; }
353 const midX = (attacker.visualX + target.visualX) / 2;
354 const midY = (attacker.visualY + target.visualY) / 2;
355 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
356 const spriteName = "fx:melee-swipe:melee-swipe";
357 const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1);
358 if (object.transform)
359 { object.transform.rotation = angle; }
360 this.scene.addObject(object);
361 this.swipes.push({ object, until: performance.now() + 500 });
362 this.addDynamicLight({
363 worldX: (attacker.tileX + target.tileX) / 2 + 0.5,
364 worldY: (attacker.tileY + target.tileY) / 2 + 0.5,
365 radiusTiles: 2.5,
366 intensity: 0.55,
367 durationMs: 220
368 });
369 }
370
371 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
372 {
373 this.dynamicLights.push({
374 worldX,
375 worldY,
376 radiusTiles,
377 intensity,
378 until: performance.now() + durationMs
379 });
380 }
381
311 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
382 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
312 {
383 {
313 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
384 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
@@ -320,16 +391,24 @@ export class WorldView
320 { snapshot.blocks[index] = block; }
391 { snapshot.blocks[index] = block; }
321 if (light !== undefined)
392 if (light !== undefined)
322 { snapshot.light[index] = light; }
393 { snapshot.light[index] = light; }
323 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
394 this.#rebuildChunk(snapshot);
324 }
395 }
325
396
326 setTilePreview (tileX, tileY, override)
397 setTilePreview (tileX, tileY, override)
327 {
398 {
328 const previous = this.preview;
399 const previous = this.preview;
329 this.preview = { tileX, tileY, ...override };
400 this.preview = { tileX, tileY, ...override };
401 const chunkX = Math.floor(tileX / CHUNK_SIZE);
402 const chunkY = Math.floor(tileY / CHUNK_SIZE);
403 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
404 if (snapshot)
405 { this.#rebuildChunk(snapshot); }
330 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
406 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
331 { this.#drawTile(previous.tileX, previous.tileY); }
407 {
332 this.#drawTile(tileX, tileY);
408 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
409 if (prevSnapshot && prevSnapshot !== snapshot)
410 { this.#rebuildChunk(prevSnapshot); }
411 }
333 }
412 }
334
413
335 clearTilePreview ()
414 clearTilePreview ()
@@ -337,7 +416,11 @@ export class WorldView
337 const previous = this.preview;
416 const previous = this.preview;
338 this.preview = null;
417 this.preview = null;
339 if (previous)
418 if (previous)
340 { this.#drawTile(previous.tileX, previous.tileY); }
419 {
420 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
421 if (snapshot)
422 { this.#rebuildChunk(snapshot); }
423 }
341 }
424 }
342
425
343 #lerpMs (gait)
426 #lerpMs (gait)
@@ -370,6 +453,7 @@ export class WorldView
370 ?? bodySpriteName(payload.sex);
453 ?? bodySpriteName(payload.sex);
371 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
454 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
372 this.scene.addObject(object);
455 this.scene.addObject(object);
456 this.#startIdleAnimation(object);
373 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
457 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
374 this.entities.set(payload.entityId, entity);
458 this.entities.set(payload.entityId, entity);
375 }
459 }
@@ -379,16 +463,35 @@ export class WorldView
379 entity.gait = payload.gait;
463 entity.gait = payload.gait;
380 entity.sex = payload.sex ?? entity.sex;
464 entity.sex = payload.sex ?? entity.sex;
381 entity.characterId = payload.characterId ?? entity.characterId ?? null;
465 entity.characterId = payload.characterId ?? entity.characterId ?? null;
466 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
467 entity.hostile = !!payload.hostile;
468 entity.talkable = !!payload.talkable;
469 entity.untargetable = !!payload.untargetable;
470 entity.freeFlight = !!payload.freeFlight;
382 if (payload.firstName)
471 if (payload.firstName)
383 { entity.firstName = payload.firstName; }
472 { entity.firstName = payload.firstName; }
384 if (payload.lastName)
473 if (payload.lastName)
385 { entity.lastName = payload.lastName; }
474 { entity.lastName = payload.lastName; }
386 entity.firstName = entity.firstName ?? "";
475 entity.firstName = entity.firstName ?? "";
387 entity.lastName = entity.lastName ?? "";
476 entity.lastName = entity.lastName ?? "";
388 entity.visualX = pivot.x;
477 if (payload.worldX != null && payload.worldY != null)
389 entity.visualY = pivot.y;
478 {
390 entity.fromX = pivot.x;
479 entity.worldX = payload.worldX;
391 entity.fromY = pivot.y;
480 entity.worldY = payload.worldY;
481 entity.visualX = payload.worldX * size;
482 entity.visualY = payload.worldY * size;
483 entity.targetX = entity.visualX;
484 entity.targetY = entity.visualY;
485 }
486 else
487 {
488 entity.visualX = pivot.x;
489 entity.visualY = pivot.y;
490 entity.targetX = pivot.x;
491 entity.targetY = pivot.y;
492 }
493 entity.fromX = entity.visualX;
494 entity.fromY = entity.visualY;
392 if (payload.layers)
495 if (payload.layers)
393 { this.#applyLayers(entity, payload.layers); }
496 { this.#applyLayers(entity, payload.layers); }
394 this.#placeEntity(entity);
497 this.#placeEntity(entity);
@@ -399,7 +502,10 @@ export class WorldView
399 const base = layers[0]?.sprite
502 const base = layers[0]?.sprite
400 ?? bodySpriteName(entity.sex);
503 ?? bodySpriteName(entity.sex);
401 if (this.game.images[base])
504 if (this.game.images[base])
402 { entity.object.renderer.sprite = this.game.images[base]; }
505 {
506 entity.object.renderer.sprite = this.game.images[base];
507 this.#startIdleAnimation(entity.object);
508 }
403 for (const overlay of entity.overlays ?? [])
509 for (const overlay of entity.overlays ?? [])
404 { overlay.destroy(); }
510 { overlay.destroy(); }
405 for (const overlay of entity.bloomOverlays ?? [])
511 for (const overlay of entity.bloomOverlays ?? [])
@@ -432,24 +538,142 @@ export class WorldView
432 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
538 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
433 for (const overlay of entity.bloomOverlays ?? [])
539 for (const overlay of entity.bloomOverlays ?? [])
434 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
540 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
541 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
435 }
542 }
436
543
437 #rebuildChunk (snapshot)
544 #rebuildChunk (snapshot)
438 {
545 {
546 this.#bakeAndPlaceChunk(snapshot);
547 const tall = new Set(
548 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
549 .map((entry) => `${entry.tileX},${entry.tileY}`)
550 );
439 for (let localY = 0; localY < CHUNK_SIZE; localY++)
551 for (let localY = 0; localY < CHUNK_SIZE; localY++)
440 {
552 {
441 for (let localX = 0; localX < CHUNK_SIZE; localX++)
553 for (let localX = 0; localX < CHUNK_SIZE; localX++)
442 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
554 {
555 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
556 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
557 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
558 }
443 }
559 }
444 }
560 }
445
561
446 #redrawPreview ()
562 #redrawPreview ()
447 {
563 {
448 if (this.preview)
564 if (!this.preview)
449 { this.#drawTile(this.preview.tileX, this.preview.tileY); }
565 { return; }
566 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
567 if (snapshot)
568 { this.#rebuildChunk(snapshot); }
569 }
570
571 #bakeAndPlaceChunk (snapshot)
572 {
573 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
574 const atlases = bakeChunkAtlases({
575 snapshot,
576 catalog: this.catalog,
577 images: this.game.images,
578 preview: this.preview
579 });
580 let baked = this.bakedChunks.get(key);
581 if (!baked)
582 {
583 baked = {
584 groundCanvas: atlases.ground,
585 blockCanvases: atlases.blockRows,
586 bloomCanvas: atlases.bloom,
587 groundImage: frameworkImageFromCanvas(atlases.ground),
588 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
589 bloomImage: frameworkImageFromCanvas(atlases.bloom),
590 groundObject: null,
591 blockObjects: [],
592 bloomObject: null,
593 tallBlocks: atlases.tallBlocks
594 };
595 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
596 this.scene.addObject(baked.groundObject);
597 for (let row = 0; row < CHUNK_SIZE; row++)
598 {
599 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
600 this.scene.addObject(object);
601 baked.blockObjects.push(object);
602 }
603 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
604 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
605 this.scene.addObject(baked.bloomObject);
606 this.bakedChunks.set(key, baked);
607 }
608 else
609 {
610 copyCanvas(atlases.ground, baked.groundCanvas);
611 for (let row = 0; row < CHUNK_SIZE; row++)
612 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
613 copyCanvas(atlases.bloom, baked.bloomCanvas);
614 invalidateCanvasTexture(this.scene, baked.groundCanvas);
615 for (const canvas of baked.blockCanvases)
616 { invalidateCanvasTexture(this.scene, canvas); }
617 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
618 baked.tallBlocks = atlases.tallBlocks;
619 }
620 this.#layoutBakedChunk(snapshot);
450 }
621 }
451
622
452 #drawTile (tileX, tileY)
623 #layoutBakedChunk (snapshot)
624 {
625 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
626 const baked = this.bakedChunks.get(key);
627 if (!baked)
628 { return; }
629 const size = this.tileSize();
630 const left = snapshot.chunkX * CHUNK_SIZE * size;
631 const top = snapshot.chunkY * CHUNK_SIZE * size;
632 const chunkPx = CHUNK_SIZE * size;
633 baked.groundObject.transform.position.x = left + chunkPx / 2;
634 baked.groundObject.transform.position.y = top + chunkPx / 2;
635 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
636 baked.groundObject.layer = LAYER_GROUND;
637
638 for (let row = 0; row < CHUNK_SIZE; row++)
639 {
640 const object = baked.blockObjects[row];
641 const rowY = top + row * size + size / 2;
642 object.transform.position.x = left + chunkPx / 2;
643 object.transform.position.y = rowY;
644 object.transform.size = new vector(chunkPx, size);
645 object.layer = ySortLayer(rowY, SORT_BLOCK);
646 }
647
648 baked.bloomObject.transform.position.x = left + chunkPx / 2;
649 baked.bloomObject.transform.position.y = top + chunkPx / 2;
650 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
651 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
652 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
653 this.#markSortDirty();
654 setNearestFilter(this.scene, baked.groundCanvas);
655 for (const canvas of baked.blockCanvases)
656 { setNearestFilter(this.scene, canvas); }
657 setNearestFilter(this.scene, baked.bloomCanvas);
658 }
659
660 #destroyBakedChunk (key)
661 {
662 const baked = this.bakedChunks.get(key);
663 if (!baked)
664 { return; }
665 baked.groundObject?.destroy();
666 for (const object of baked.blockObjects ?? [])
667 { object.destroy(); }
668 baked.bloomObject?.destroy();
669 invalidateCanvasTexture(this.scene, baked.groundCanvas);
670 for (const canvas of baked.blockCanvases ?? [])
671 { invalidateCanvasTexture(this.scene, canvas); }
672 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
673 this.bakedChunks.delete(key);
674 }
675
676 #drawTile (tileX, tileY, forceTall = null)
453 {
677 {
454 const chunkX = Math.floor(tileX / CHUNK_SIZE);
678 const chunkX = Math.floor(tileX / CHUNK_SIZE);
455 const chunkY = Math.floor(tileY / CHUNK_SIZE);
679 const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -463,116 +687,90 @@ export class WorldView
463 let objects = this.tiles.get(key);
687 let objects = this.tiles.get(key);
464 if (!objects)
688 if (!objects)
465 {
689 {
466 objects = { chunkX, chunkY };
690 objects = { chunkX, chunkY, tileX, tileY };
467 this.tiles.set(key, objects);
691 this.tiles.set(key, objects);
468 }
692 }
469
693 objects.tileX = tileX;
470 let ground = snapshot.grounds[index];
694 objects.tileY = tileY;
471 let block = snapshot.blocks[index];
695 objects.chunkX = chunkX;
472 const preview = this.preview;
696 objects.chunkY = chunkY;
473 if (preview && preview.tileX === tileX && preview.tileY === tileY)
474 {
475 if (preview.ground !== undefined)
476 { ground = preview.ground; }
477 if (preview.block !== undefined)
478 { block = preview.block; }
479 }
480
697
481 const size = this.tileSize();
698 const size = this.tileSize();
482 const pivot = tilePivot(tileX, tileY, size);
699 const pivot = tilePivot(tileX, tileY, size);
483 const groundName = this.#groundSpriteName(ground);
700 objects.light = snapshot.light[index] ?? 0;
484 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
701 const previousShade = objects.shade;
485 if (objects.ground)
702 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
486 {
703 if (objects.shade && objects.shade !== previousShade)
487 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
704 { objects.shade.renderer.alpha = 0; }
488 objects.ground.layer = LAYER_GROUND;
489 }
490 objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, this.#groundBloomName(ground), pivot);
491
705
492 const blockName = this.#blockSpriteName(block);
706 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
493 if (blockName)
707 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
708 const isTall = forceTall === true || !!tallEntry;
709 if (isTall && tallEntry)
494 {
710 {
495 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
711 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
496 if (objects.block)
712 if (objects.block)
497 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); }
713 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
714 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
715 objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
498 }
716 }
499 else if (objects.block)
717 else
500 {
718 {
501 objects.block.destroy();
719 if (objects.block)
502 objects.block = null;
720 {
721 objects.block.destroy();
722 objects.block = null;
723 }
724 if (objects.blockBloom)
725 {
726 objects.blockBloom.destroy();
727 objects.blockBloom = null;
728 }
729 if (objects.spriteShade)
730 {
731 objects.spriteShade.destroy();
732 objects.spriteShade = null;
733 }
503 }
734 }
504 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, this.#blockBloomName(block), pivot);
505
506 objects.light = snapshot.light[index] ?? 0;
507 const previousShade = objects.shade;
508 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
509 if (objects.shade && objects.shade !== previousShade)
510 { objects.shade.renderer.alpha = 0; }
511 }
735 }
512
736
513 #groundSpriteName (ground)
737 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
514 {
515 const entry = normalizeGround(ground);
516 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
517 const states = this.catalog.grounds?.[def.key]?.states ?? [];
518 const state = resolveState(states, entry.state);
519 return spriteImageName("ground", def.key, state);
520 }
521
522 #blockSpriteName (block)
523 {
524 const entry = normalizeBlock(block);
525 if (!entry)
526 { return null; }
527 const def = BLOCK_DEFINITIONS[entry.typeId];
528 if (!def)
529 { return null; }
530 const states = this.catalog.blocks?.[def.key]?.states ?? [];
531 const state = resolveState(states, entry.state);
532 return spriteImageName("block", def.key, state);
533 }
534
535 #groundBloomName (ground)
536 {
537 const entry = normalizeGround(ground);
538 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
539 const type = this.catalog.grounds?.[def.key];
540 const state = resolveState(type?.states ?? [], entry.state);
541 if (!state || !type?.blooms?.[state])
542 { return null; }
543 return bloomImageName("ground", def.key, state);
544 }
545
546 #blockBloomName (block)
547 {
548 const entry = normalizeBlock(block);
549 if (!entry)
550 { return null; }
551 const def = BLOCK_DEFINITIONS[entry.typeId];
552 if (!def)
553 { return null; }
554 const type = this.catalog.blocks?.[def.key];
555 const state = resolveState(type?.states ?? [], entry.state);
556 if (!state || !type?.blooms?.[state])
557 { return null; }
558 return bloomImageName("block", def.key, state);
559 }
560
561 #placeBloomOverlay (existing, name, pivot)
562 {
738 {
563 if (!name)
739 if (!name)
564 {
740 {
565 existing?.destroy();
741 existing?.destroy();
566 return null;
742 return null;
567 }
743 }
568 const object = this.#ensureSprite(existing, name, SORT_BLOCK);
744 const object = this.#ensureSprite(existing, name, sortOrder);
569 if (!object)
745 if (!object)
570 { return null; }
746 { return null; }
571 object.renderer.layer = RENDER_LAYER_BLOOM;
747 object.renderer.layer = RENDER_LAYER_BLOOM;
572 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
748 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
573 return object;
749 return object;
574 }
750 }
575
751
752 #placeSpriteShade (existing, targetObject, pivotX, pivotY)
753 {
754 if (!targetObject?.renderer?.sprite)
755 {
756 existing?.destroy();
757 return null;
758 }
759 const shade = this.#ensureSprite(existing, "night-shade", SORT_SPRITE_SHADE);
760 if (!shade)
761 { return null; }
762 const sprite = targetObject.renderer.sprite;
763 const zoom = this.zoom;
764 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
765 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
766 shade.transform.position.x = center.x;
767 shade.transform.position.y = center.y;
768 shade.transform.size = new vector(draw.w, draw.h);
769 shade.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
770 this.#markSortDirty();
771 return shade;
772 }
773
576 #tileFill (existing, name, x, y, layer)
774 #tileFill (existing, name, x, y, layer)
577 {
775 {
578 existing = this.#ensureSprite(existing, name, layer);
776 existing = this.#ensureSprite(existing, name, layer);
@@ -615,12 +813,18 @@ export class WorldView
615 existing?.destroy();
813 existing?.destroy();
616 existing = new GameObject(0, 0, sprite, layer);
814 existing = new GameObject(0, 0, sprite, layer);
617 this.scene.addObject(existing);
815 this.scene.addObject(existing);
618 if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
816 this.#startIdleAnimation(existing);
619 { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
620 }
817 }
621 return existing;
818 return existing;
622 }
819 }
623
820
821 #startIdleAnimation (object)
822 {
823 const sprite = object?.renderer?.sprite;
824 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
825 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
826 }
827
624 #neighborClosed (snapshot, dir, dx, dy)
828 #neighborClosed (snapshot, dir, dx, dy)
625 {
829 {
626 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
830 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
@@ -716,15 +920,50 @@ export class WorldView
716 {
920 {
717 const hour = this.nightPreview ?? this.worldHour;
921 const hour = this.nightPreview ?? this.worldHour;
718 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
922 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
923 const now = performance.now();
924 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
719 for (const objects of this.tiles.values())
925 for (const objects of this.tiles.values())
720 {
926 {
721 if (!objects.shade)
927 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
928 let dynamic = 0;
929 for (const light of this.dynamicLights)
930 {
931 const dx = (objects.tileX + 0.5) - light.worldX;
932 const dy = (objects.tileY + 0.5) - light.worldY;
933 const dist = Math.hypot(dx, dy);
934 if (dist >= light.radiusTiles)
935 { continue; }
936 const falloff = 1 - dist / light.radiusTiles;
937 dynamic = Math.max(dynamic, falloff * light.intensity);
938 }
939 const intensity = Math.max(baked, dynamic);
940 const alpha = ambientDark * (1 - intensity);
941 objects.shadeAlpha = alpha;
942 if (objects.shade)
943 { objects.shade.renderer.alpha = alpha; }
944 if (objects.spriteShade)
945 { objects.spriteShade.renderer.alpha = alpha; }
946 }
947 for (const entity of this.entities.values())
948 {
949 if (!entity.spriteShade)
722 { continue; }
950 { continue; }
723 const intensity = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
951 const tile = this.tiles.get(`${entity.tileX},${entity.tileY}`);
724 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
952 entity.spriteShade.renderer.alpha = tile?.shadeAlpha ?? 0;
725 }
953 }
726 }
954 }
727
955
956 #updateSwipes (now)
957 {
958 this.swipes = this.swipes.filter((swipe) =>
959 {
960 if (swipe.until > now)
961 { return true; }
962 swipe.object?.destroy();
963 return false;
964 });
965 }
966
728 #syncBloomLayer ()
967 #syncBloomLayer ()
729 {
968 {
730 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
969 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
@@ -771,3 +1010,25 @@ function lerp (a, b, t)
771{
1010{
772 return a + (b - a) * Math.min(1, Math.max(0, t));
1011 return a + (b - a) * Math.min(1, Math.max(0, t));
773}
1012}
1013
1014function copyCanvas (source, dest)
1015{
1016 const ctx = dest.getContext("2d");
1017 ctx.imageSmoothingEnabled = false;
1018 ctx.clearRect(0, 0, dest.width, dest.height);
1019 ctx.drawImage(source, 0, 0);
1020}
1021
1022function setNearestFilter (scene, canvas)
1023{
1024 const glContext = scene?.glContext;
1025 if (!glContext || !canvas)
1026 { return; }
1027 const texture = glContext.getTexture(canvas);
1028 if (!texture)
1029 { return; }
1030 const gl = glContext.gl;
1031 gl.bindTexture(gl.TEXTURE_2D, texture);
1032 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1033 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1034}
client/ui/play.css +31 −0
@@ -78,6 +78,37 @@ a { color: #d4c48a; }
78 78 font-size: 0.85rem;
79 79 }
80 80
81 #context-menu {
82 position: fixed;
83 z-index: 20;
84 min-width: 140px;
85 background: #161a22;
86 border: 1px solid #3a4250;
87 padding: 0.25rem;
88 display: flex;
89 flex-direction: column;
90 gap: 0.15rem;
91 }
92
93 #context-menu[hidden] {
94 display: none !important;
95 }
96
97 #context-menu button {
98 display: block;
99 width: 100%;
100 text-align: left;
101 background: transparent;
102 border: 0;
103 color: #e8ecf4;
104 padding: 0.35rem 0.55rem;
105 cursor: pointer;
106 }
107
108 #context-menu button:hover {
109 background: #2a3140;
110 }
111
81 112 #inspect-backdrop {
82 113 position: fixed;
83 114 inset: 0;
@@ -78,6 +78,37 @@ a { color: #d4c48a; }
78 font-size: 0.85rem;
78 font-size: 0.85rem;
79}
79}
80
80
81#context-menu {
82 position: fixed;
83 z-index: 20;
84 min-width: 140px;
85 background: #161a22;
86 border: 1px solid #3a4250;
87 padding: 0.25rem;
88 display: flex;
89 flex-direction: column;
90 gap: 0.15rem;
91}
92
93#context-menu[hidden] {
94 display: none !important;
95}
96
97#context-menu button {
98 display: block;
99 width: 100%;
100 text-align: left;
101 background: transparent;
102 border: 0;
103 color: #e8ecf4;
104 padding: 0.35rem 0.55rem;
105 cursor: pointer;
106}
107
108#context-menu button:hover {
109 background: #2a3140;
110}
111
81#inspect-backdrop {
112#inspect-backdrop {
82 position: fixed;
113 position: fixed;
83 inset: 0;
114 inset: 0;
docs/FEATURES.md +17 −11
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16 16 ## Ground and block tile layers
17 17
18 18 **Status:** full
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states.
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21 21
22 22 ## Open and closed chunks
23 23
@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136 136 ## Night shading
137 137
138 138 **Status:** full
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle.
140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades.
140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`), `server/src/simulation/simulation.js` (`worldTime`)
141 141
142 142 ## FrameworkV3 client bootstrap
143 143
@@ -148,8 +148,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
148 148 ## Sprite size, pivot and Y-sort
149 149
150 150 **Status:** full
151 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets.
152 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
151 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
152 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
153 153
154 154 ## Visual tile states
155 155
@@ -178,8 +178,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178 178 ## Spawners
179 179
180 180 **Status:** full
181 **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Placeholder deer art until real sprites exist.
182 **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`
181 **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and hostile rats. Pigeons are not ambient wildlife.
182 **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
183
184 ## Character logout resume
185
186 **Status:** full
187 **Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
188 **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
183 189
184 190 ## Inventory, items, equipment, ground drops
185 191
@@ -189,9 +195,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
189 195
190 196 ## Combat, skills, groups, pigeons
191 197
192 **Status:** not implemented
193 **Spec:** Later systems described in the design. Not part of this playable basis. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
194 **Code:** —
198 **Status:** partial
199 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. Ranged/spells/groups/pigeon dispatch remain design-only.
200 **Code:** `shared/definitions/skills.js`, `server/src/simulation/follow.js`, combat tick, `client/src/play/` context menu + swipe, tests in `server/tests/combat.test.js` / `server/tests/follow.test.js`
195 201
196 202 ## Proximity chat
197 203
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16## Ground and block tile layers
16## Ground and block tile layers
17
17
18**Status:** full
18**Status:** full
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states.
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21
21
22## Open and closed chunks
22## Open and closed chunks
23
23
@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136## Night shading
136## Night shading
137
137
138**Status:** full
138**Status:** full
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle.
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades.
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`), `server/src/simulation/simulation.js` (`worldTime`)
141
141
142## FrameworkV3 client bootstrap
142## FrameworkV3 client bootstrap
143
143
@@ -148,8 +148,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
148## Sprite size, pivot and Y-sort
148## Sprite size, pivot and Y-sort
149
149
150**Status:** full
150**Status:** full
151**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets.
151**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
152**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
152**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
153
153
154## Visual tile states
154## Visual tile states
155
155
@@ -178,8 +178,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178## Spawners
178## Spawners
179
179
180**Status:** full
180**Status:** full
181**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Placeholder deer art until real sprites exist.
181**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and hostile rats. Pigeons are not ambient wildlife.
182**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`
182**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
183
184## Character logout resume
185
186**Status:** full
187**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
188**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
183
189
184## Inventory, items, equipment, ground drops
190## Inventory, items, equipment, ground drops
185
191
@@ -189,9 +195,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
189
195
190## Combat, skills, groups, pigeons
196## Combat, skills, groups, pigeons
191
197
192**Status:** not implemented
198**Status:** partial
193**Spec:** Later systems described in the design. Not part of this playable basis. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
199**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. Ranged/spells/groups/pigeon dispatch remain design-only.
194**Code:** —
200**Code:** `shared/definitions/skills.js`, `server/src/simulation/follow.js`, combat tick, `client/src/play/` context menu + swipe, tests in `server/tests/combat.test.js` / `server/tests/follow.test.js`
195
201
196## Proximity chat
202## Proximity chat
197
203
server/src/assets/spriteCatalog.js +54 −3
@@ -22,20 +22,23 @@ export function buildSpriteCatalog (assetRoot)
22 22 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
23 23 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
24 24 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
25 const mobs = scanLayer(join(assetRoot, "mobs"), mobScanDefs(), "mob", "mobs");
25 const mobs = scanMobLayers(assetRoot);
26 26 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
27 const fx = scanFx(join(assetRoot, "fx"));
27 28 return {
28 29 grounds: grounds.types,
29 30 blocks: blocks.types,
30 31 items: items.types,
31 32 mobs: mobs.types,
32 33 characters: characters.types,
34 fx: fx.types,
33 35 images: [
34 36 ...grounds.images,
35 37 ...blocks.images,
36 38 ...items.images,
37 39 ...mobs.images,
38 ...characters.images
40 ...characters.images,
41 ...fx.images
39 42 ]
40 43 };
41 44 }
@@ -67,12 +70,60 @@ function mobScanDefs ()
67 70 id: def.mobTypeId,
68 71 frames: def.frames ?? 1,
69 72 framesPerRow: def.framesPerRow ?? 1,
70 animationSpeed: def.animationSpeed ?? 0
73 animationSpeed: def.animationSpeed ?? 0,
74 assetFolder: def.assetFolder ?? "mobs"
71 75 };
72 76 }
73 77 return defs;
74 78 }
75 79
80 function scanMobLayers (assetRoot)
81 {
82 const byFolder = new Map();
83 for (const def of Object.values(mobScanDefs()))
84 {
85 const folder = def.assetFolder ?? "mobs";
86 if (!byFolder.has(folder))
87 { byFolder.set(folder, {}); }
88 byFolder.get(folder)[def.key] = def;
89 }
90 const types = {};
91 const images = [];
92 for (const [folder, defs] of byFolder)
93 {
94 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
95 Object.assign(types, scanned.types);
96 images.push(...scanned.images);
97 }
98 return { types, images };
99 }
100
101 function scanFx (fxRoot)
102 {
103 const types = {};
104 const images = [];
105 let folders;
106 try
107 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
108 catch (error)
109 {
110 if (error.code === "ENOENT")
111 { return { types, images }; }
112 throw error;
113 }
114 for (const entry of folders)
115 {
116 const key = entry.name;
117 const defs = {
118 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
119 };
120 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
121 Object.assign(types, scanned.types);
122 images.push(...scanned.images);
123 }
124 return { types, images };
125 }
126
76 127 function scanLayer (layerDir, definitions, layer, urlFolder)
77 128 {
78 129 const types = {};
@@ -22,20 +22,23 @@ export function buildSpriteCatalog (assetRoot)
22 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
22 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
23 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
23 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
24 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
24 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
25 const mobs = scanLayer(join(assetRoot, "mobs"), mobScanDefs(), "mob", "mobs");
25 const mobs = scanMobLayers(assetRoot);
26 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
26 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
27 const fx = scanFx(join(assetRoot, "fx"));
27 return {
28 return {
28 grounds: grounds.types,
29 grounds: grounds.types,
29 blocks: blocks.types,
30 blocks: blocks.types,
30 items: items.types,
31 items: items.types,
31 mobs: mobs.types,
32 mobs: mobs.types,
32 characters: characters.types,
33 characters: characters.types,
34 fx: fx.types,
33 images: [
35 images: [
34 ...grounds.images,
36 ...grounds.images,
35 ...blocks.images,
37 ...blocks.images,
36 ...items.images,
38 ...items.images,
37 ...mobs.images,
39 ...mobs.images,
38 ...characters.images
40 ...characters.images,
41 ...fx.images
39 ]
42 ]
40 };
43 };
41}
44}
@@ -67,12 +70,60 @@ function mobScanDefs ()
67 id: def.mobTypeId,
70 id: def.mobTypeId,
68 frames: def.frames ?? 1,
71 frames: def.frames ?? 1,
69 framesPerRow: def.framesPerRow ?? 1,
72 framesPerRow: def.framesPerRow ?? 1,
70 animationSpeed: def.animationSpeed ?? 0
73 animationSpeed: def.animationSpeed ?? 0,
74 assetFolder: def.assetFolder ?? "mobs"
71 };
75 };
72 }
76 }
73 return defs;
77 return defs;
74}
78}
75
79
80function scanMobLayers (assetRoot)
81{
82 const byFolder = new Map();
83 for (const def of Object.values(mobScanDefs()))
84 {
85 const folder = def.assetFolder ?? "mobs";
86 if (!byFolder.has(folder))
87 { byFolder.set(folder, {}); }
88 byFolder.get(folder)[def.key] = def;
89 }
90 const types = {};
91 const images = [];
92 for (const [folder, defs] of byFolder)
93 {
94 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
95 Object.assign(types, scanned.types);
96 images.push(...scanned.images);
97 }
98 return { types, images };
99}
100
101function scanFx (fxRoot)
102{
103 const types = {};
104 const images = [];
105 let folders;
106 try
107 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
108 catch (error)
109 {
110 if (error.code === "ENOENT")
111 { return { types, images }; }
112 throw error;
113 }
114 for (const entry of folders)
115 {
116 const key = entry.name;
117 const defs = {
118 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
119 };
120 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
121 Object.assign(types, scanned.types);
122 images.push(...scanned.images);
123 }
124 return { types, images };
125}
126
76function scanLayer (layerDir, definitions, layer, urlFolder)
127function scanLayer (layerDir, definitions, layer, urlFolder)
77{
128{
78 const types = {};
129 const types = {};
server/src/combat/service.js added +237 −0
@@ -0,0 +1,237 @@
1 import { Component } from "../ecs/components.js";
2 import { itemDefinition } from "../../../shared/definitions/items.js";
3 import { mobDefinition } from "../../../shared/definitions/mobs.js";
4 import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
5 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
7
8 export function chebyshev (ax, ay, bx, by)
9 {
10 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
11 }
12
13 export function attackProfileOf (ecs, handle)
14 {
15 const equipment = ecs.get(handle, Component.equipment);
16 const weapon = equipment?.slots?.weapon;
17 if (weapon?.itemId != null)
18 {
19 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
20 if (attack)
21 { return { ...attack }; }
22 }
23 const creature = ecs.get(handle, Component.creature);
24 const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null;
25 if (mobAttack)
26 { return { ...mobAttack }; }
27 return { ...UNARMED_ATTACK };
28 }
29
30 export function isUntargetable (ecs, handle)
31 {
32 const creature = ecs.get(handle, Component.creature);
33 if (!creature)
34 { return false; }
35 return !!mobDefinition(creature.mobTypeId)?.untargetable;
36 }
37
38 export function engageTarget (ecs, attackerId, targetId, now = Date.now())
39 {
40 const handle = ecs.handleOf(attackerId);
41 if (handle == null)
42 { return false; }
43 let combat = ecs.get(handle, Component.combat);
44 if (!combat)
45 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
46 combat.targetEntityId = targetId;
47 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
48 return true;
49 }
50
51 export function clearEngage (ecs, entityId)
52 {
53 const handle = ecs.handleOf(entityId);
54 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
55 if (combat)
56 { combat.targetEntityId = null; }
57 }
58
59 export function stepCombat (world, now = Date.now())
60 {
61 const events = [];
62 for (const entity of world.ecs.query(Component.combat, Component.position))
63 {
64 const combat = entity.combat;
65 const targetId = combat.targetEntityId;
66 if (targetId == null)
67 { continue; }
68 const targetHandle = world.ecs.handleOf(targetId);
69 if (targetHandle == null)
70 {
71 combat.targetEntityId = null;
72 continue;
73 }
74 if (isUntargetable(world.ecs, targetHandle))
75 {
76 combat.targetEntityId = null;
77 continue;
78 }
79 const targetPos = world.ecs.get(targetHandle, Component.position);
80 const targetHealth = world.ecs.get(targetHandle, Component.health);
81 if (!targetPos || !targetHealth || targetHealth.current <= 0)
82 {
83 combat.targetEntityId = null;
84 continue;
85 }
86
87 const profile = attackProfileOf(world.ecs, entity.handle);
88 if (profile.mode !== "melee")
89 { continue; }
90
91 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
92 if (dist > 1)
93 {
94 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
95 continue;
96 }
97 if (dist !== 1)
98 { continue; }
99 if ((combat.nextSwingAt || 0) > now)
100 { continue; }
101
102 combat.nextSwingAt = now + (profile.cooldownMs || 800);
103 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
104 }
105 return events;
106 }
107
108 function queueMeleeApproach (world, entityId, handle, position, targetPos)
109 {
110 if (world.frozen?.has?.(entityId))
111 { return; }
112 let path = world.ecs.get(handle, Component.path);
113 if (!path)
114 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
115 if (path.tiles?.length)
116 { return; }
117 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
118 if (!goal)
119 { return; }
120 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
121 path.tiles = findPath(
122 position.tileX,
123 position.tileY,
124 goal.x,
125 goal.y,
126 (x, y) => world.walkableFor(entityId, x, y),
127 bounds.minX,
128 bounds.minY,
129 bounds.maxX,
130 bounds.maxY
131 );
132 const movement = world.ecs.get(handle, Component.movement);
133 if (movement)
134 { movement.walkCarry = 0; }
135 }
136
137 function bestAdjacentGoal (world, entityId, position, targetPos)
138 {
139 const dirs = [
140 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
141 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
142 ];
143 let best = null;
144 let bestDist = Infinity;
145 for (const dir of dirs)
146 {
147 const x = targetPos.tileX + dir.x;
148 const y = targetPos.tileY + dir.y;
149 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
150 { continue; }
151 const dist = chebyshev(position.tileX, position.tileY, x, y);
152 if (dist < bestDist)
153 {
154 bestDist = dist;
155 best = { x, y };
156 }
157 }
158 return best;
159 }
160
161 export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
162 {
163 const events = [];
164 const attackerHandle = world.ecs.handleOf(attackerId);
165 const targetHandle = world.ecs.handleOf(targetId);
166 if (attackerHandle == null || targetHandle == null)
167 { return events; }
168 const from = world.ecs.get(attackerHandle, Component.position);
169 const to = world.ecs.get(targetHandle, Component.position);
170 if (!from || !to)
171 { return events; }
172
173 events.push({
174 type: "combat-swing",
175 attackerId,
176 targetId,
177 tileX: to.tileX,
178 tileY: to.tileY,
179 fromTileX: from.tileX,
180 fromTileY: from.tileY
181 });
182
183 const skills = world.ecs.get(attackerHandle, Component.skills);
184 const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03);
185 const hit = Math.random() < hitChance;
186 if (!hit)
187 {
188 events.push({
189 type: "combat-miss",
190 attackerId,
191 targetId,
192 tileX: to.tileX,
193 tileY: to.tileY
194 });
195 return events;
196 }
197
198 const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5));
199 const health = world.ecs.get(targetHandle, Component.health);
200 if (health)
201 {
202 health.current = Math.max(0, (health.current | 0) - damage);
203 }
204 events.push({
205 type: "combat-hit",
206 attackerId,
207 targetId,
208 damage,
209 tileX: to.tileX,
210 tileY: to.tileY,
211 health: health?.current ?? 0
212 });
213
214 if (world.ecs.get(targetHandle, Component.combat))
215 { engageTarget(world.ecs, targetId, attackerId, now); }
216
217 if (health && health.current <= 0)
218 {
219 clearEngage(world.ecs, attackerId);
220 clearEngage(world.ecs, targetId);
221 const creature = world.ecs.get(targetHandle, Component.creature);
222 if (creature && !world.ecs.get(targetHandle, Component.character))
223 {
224 const view = world.destroyEntity?.(targetId) ?? null;
225 if (view)
226 {
227 events.push({
228 type: "entity-despawn",
229 entityId: targetId,
230 tileX: view.tileX,
231 tileY: view.tileY
232 });
233 }
234 }
235 }
236 return events;
237 }
@@ -0,0 +1,237 @@
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
5import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
7
8export function chebyshev (ax, ay, bx, by)
9{
10 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
11}
12
13export function attackProfileOf (ecs, handle)
14{
15 const equipment = ecs.get(handle, Component.equipment);
16 const weapon = equipment?.slots?.weapon;
17 if (weapon?.itemId != null)
18 {
19 const attack = itemDefinition(weapon.itemId)?.equipment?.attack;
20 if (attack)
21 { return { ...attack }; }
22 }
23 const creature = ecs.get(handle, Component.creature);
24 const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null;
25 if (mobAttack)
26 { return { ...mobAttack }; }
27 return { ...UNARMED_ATTACK };
28}
29
30export function isUntargetable (ecs, handle)
31{
32 const creature = ecs.get(handle, Component.creature);
33 if (!creature)
34 { return false; }
35 return !!mobDefinition(creature.mobTypeId)?.untargetable;
36}
37
38export function engageTarget (ecs, attackerId, targetId, now = Date.now())
39{
40 const handle = ecs.handleOf(attackerId);
41 if (handle == null)
42 { return false; }
43 let combat = ecs.get(handle, Component.combat);
44 if (!combat)
45 { combat = ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
46 combat.targetEntityId = targetId;
47 combat.nextSwingAt = Math.min(combat.nextSwingAt || 0, now);
48 return true;
49}
50
51export function clearEngage (ecs, entityId)
52{
53 const handle = ecs.handleOf(entityId);
54 const combat = handle != null ? ecs.get(handle, Component.combat) : null;
55 if (combat)
56 { combat.targetEntityId = null; }
57}
58
59export function stepCombat (world, now = Date.now())
60{
61 const events = [];
62 for (const entity of world.ecs.query(Component.combat, Component.position))
63 {
64 const combat = entity.combat;
65 const targetId = combat.targetEntityId;
66 if (targetId == null)
67 { continue; }
68 const targetHandle = world.ecs.handleOf(targetId);
69 if (targetHandle == null)
70 {
71 combat.targetEntityId = null;
72 continue;
73 }
74 if (isUntargetable(world.ecs, targetHandle))
75 {
76 combat.targetEntityId = null;
77 continue;
78 }
79 const targetPos = world.ecs.get(targetHandle, Component.position);
80 const targetHealth = world.ecs.get(targetHandle, Component.health);
81 if (!targetPos || !targetHealth || targetHealth.current <= 0)
82 {
83 combat.targetEntityId = null;
84 continue;
85 }
86
87 const profile = attackProfileOf(world.ecs, entity.handle);
88 if (profile.mode !== "melee")
89 { continue; }
90
91 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
92 if (dist > 1)
93 {
94 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
95 continue;
96 }
97 if (dist !== 1)
98 { continue; }
99 if ((combat.nextSwingAt || 0) > now)
100 { continue; }
101
102 combat.nextSwingAt = now + (profile.cooldownMs || 800);
103 events.push(...resolveMeleeSwing(world, entity.entityId, targetId, profile, now));
104 }
105 return events;
106}
107
108function queueMeleeApproach (world, entityId, handle, position, targetPos)
109{
110 if (world.frozen?.has?.(entityId))
111 { return; }
112 let path = world.ecs.get(handle, Component.path);
113 if (!path)
114 { path = world.ecs.add(handle, Component.path, { tiles: [] }); }
115 if (path.tiles?.length)
116 { return; }
117 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
118 if (!goal)
119 { return; }
120 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
121 path.tiles = findPath(
122 position.tileX,
123 position.tileY,
124 goal.x,
125 goal.y,
126 (x, y) => world.walkableFor(entityId, x, y),
127 bounds.minX,
128 bounds.minY,
129 bounds.maxX,
130 bounds.maxY
131 );
132 const movement = world.ecs.get(handle, Component.movement);
133 if (movement)
134 { movement.walkCarry = 0; }
135}
136
137function bestAdjacentGoal (world, entityId, position, targetPos)
138{
139 const dirs = [
140 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
141 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
142 ];
143 let best = null;
144 let bestDist = Infinity;
145 for (const dir of dirs)
146 {
147 const x = targetPos.tileX + dir.x;
148 const y = targetPos.tileY + dir.y;
149 if (!world.walkableFor(entityId, x, y) && !(x === position.tileX && y === position.tileY))
150 { continue; }
151 const dist = chebyshev(position.tileX, position.tileY, x, y);
152 if (dist < bestDist)
153 {
154 bestDist = dist;
155 best = { x, y };
156 }
157 }
158 return best;
159}
160
161export function resolveMeleeSwing (world, attackerId, targetId, profile, now = Date.now())
162{
163 const events = [];
164 const attackerHandle = world.ecs.handleOf(attackerId);
165 const targetHandle = world.ecs.handleOf(targetId);
166 if (attackerHandle == null || targetHandle == null)
167 { return events; }
168 const from = world.ecs.get(attackerHandle, Component.position);
169 const to = world.ecs.get(targetHandle, Component.position);
170 if (!from || !to)
171 { return events; }
172
173 events.push({
174 type: "combat-swing",
175 attackerId,
176 targetId,
177 tileX: to.tileX,
178 tileY: to.tileY,
179 fromTileX: from.tileX,
180 fromTileY: from.tileY
181 });
182
183 const skills = world.ecs.get(attackerHandle, Component.skills);
184 const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03);
185 const hit = Math.random() < hitChance;
186 if (!hit)
187 {
188 events.push({
189 type: "combat-miss",
190 attackerId,
191 targetId,
192 tileX: to.tileX,
193 tileY: to.tileY
194 });
195 return events;
196 }
197
198 const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5));
199 const health = world.ecs.get(targetHandle, Component.health);
200 if (health)
201 {
202 health.current = Math.max(0, (health.current | 0) - damage);
203 }
204 events.push({
205 type: "combat-hit",
206 attackerId,
207 targetId,
208 damage,
209 tileX: to.tileX,
210 tileY: to.tileY,
211 health: health?.current ?? 0
212 });
213
214 if (world.ecs.get(targetHandle, Component.combat))
215 { engageTarget(world.ecs, targetId, attackerId, now); }
216
217 if (health && health.current <= 0)
218 {
219 clearEngage(world.ecs, attackerId);
220 clearEngage(world.ecs, targetId);
221 const creature = world.ecs.get(targetHandle, Component.creature);
222 if (creature && !world.ecs.get(targetHandle, Component.character))
223 {
224 const view = world.destroyEntity?.(targetId) ?? null;
225 if (view)
226 {
227 events.push({
228 type: "entity-despawn",
229 entityId: targetId,
230 tileX: view.tileX,
231 tileY: view.tileY
232 });
233 }
234 }
235 }
236 return events;
237}
server/src/ecs/components.js +5 −1
@@ -2,6 +2,7 @@ export const Component = Object.freeze({
2 2 position: "position",
3 3 movement: "movement",
4 4 path: "path",
5 flight: "flight",
5 6 appearance: "appearance",
6 7 character: "character",
7 8 networkIdentity: "networkIdentity",
@@ -13,5 +14,8 @@ export const Component = Object.freeze({
13 14 vault: "vault",
14 15 health: "health",
15 16 creature: "creature",
16 spawnOrigin: "spawnOrigin"
17 spawnOrigin: "spawnOrigin",
18 combat: "combat",
19 skills: "skills",
20 follow: "follow"
17 21 });
@@ -2,6 +2,7 @@ export const Component = Object.freeze({
2 position: "position",
2 position: "position",
3 movement: "movement",
3 movement: "movement",
4 path: "path",
4 path: "path",
5 flight: "flight",
5 appearance: "appearance",
6 appearance: "appearance",
6 character: "character",
7 character: "character",
7 networkIdentity: "networkIdentity",
8 networkIdentity: "networkIdentity",
@@ -13,5 +14,8 @@ export const Component = Object.freeze({
13 vault: "vault",
14 vault: "vault",
14 health: "health",
15 health: "health",
15 creature: "creature",
16 creature: "creature",
16 spawnOrigin: "spawnOrigin"
17 spawnOrigin: "spawnOrigin",
18 combat: "combat",
19 skills: "skills",
20 follow: "follow"
17});
21});
server/src/ecs/serialize.js +23 −2
@@ -1,6 +1,7 @@
1 1 import { Component } from "./components.js";
2 2 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3 3 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 import { mobDefinition } from "../../../shared/definitions/mobs.js";
4 5
5 6 function bodySprite (sex)
6 7 {
@@ -60,16 +61,26 @@ export function publicEntityView (ecs, entityId)
60 61 const movement = ecs.get(handle, Component.movement);
61 62 const appearance = ecs.get(handle, Component.appearance);
62 63 const character = ecs.get(handle, Component.character);
64 const creature = ecs.get(handle, Component.creature);
65 const flight = ecs.get(handle, Component.flight);
63 66 const layers = appearanceLayers(ecs, handle, appearance);
67 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
64 68 return {
65 69 entityId,
66 70 tileX: position.tileX,
67 71 tileY: position.tileY,
72 worldX: flight?.x ?? position.tileX + 0.5,
73 worldY: flight?.y ?? position.tileY + 0.5,
68 74 gait: movement?.gait ?? "walk",
69 75 sex: appearance?.sex ?? null,
70 76 firstName: appearance?.firstName ?? "",
71 77 lastName: appearance?.lastName ?? "",
72 78 characterId: character?.characterId ?? null,
79 mobTypeId: creature?.mobTypeId ?? null,
80 hostile: !!mob?.hostile,
81 talkable: !!mob?.talkable,
82 untargetable: !!mob?.untargetable,
83 freeFlight: !!mob?.freeFlight,
73 84 sprite: layers[0]?.sprite ?? null,
74 85 layers
75 86 };
@@ -102,12 +113,19 @@ export function replicationSpawn (view)
102 113 characterId: view.characterId,
103 114 tileX: view.tileX,
104 115 tileY: view.tileY,
116 worldX: view.worldX,
117 worldY: view.worldY,
105 118 gait: view.gait,
106 119 sex: view.sex,
107 120 firstName: view.firstName,
108 121 lastName: view.lastName,
109 122 sprite: view.sprite ?? null,
110 layers: view.layers ?? []
123 layers: view.layers ?? [],
124 mobTypeId: view.mobTypeId ?? null,
125 hostile: !!view.hostile,
126 talkable: !!view.talkable,
127 untargetable: !!view.untargetable,
128 freeFlight: !!view.freeFlight
111 129 };
112 130 }
113 131
@@ -120,9 +138,12 @@ export function replicationMove (view, fromTileX, fromTileY)
120 138 entityId: view.entityId,
121 139 tileX: view.tileX,
122 140 tileY: view.tileY,
141 worldX: view.worldX,
142 worldY: view.worldY,
123 143 gait: view.gait,
124 144 fromTileX,
125 fromTileY
145 fromTileY,
146 freeFlight: !!view.freeFlight
126 147 };
127 148 }
128 149
@@ -1,6 +1,7 @@
1import { Component } from "./components.js";
1import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4
5
5function bodySprite (sex)
6function bodySprite (sex)
6{
7{
@@ -60,16 +61,26 @@ export function publicEntityView (ecs, entityId)
60 const movement = ecs.get(handle, Component.movement);
61 const movement = ecs.get(handle, Component.movement);
61 const appearance = ecs.get(handle, Component.appearance);
62 const appearance = ecs.get(handle, Component.appearance);
62 const character = ecs.get(handle, Component.character);
63 const character = ecs.get(handle, Component.character);
64 const creature = ecs.get(handle, Component.creature);
65 const flight = ecs.get(handle, Component.flight);
63 const layers = appearanceLayers(ecs, handle, appearance);
66 const layers = appearanceLayers(ecs, handle, appearance);
67 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
64 return {
68 return {
65 entityId,
69 entityId,
66 tileX: position.tileX,
70 tileX: position.tileX,
67 tileY: position.tileY,
71 tileY: position.tileY,
72 worldX: flight?.x ?? position.tileX + 0.5,
73 worldY: flight?.y ?? position.tileY + 0.5,
68 gait: movement?.gait ?? "walk",
74 gait: movement?.gait ?? "walk",
69 sex: appearance?.sex ?? null,
75 sex: appearance?.sex ?? null,
70 firstName: appearance?.firstName ?? "",
76 firstName: appearance?.firstName ?? "",
71 lastName: appearance?.lastName ?? "",
77 lastName: appearance?.lastName ?? "",
72 characterId: character?.characterId ?? null,
78 characterId: character?.characterId ?? null,
79 mobTypeId: creature?.mobTypeId ?? null,
80 hostile: !!mob?.hostile,
81 talkable: !!mob?.talkable,
82 untargetable: !!mob?.untargetable,
83 freeFlight: !!mob?.freeFlight,
73 sprite: layers[0]?.sprite ?? null,
84 sprite: layers[0]?.sprite ?? null,
74 layers
85 layers
75 };
86 };
@@ -102,12 +113,19 @@ export function replicationSpawn (view)
102 characterId: view.characterId,
113 characterId: view.characterId,
103 tileX: view.tileX,
114 tileX: view.tileX,
104 tileY: view.tileY,
115 tileY: view.tileY,
116 worldX: view.worldX,
117 worldY: view.worldY,
105 gait: view.gait,
118 gait: view.gait,
106 sex: view.sex,
119 sex: view.sex,
107 firstName: view.firstName,
120 firstName: view.firstName,
108 lastName: view.lastName,
121 lastName: view.lastName,
109 sprite: view.sprite ?? null,
122 sprite: view.sprite ?? null,
110 layers: view.layers ?? []
123 layers: view.layers ?? [],
124 mobTypeId: view.mobTypeId ?? null,
125 hostile: !!view.hostile,
126 talkable: !!view.talkable,
127 untargetable: !!view.untargetable,
128 freeFlight: !!view.freeFlight
111 };
129 };
112}
130}
113
131
@@ -120,9 +138,12 @@ export function replicationMove (view, fromTileX, fromTileY)
120 entityId: view.entityId,
138 entityId: view.entityId,
121 tileX: view.tileX,
139 tileX: view.tileX,
122 tileY: view.tileY,
140 tileY: view.tileY,
141 worldX: view.worldX,
142 worldY: view.worldY,
123 gait: view.gait,
143 gait: view.gait,
124 fromTileX,
144 fromTileX,
125 fromTileY
145 fromTileY,
146 freeFlight: !!view.freeFlight
126 };
147 };
127}
148}
128
149
server/src/gateway/websocket.js +74 −3
@@ -199,6 +199,44 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
199 199 });
200 200 }
201 201 break;
202 case MessageType.attack:
203 requirePlaying(session);
204 simulation.enqueue(session.id, {
205 type: "attack",
206 characterId: session.characterId,
207 targetEntityId: message.targetEntityId | 0
208 });
209 break;
210 case MessageType.cancelAttack:
211 requirePlaying(session);
212 simulation.enqueue(session.id, {
213 type: "cancel-attack",
214 characterId: session.characterId
215 });
216 break;
217 case MessageType.interact:
218 requirePlaying(session);
219 simulation.enqueue(session.id, {
220 type: "interact",
221 characterId: session.characterId,
222 targetEntityId: message.targetEntityId | 0
223 });
224 break;
225 case MessageType.follow:
226 requirePlaying(session);
227 simulation.enqueue(session.id, {
228 type: "follow",
229 characterId: session.characterId,
230 targetEntityId: message.targetEntityId | 0
231 });
232 break;
233 case MessageType.cancelFollow:
234 requirePlaying(session);
235 simulation.enqueue(session.id, {
236 type: "cancel-follow",
237 characterId: session.characterId
238 });
239 break;
202 240 case MessageType.editorLoadChunk:
203 241 requireAdmin(session);
204 242 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -424,7 +462,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
424 462 }
425 463 continue;
426 464 }
427 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance")
465 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
428 466 { publishEntity(event); }
429 467 }
430 468 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -489,6 +527,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
489 527 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
490 528 continue;
491 529 }
530 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
531 {
532 if (!seesTo && !seesFrom)
533 { continue; }
534 const type = event.type === "combat-swing"
535 ? MessageType.combatSwing
536 : event.type === "combat-hit"
537 ? MessageType.combatHit
538 : MessageType.combatMiss;
539 send(session, {
540 type,
541 attackerId: event.attackerId,
542 targetId: event.targetId,
543 damage: event.damage,
544 health: event.health,
545 tileX: event.tileX,
546 tileY: event.tileY,
547 fromTileX: event.fromTileX,
548 fromTileY: event.fromTileY
549 });
550 continue;
551 }
492 552 if (event.type !== "entity-move")
493 553 { continue; }
494 554 if (seesTo)
@@ -502,7 +562,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
502 562 entityId: event.entityId,
503 563 tileX: event.tileX,
504 564 tileY: event.tileY,
505 gait: event.gait
565 worldX: event.worldX,
566 worldY: event.worldY,
567 gait: event.gait,
568 lerpMs: event.lerpMs,
569 freeFlight: !!event.freeFlight
506 570 });
507 571 }
508 572 }
@@ -522,12 +586,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
522 586 characterId: record.characterId ?? event.characterId ?? null,
523 587 tileX: event.tileX ?? record.tileX,
524 588 tileY: event.tileY ?? record.tileY,
589 worldX: event.worldX ?? record.worldX,
590 worldY: event.worldY ?? record.worldY,
525 591 gait: event.gait ?? record.gait,
526 592 sex: record.sex ?? event.sex ?? null,
527 593 firstName: record.firstName ?? event.firstName ?? "",
528 594 lastName: record.lastName ?? event.lastName ?? "",
529 595 sprite: record.sprite ?? event.sprite ?? null,
530 layers: record.layers ?? event.layers ?? []
596 layers: record.layers ?? event.layers ?? [],
597 mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
598 hostile: !!(record.hostile ?? event.hostile),
599 talkable: !!(record.talkable ?? event.talkable),
600 untargetable: !!(record.untargetable ?? event.untargetable),
601 freeFlight: !!(record.freeFlight ?? event.freeFlight)
531 602 };
532 603 }
533 604
@@ -199,6 +199,44 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
199 });
199 });
200 }
200 }
201 break;
201 break;
202 case MessageType.attack:
203 requirePlaying(session);
204 simulation.enqueue(session.id, {
205 type: "attack",
206 characterId: session.characterId,
207 targetEntityId: message.targetEntityId | 0
208 });
209 break;
210 case MessageType.cancelAttack:
211 requirePlaying(session);
212 simulation.enqueue(session.id, {
213 type: "cancel-attack",
214 characterId: session.characterId
215 });
216 break;
217 case MessageType.interact:
218 requirePlaying(session);
219 simulation.enqueue(session.id, {
220 type: "interact",
221 characterId: session.characterId,
222 targetEntityId: message.targetEntityId | 0
223 });
224 break;
225 case MessageType.follow:
226 requirePlaying(session);
227 simulation.enqueue(session.id, {
228 type: "follow",
229 characterId: session.characterId,
230 targetEntityId: message.targetEntityId | 0
231 });
232 break;
233 case MessageType.cancelFollow:
234 requirePlaying(session);
235 simulation.enqueue(session.id, {
236 type: "cancel-follow",
237 characterId: session.characterId
238 });
239 break;
202 case MessageType.editorLoadChunk:
240 case MessageType.editorLoadChunk:
203 requireAdmin(session);
241 requireAdmin(session);
204 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
242 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -424,7 +462,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
424 }
462 }
425 continue;
463 continue;
426 }
464 }
427 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance")
465 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
428 { publishEntity(event); }
466 { publishEntity(event); }
429 }
467 }
430 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
468 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -489,6 +527,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
489 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
527 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
490 continue;
528 continue;
491 }
529 }
530 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
531 {
532 if (!seesTo && !seesFrom)
533 { continue; }
534 const type = event.type === "combat-swing"
535 ? MessageType.combatSwing
536 : event.type === "combat-hit"
537 ? MessageType.combatHit
538 : MessageType.combatMiss;
539 send(session, {
540 type,
541 attackerId: event.attackerId,
542 targetId: event.targetId,
543 damage: event.damage,
544 health: event.health,
545 tileX: event.tileX,
546 tileY: event.tileY,
547 fromTileX: event.fromTileX,
548 fromTileY: event.fromTileY
549 });
550 continue;
551 }
492 if (event.type !== "entity-move")
552 if (event.type !== "entity-move")
493 { continue; }
553 { continue; }
494 if (seesTo)
554 if (seesTo)
@@ -502,7 +562,11 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
502 entityId: event.entityId,
562 entityId: event.entityId,
503 tileX: event.tileX,
563 tileX: event.tileX,
504 tileY: event.tileY,
564 tileY: event.tileY,
505 gait: event.gait
565 worldX: event.worldX,
566 worldY: event.worldY,
567 gait: event.gait,
568 lerpMs: event.lerpMs,
569 freeFlight: !!event.freeFlight
506 });
570 });
507 }
571 }
508 }
572 }
@@ -522,12 +586,19 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
522 characterId: record.characterId ?? event.characterId ?? null,
586 characterId: record.characterId ?? event.characterId ?? null,
523 tileX: event.tileX ?? record.tileX,
587 tileX: event.tileX ?? record.tileX,
524 tileY: event.tileY ?? record.tileY,
588 tileY: event.tileY ?? record.tileY,
589 worldX: event.worldX ?? record.worldX,
590 worldY: event.worldY ?? record.worldY,
525 gait: event.gait ?? record.gait,
591 gait: event.gait ?? record.gait,
526 sex: record.sex ?? event.sex ?? null,
592 sex: record.sex ?? event.sex ?? null,
527 firstName: record.firstName ?? event.firstName ?? "",
593 firstName: record.firstName ?? event.firstName ?? "",
528 lastName: record.lastName ?? event.lastName ?? "",
594 lastName: record.lastName ?? event.lastName ?? "",
529 sprite: record.sprite ?? event.sprite ?? null,
595 sprite: record.sprite ?? event.sprite ?? null,
530 layers: record.layers ?? event.layers ?? []
596 layers: record.layers ?? event.layers ?? [],
597 mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
598 hostile: !!(record.hostile ?? event.hostile),
599 talkable: !!(record.talkable ?? event.talkable),
600 untargetable: !!(record.untargetable ?? event.untargetable),
601 freeFlight: !!(record.freeFlight ?? event.freeFlight)
531 };
602 };
532 }
603 }
533
604
server/src/simulation/follow.js added +247 −0
@@ -0,0 +1,247 @@
1 import { Component } from "../ecs/components.js";
2 import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
3 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
4 import { chebyshev } from "../combat/service.js";
5
6 const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7 const FOLLOW_ALWAYS_RUN_TILES = 3;
8 const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9
10 export function clearFollow (ecs, entityId)
11 {
12 const handle = ecs.handleOf(entityId);
13 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
14 if (follow)
15 {
16 follow.targetEntityId = null;
17 follow.trail = [];
18 }
19 }
20
21 export function setFollow (ecs, followerId, targetId)
22 {
23 const handle = ecs.handleOf(followerId);
24 if (handle == null)
25 { return false; }
26 let follow = ecs.get(handle, Component.follow);
27 if (!follow)
28 { follow = ecs.add(handle, Component.follow, { targetEntityId: null, trail: [] }); }
29 follow.targetEntityId = targetId;
30 follow.trail = [];
31 return true;
32 }
33
34 /** Record a tile the target just vacated so followers can reuse that path. */
35 export function recordFollowTrail (ecs, targetEntityId, fromTileX, fromTileY)
36 {
37 for (const entity of ecs.query(Component.follow))
38 {
39 const follow = entity.follow;
40 if (follow.targetEntityId !== targetEntityId)
41 { continue; }
42 if (!Array.isArray(follow.trail))
43 { follow.trail = []; }
44 const last = follow.trail[follow.trail.length - 1];
45 if (last && last.x === fromTileX && last.y === fromTileY)
46 { continue; }
47 follow.trail.push({ x: fromTileX, y: fromTileY });
48 if (follow.trail.length > FOLLOW_TRAIL_MAX)
49 { follow.trail.splice(0, follow.trail.length - FOLLOW_TRAIL_MAX); }
50 }
51 }
52
53 /** Drop trail tiles the follower has already reached. */
54 export function consumeFollowTrail (ecs, followerId, tileX, tileY)
55 {
56 const handle = ecs.handleOf(followerId);
57 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
58 if (!follow?.trail?.length)
59 { return; }
60 while (follow.trail.length && follow.trail[0].x === tileX && follow.trail[0].y === tileY)
61 { follow.trail.shift(); }
62 }
63
64 export function stepFollow (world)
65 {
66 for (const entity of world.ecs.query(Component.follow, Component.position, Component.movement))
67 {
68 const follow = entity.follow;
69 const targetId = follow.targetEntityId;
70 if (targetId == null)
71 { continue; }
72 if (world.frozen?.has?.(entity.entityId))
73 { continue; }
74
75 const targetHandle = world.ecs.handleOf(targetId);
76 if (targetHandle == null)
77 {
78 follow.targetEntityId = null;
79 follow.trail = [];
80 continue;
81 }
82 const targetPos = world.ecs.get(targetHandle, Component.position);
83 if (!targetPos)
84 {
85 follow.targetEntityId = null;
86 follow.trail = [];
87 continue;
88 }
89
90 const dist = chebyshev(
91 entity.position.tileX,
92 entity.position.tileY,
93 targetPos.tileX,
94 targetPos.tileY
95 );
96 if (dist > FOLLOW_BREAK_TILES)
97 {
98 follow.targetEntityId = null;
99 follow.trail = [];
100 clearPath(world.ecs, entity.handle);
101 continue;
102 }
103
104 const targetMovement = world.ecs.get(targetHandle, Component.movement);
105 if (dist > FOLLOW_ALWAYS_RUN_TILES)
106 { entity.movement.gait = GAIT.run; }
107 else if (dist > 1)
108 { entity.movement.gait = targetMovement?.gait === GAIT.run ? GAIT.run : GAIT.walk; }
109
110 if (dist <= 1)
111 {
112 clearPath(world.ecs, entity.handle);
113 continue;
114 }
115
116 if (!Array.isArray(follow.trail))
117 { follow.trail = []; }
118 trimTrailBehindFollower(follow.trail, entity.position);
119
120 const targetPath = world.ecs.get(targetHandle, Component.path)?.tiles ?? [];
121 const reused = buildFollowPath(
122 world,
123 entity.entityId,
124 entity.position,
125 targetPos,
126 follow.trail,
127 targetPath
128 );
129
130 let path = world.ecs.get(entity.handle, Component.path);
131 if (!path)
132 { path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }
133
134 if (reused.length)
135 {
136 path.tiles = reused;
137 entity.movement.walkCarry = 0;
138 continue;
139 }
140
141 // No shared trail/path yet — catch up with a one-shot approach path.
142 queueCatchUp(world, entity.entityId, entity.handle, entity.position, targetPos, path);
143 }
144 }
145
146 function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)
147 {
148 const combined = [];
149 for (const tile of trail)
150 { combined.push({ x: tile.x, y: tile.y }); }
151 for (const tile of targetPathTiles)
152 { combined.push({ x: tile.x, y: tile.y }); }
153
154 const result = [];
155 for (const tile of combined)
156 {
157 if (tile.x === targetPos.tileX && tile.y === targetPos.tileY)
158 { break; }
159 if (tile.x === followerPos.tileX && tile.y === followerPos.tileY)
160 { continue; }
161 if (!world.walkableFor(followerId, tile.x, tile.y))
162 { break; }
163 const prev = result[result.length - 1];
164 if (prev && prev.x === tile.x && prev.y === tile.y)
165 { continue; }
166 result.push(tile);
167 }
168 return result;
169 }
170
171 function trimTrailBehindFollower (trail, position)
172 {
173 while (trail.length)
174 {
175 const next = trail[0];
176 if (next.x === position.tileX && next.y === position.tileY)
177 {
178 trail.shift();
179 continue;
180 }
181 break;
182 }
183 }
184
185 function queueCatchUp (world, entityId, handle, position, targetPos, path)
186 {
187 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
188 if (!goal)
189 {
190 path.tiles = [];
191 return;
192 }
193 if (path.tiles?.length)
194 {
195 const last = path.tiles[path.tiles.length - 1];
196 if (last.x === goal.x && last.y === goal.y)
197 { return; }
198 }
199 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
200 path.tiles = findPath(
201 position.tileX,
202 position.tileY,
203 goal.x,
204 goal.y,
205 (x, y) => world.walkableFor(entityId, x, y),
206 bounds.minX,
207 bounds.minY,
208 bounds.maxX,
209 bounds.maxY
210 );
211 const movement = world.ecs.get(handle, Component.movement);
212 if (movement)
213 { movement.walkCarry = 0; }
214 }
215
216 function clearPath (ecs, handle)
217 {
218 const path = ecs.get(handle, Component.path);
219 if (path)
220 { path.tiles = []; }
221 }
222
223 function bestAdjacentGoal (world, entityId, position, targetPos)
224 {
225 const dirs = [
226 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
227 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
228 ];
229 let best = null;
230 let bestDist = Infinity;
231 for (const dir of dirs)
232 {
233 const x = targetPos.tileX + dir.x;
234 const y = targetPos.tileY + dir.y;
235 if (x === position.tileX && y === position.tileY)
236 { return { x, y }; }
237 if (!world.walkableFor(entityId, x, y))
238 { continue; }
239 const dist = chebyshev(position.tileX, position.tileY, x, y);
240 if (dist < bestDist)
241 {
242 bestDist = dist;
243 best = { x, y };
244 }
245 }
246 return best;
247 }
@@ -0,0 +1,247 @@
1import { Component } from "../ecs/components.js";
2import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
3import { chunkBoundsAround, findPath } from "../navigation/astar.js";
4import { chebyshev } from "../combat/service.js";
5
6const FOLLOW_BREAK_TILES = CHUNK_SIZE;
7const FOLLOW_ALWAYS_RUN_TILES = 3;
8const FOLLOW_TRAIL_MAX = CHUNK_SIZE * 2;
9
10export function clearFollow (ecs, entityId)
11{
12 const handle = ecs.handleOf(entityId);
13 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
14 if (follow)
15 {
16 follow.targetEntityId = null;
17 follow.trail = [];
18 }
19}
20
21export function setFollow (ecs, followerId, targetId)
22{
23 const handle = ecs.handleOf(followerId);
24 if (handle == null)
25 { return false; }
26 let follow = ecs.get(handle, Component.follow);
27 if (!follow)
28 { follow = ecs.add(handle, Component.follow, { targetEntityId: null, trail: [] }); }
29 follow.targetEntityId = targetId;
30 follow.trail = [];
31 return true;
32}
33
34/** Record a tile the target just vacated so followers can reuse that path. */
35export function recordFollowTrail (ecs, targetEntityId, fromTileX, fromTileY)
36{
37 for (const entity of ecs.query(Component.follow))
38 {
39 const follow = entity.follow;
40 if (follow.targetEntityId !== targetEntityId)
41 { continue; }
42 if (!Array.isArray(follow.trail))
43 { follow.trail = []; }
44 const last = follow.trail[follow.trail.length - 1];
45 if (last && last.x === fromTileX && last.y === fromTileY)
46 { continue; }
47 follow.trail.push({ x: fromTileX, y: fromTileY });
48 if (follow.trail.length > FOLLOW_TRAIL_MAX)
49 { follow.trail.splice(0, follow.trail.length - FOLLOW_TRAIL_MAX); }
50 }
51}
52
53/** Drop trail tiles the follower has already reached. */
54export function consumeFollowTrail (ecs, followerId, tileX, tileY)
55{
56 const handle = ecs.handleOf(followerId);
57 const follow = handle != null ? ecs.get(handle, Component.follow) : null;
58 if (!follow?.trail?.length)
59 { return; }
60 while (follow.trail.length && follow.trail[0].x === tileX && follow.trail[0].y === tileY)
61 { follow.trail.shift(); }
62}
63
64export function stepFollow (world)
65{
66 for (const entity of world.ecs.query(Component.follow, Component.position, Component.movement))
67 {
68 const follow = entity.follow;
69 const targetId = follow.targetEntityId;
70 if (targetId == null)
71 { continue; }
72 if (world.frozen?.has?.(entity.entityId))
73 { continue; }
74
75 const targetHandle = world.ecs.handleOf(targetId);
76 if (targetHandle == null)
77 {
78 follow.targetEntityId = null;
79 follow.trail = [];
80 continue;
81 }
82 const targetPos = world.ecs.get(targetHandle, Component.position);
83 if (!targetPos)
84 {
85 follow.targetEntityId = null;
86 follow.trail = [];
87 continue;
88 }
89
90 const dist = chebyshev(
91 entity.position.tileX,
92 entity.position.tileY,
93 targetPos.tileX,
94 targetPos.tileY
95 );
96 if (dist > FOLLOW_BREAK_TILES)
97 {
98 follow.targetEntityId = null;
99 follow.trail = [];
100 clearPath(world.ecs, entity.handle);
101 continue;
102 }
103
104 const targetMovement = world.ecs.get(targetHandle, Component.movement);
105 if (dist > FOLLOW_ALWAYS_RUN_TILES)
106 { entity.movement.gait = GAIT.run; }
107 else if (dist > 1)
108 { entity.movement.gait = targetMovement?.gait === GAIT.run ? GAIT.run : GAIT.walk; }
109
110 if (dist <= 1)
111 {
112 clearPath(world.ecs, entity.handle);
113 continue;
114 }
115
116 if (!Array.isArray(follow.trail))
117 { follow.trail = []; }
118 trimTrailBehindFollower(follow.trail, entity.position);
119
120 const targetPath = world.ecs.get(targetHandle, Component.path)?.tiles ?? [];
121 const reused = buildFollowPath(
122 world,
123 entity.entityId,
124 entity.position,
125 targetPos,
126 follow.trail,
127 targetPath
128 );
129
130 let path = world.ecs.get(entity.handle, Component.path);
131 if (!path)
132 { path = world.ecs.add(entity.handle, Component.path, { tiles: [] }); }
133
134 if (reused.length)
135 {
136 path.tiles = reused;
137 entity.movement.walkCarry = 0;
138 continue;
139 }
140
141 // No shared trail/path yet — catch up with a one-shot approach path.
142 queueCatchUp(world, entity.entityId, entity.handle, entity.position, targetPos, path);
143 }
144}
145
146function buildFollowPath (world, followerId, followerPos, targetPos, trail, targetPathTiles)
147{
148 const combined = [];
149 for (const tile of trail)
150 { combined.push({ x: tile.x, y: tile.y }); }
151 for (const tile of targetPathTiles)
152 { combined.push({ x: tile.x, y: tile.y }); }
153
154 const result = [];
155 for (const tile of combined)
156 {
157 if (tile.x === targetPos.tileX && tile.y === targetPos.tileY)
158 { break; }
159 if (tile.x === followerPos.tileX && tile.y === followerPos.tileY)
160 { continue; }
161 if (!world.walkableFor(followerId, tile.x, tile.y))
162 { break; }
163 const prev = result[result.length - 1];
164 if (prev && prev.x === tile.x && prev.y === tile.y)
165 { continue; }
166 result.push(tile);
167 }
168 return result;
169}
170
171function trimTrailBehindFollower (trail, position)
172{
173 while (trail.length)
174 {
175 const next = trail[0];
176 if (next.x === position.tileX && next.y === position.tileY)
177 {
178 trail.shift();
179 continue;
180 }
181 break;
182 }
183}
184
185function queueCatchUp (world, entityId, handle, position, targetPos, path)
186{
187 const goal = bestAdjacentGoal(world, entityId, position, targetPos);
188 if (!goal)
189 {
190 path.tiles = [];
191 return;
192 }
193 if (path.tiles?.length)
194 {
195 const last = path.tiles[path.tiles.length - 1];
196 if (last.x === goal.x && last.y === goal.y)
197 { return; }
198 }
199 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
200 path.tiles = findPath(
201 position.tileX,
202 position.tileY,
203 goal.x,
204 goal.y,
205 (x, y) => world.walkableFor(entityId, x, y),
206 bounds.minX,
207 bounds.minY,
208 bounds.maxX,
209 bounds.maxY
210 );
211 const movement = world.ecs.get(handle, Component.movement);
212 if (movement)
213 { movement.walkCarry = 0; }
214}
215
216function clearPath (ecs, handle)
217{
218 const path = ecs.get(handle, Component.path);
219 if (path)
220 { path.tiles = []; }
221}
222
223function bestAdjacentGoal (world, entityId, position, targetPos)
224{
225 const dirs = [
226 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
227 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
228 ];
229 let best = null;
230 let bestDist = Infinity;
231 for (const dir of dirs)
232 {
233 const x = targetPos.tileX + dir.x;
234 const y = targetPos.tileY + dir.y;
235 if (x === position.tileX && y === position.tileY)
236 { return { x, y }; }
237 if (!world.walkableFor(entityId, x, y))
238 { continue; }
239 const dist = chebyshev(position.tileX, position.tileY, x, y);
240 if (dist < bestDist)
241 {
242 bestDist = dist;
243 best = { x, y };
244 }
245 }
246 return best;
247}
server/src/simulation/freeFlight.js added +128 −0
@@ -0,0 +1,128 @@
1 import { Component } from "../ecs/components.js";
2 import { mobDefinition } from "../../../shared/definitions/mobs.js";
3 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
4
5 export function ensureFlightComponent (ecs, handle, position, def)
6 {
7 let flight = ecs.get(handle, Component.flight);
8 if (flight)
9 { return flight; }
10 const x = (position.tileX ?? 0) + 0.5;
11 const y = (position.tileY ?? 0) + 0.5;
12 flight = ecs.add(handle, Component.flight, {
13 x,
14 y,
15 targetX: x,
16 targetY: y,
17 speed: def?.flightSpeedTilesPerSec ?? 2.5,
18 nextPickAt: 0,
19 lastAt: 0
20 });
21 return flight;
22 }
23
24 export function stepFreeFlight (world, now = Date.now())
25 {
26 const events = [];
27 for (const entity of world.ecs.query(Component.position, Component.creature))
28 {
29 const def = mobDefinition(entity.creature.mobTypeId);
30 if (!def?.freeFlight)
31 { continue; }
32 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
33 { continue; }
34 if (world.frozen?.has?.(entity.entityId))
35 { continue; }
36
37 const flight = ensureFlightComponent(world.ecs, entity.handle, entity.position, def);
38 if (!flight.lastAt)
39 { flight.lastAt = now; }
40 const dt = Math.min(0.25, Math.max(0, (now - flight.lastAt) / 1000));
41 flight.lastAt = now;
42
43 const arrived = Math.hypot(flight.targetX - flight.x, flight.targetY - flight.y) < 0.08;
44 if (arrived || now >= (flight.nextPickAt || 0))
45 {
46 const next = pickFlightTarget(world, flight.x, flight.y);
47 if (next)
48 {
49 flight.targetX = next.x;
50 flight.targetY = next.y;
51 flight.nextPickAt = now + 1800 + Math.floor(Math.random() * 2400);
52 }
53 else
54 { flight.nextPickAt = now + 1000; }
55 }
56
57 const dx = flight.targetX - flight.x;
58 const dy = flight.targetY - flight.y;
59 const dist = Math.hypot(dx, dy);
60 if (dist < 1e-6 || dt <= 0)
61 { continue; }
62
63 const step = Math.min(dist, (flight.speed || 2.5) * dt);
64 flight.x += (dx / dist) * step;
65 flight.y += (dy / dist) * step;
66
67 const fromTileX = entity.position.tileX;
68 const fromTileY = entity.position.tileY;
69 const tileX = Math.floor(flight.x);
70 const tileY = Math.floor(flight.y);
71 entity.position.tileX = tileX;
72 entity.position.tileY = tileY;
73
74 const destRegionX = tileToRegion(tileX);
75 const destRegionY = tileToRegion(tileY);
76 if (!world.ownsRegion(destRegionX, destRegionY))
77 {
78 world.frozen.add(entity.entityId);
79 events.push({
80 type: "transfer-request",
81 entityId: entity.entityId,
82 fromTileX,
83 fromTileY,
84 destTileX: tileX,
85 destTileY: tileY,
86 toRegionX: destRegionX,
87 toRegionY: destRegionY
88 });
89 continue;
90 }
91
92 const lerpMs = Math.max(50, Math.round(dt * 1000));
93 events.push({
94 type: "entity-move",
95 entityId: entity.entityId,
96 fromTileX,
97 fromTileY,
98 tileX,
99 tileY,
100 worldX: flight.x,
101 worldY: flight.y,
102 gait: entity.movement?.gait ?? "walk",
103 lerpMs,
104 freeFlight: true
105 });
106 }
107 return events;
108 }
109
110 function pickFlightTarget (world, fromX, fromY)
111 {
112 for (let attempt = 0; attempt < 16; attempt++)
113 {
114 const angle = Math.random() * Math.PI * 2;
115 const dist = 2 + Math.random() * 6;
116 const x = fromX + Math.cos(angle) * dist;
117 const y = fromY + Math.sin(angle) * dist;
118 const tileX = Math.floor(x);
119 const tileY = Math.floor(y);
120 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
121 { continue; }
122 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
123 if (!data?.open)
124 { continue; }
125 return { x: tileX + 0.5, y: tileY + 0.5 };
126 }
127 return null;
128 }
@@ -0,0 +1,128 @@
1import { Component } from "../ecs/components.js";
2import { mobDefinition } from "../../../shared/definitions/mobs.js";
3import { tileToChunk, tileToRegion } from "../world/coordinates.js";
4
5export function ensureFlightComponent (ecs, handle, position, def)
6{
7 let flight = ecs.get(handle, Component.flight);
8 if (flight)
9 { return flight; }
10 const x = (position.tileX ?? 0) + 0.5;
11 const y = (position.tileY ?? 0) + 0.5;
12 flight = ecs.add(handle, Component.flight, {
13 x,
14 y,
15 targetX: x,
16 targetY: y,
17 speed: def?.flightSpeedTilesPerSec ?? 2.5,
18 nextPickAt: 0,
19 lastAt: 0
20 });
21 return flight;
22}
23
24export function stepFreeFlight (world, now = Date.now())
25{
26 const events = [];
27 for (const entity of world.ecs.query(Component.position, Component.creature))
28 {
29 const def = mobDefinition(entity.creature.mobTypeId);
30 if (!def?.freeFlight)
31 { continue; }
32 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
33 { continue; }
34 if (world.frozen?.has?.(entity.entityId))
35 { continue; }
36
37 const flight = ensureFlightComponent(world.ecs, entity.handle, entity.position, def);
38 if (!flight.lastAt)
39 { flight.lastAt = now; }
40 const dt = Math.min(0.25, Math.max(0, (now - flight.lastAt) / 1000));
41 flight.lastAt = now;
42
43 const arrived = Math.hypot(flight.targetX - flight.x, flight.targetY - flight.y) < 0.08;
44 if (arrived || now >= (flight.nextPickAt || 0))
45 {
46 const next = pickFlightTarget(world, flight.x, flight.y);
47 if (next)
48 {
49 flight.targetX = next.x;
50 flight.targetY = next.y;
51 flight.nextPickAt = now + 1800 + Math.floor(Math.random() * 2400);
52 }
53 else
54 { flight.nextPickAt = now + 1000; }
55 }
56
57 const dx = flight.targetX - flight.x;
58 const dy = flight.targetY - flight.y;
59 const dist = Math.hypot(dx, dy);
60 if (dist < 1e-6 || dt <= 0)
61 { continue; }
62
63 const step = Math.min(dist, (flight.speed || 2.5) * dt);
64 flight.x += (dx / dist) * step;
65 flight.y += (dy / dist) * step;
66
67 const fromTileX = entity.position.tileX;
68 const fromTileY = entity.position.tileY;
69 const tileX = Math.floor(flight.x);
70 const tileY = Math.floor(flight.y);
71 entity.position.tileX = tileX;
72 entity.position.tileY = tileY;
73
74 const destRegionX = tileToRegion(tileX);
75 const destRegionY = tileToRegion(tileY);
76 if (!world.ownsRegion(destRegionX, destRegionY))
77 {
78 world.frozen.add(entity.entityId);
79 events.push({
80 type: "transfer-request",
81 entityId: entity.entityId,
82 fromTileX,
83 fromTileY,
84 destTileX: tileX,
85 destTileY: tileY,
86 toRegionX: destRegionX,
87 toRegionY: destRegionY
88 });
89 continue;
90 }
91
92 const lerpMs = Math.max(50, Math.round(dt * 1000));
93 events.push({
94 type: "entity-move",
95 entityId: entity.entityId,
96 fromTileX,
97 fromTileY,
98 tileX,
99 tileY,
100 worldX: flight.x,
101 worldY: flight.y,
102 gait: entity.movement?.gait ?? "walk",
103 lerpMs,
104 freeFlight: true
105 });
106 }
107 return events;
108}
109
110function pickFlightTarget (world, fromX, fromY)
111{
112 for (let attempt = 0; attempt < 16; attempt++)
113 {
114 const angle = Math.random() * Math.PI * 2;
115 const dist = 2 + Math.random() * 6;
116 const x = fromX + Math.cos(angle) * dist;
117 const y = fromY + Math.sin(angle) * dist;
118 const tileX = Math.floor(x);
119 const tileY = Math.floor(y);
120 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
121 { continue; }
122 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
123 if (!data?.open)
124 { continue; }
125 return { x: tileX + 0.5, y: tileY + 0.5 };
126 }
127 return null;
128}
server/src/simulation/protocol.js +2 −1
@@ -21,5 +21,6 @@ export const WorkerMessage = Object.freeze({
21 21 inspect: "inspect",
22 22 inspectBag: "inspectBag",
23 23 setGroundItems: "setGroundItems",
24 stepSpawners: "stepSpawners"
24 stepSpawners: "stepSpawners",
25 stepSystems: "stepSystems"
25 26 });
@@ -21,5 +21,6 @@ export const WorkerMessage = Object.freeze({
21 inspect: "inspect",
21 inspect: "inspect",
22 inspectBag: "inspectBag",
22 inspectBag: "inspectBag",
23 setGroundItems: "setGroundItems",
23 setGroundItems: "setGroundItems",
24 stepSpawners: "stepSpawners"
24 stepSpawners: "stepSpawners",
25 stepSystems: "stepSystems"
25});
26});
server/src/simulation/simulation.js +83 −20
@@ -29,6 +29,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29 29 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30 30 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31 31 import { mobComponents } from "./spawners.js";
32 import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
32 33
33 34 export class Simulation
34 35 {
@@ -133,6 +134,30 @@ export class Simulation
133 134 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 135 this.lastTickAt = now;
135 136
137 {
138 const transfers = [];
139 for (const worker of this.workers)
140 {
141 const result = worker.call({ type: WorkerMessage.stepSystems, now });
142 for (const event of result?.events ?? [])
143 {
144 if (event.type === "entity-move")
145 { this.#applyMoveToDirectory(event); }
146 if (event.type === "entity-despawn")
147 { this.#forget(event.entityId); }
148 this.#persistGroundEvent(event);
149 events.push(event);
150 }
151 for (const request of result?.transferRequests ?? [])
152 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
153 }
154 if (transfers.length)
155 {
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
158 }
159 }
160
136 161 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
137 162 this.movementAccumulator += dt * movementHz;
138 163 while (this.movementAccumulator >= 1)
@@ -184,20 +209,23 @@ export class Simulation
184 209 spawnCharacter (sessionId, character)
185 210 {
186 211 this.despawnCharacter(character.character_id);
187 let tileX = character.tile_x;
188 let tileY = character.tile_y;
189 if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY))
212 // Despawn may have just written the live tile; never trust a stale row snapshot.
213 const row = this.stateDb.getCharacter(character.character_id) ?? character;
214 let tileX = row.tile_x;
215 let tileY = row.tile_y;
216 const gait = row.gait || character.gait || GAIT.walk;
217 const preferred = this.#findResumeTile(tileX, tileY);
218 if (!preferred)
190 219 {
191 const spawn = this.findOpenSpawn();
192 if (!spawn)
193 {
194 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
195 error.userFacing = true;
196 throw error;
197 }
198 tileX = spawn.tileX;
199 tileY = spawn.tileY;
200 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, character.gait);
220 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
221 error.userFacing = true;
222 throw error;
223 }
224 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
225 {
226 tileX = preferred.tileX;
227 tileY = preferred.tileY;
228 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
201 229 }
202 230
203 231 const bag = this.stateDb.getBag(character.character_id) ?? {
@@ -210,23 +238,26 @@ export class Simulation
210 238 const entityId = this.nextEntityId++;
211 239 const components = {
212 240 position: { tileX, tileY },
213 movement: { gait: character.gait || GAIT.walk, walkCarry: 0 },
241 movement: { gait, walkCarry: 0 },
214 242 path: { tiles: [] },
215 243 appearance: {
216 sex: character.sex,
217 firstName: character.first_name,
218 lastName: character.last_name
244 sex: character.sex ?? row.sex,
245 firstName: character.first_name ?? row.first_name,
246 lastName: character.last_name ?? row.last_name
219 247 },
220 248 character: {
221 characterId: character.character_id,
222 accountId: character.account_id
249 characterId: character.character_id ?? row.character_id,
250 accountId: character.account_id ?? row.account_id
223 251 },
224 252 networkIdentity: { sessionId },
225 253 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
226 254 inventory: { slots: bag.inventory ?? emptySlots() },
227 255 equipment: bag.equipment ?? emptyEquipment(),
228 256 currency: { amount: bag.currency ?? 0 },
229 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }
257 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
258 health: { current: 20, max: 20 },
259 combat: { targetEntityId: null, nextSwingAt: 0 },
260 skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
230 261 };
231 262 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
232 263 const workerId = this.#ownerOfTile(tileX, tileY);
@@ -375,6 +406,32 @@ export class Simulation
375 406 return null;
376 407 }
377 408
409 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
410 #findResumeTile (tileX, tileY, radius = 24)
411 {
412 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
413 }
414
415 #findNearbyEnterable (originX, originY, maxRadius)
416 {
417 for (let radius = 0; radius <= maxRadius; radius++)
418 {
419 for (let dy = -radius; dy <= radius; dy++)
420 {
421 for (let dx = -radius; dx <= radius; dx++)
422 {
423 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
424 { continue; }
425 const tileX = originX + dx;
426 const tileY = originY + dy;
427 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
428 { return { tileX, tileY }; }
429 }
430 }
431 }
432 return null;
433 }
434
378 435 isEnterable (tileX, tileY)
379 436 {
380 437 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
@@ -967,6 +1024,12 @@ export class Simulation
967 1024 record.tileX = event.tileX;
968 1025 record.tileY = event.tileY;
969 1026 record.gait = event.gait;
1027 if (event.worldX != null)
1028 { record.worldX = event.worldX; }
1029 if (event.worldY != null)
1030 { record.worldY = event.worldY; }
1031 if (event.freeFlight != null)
1032 { record.freeFlight = !!event.freeFlight; }
970 1033 }
971 1034
972 1035 #forget (entityId)
@@ -29,6 +29,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
31import { mobComponents } from "./spawners.js";
32import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
32
33
33export class Simulation
34export class Simulation
34{
35{
@@ -133,6 +134,30 @@ export class Simulation
133 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 this.lastTickAt = now;
135 this.lastTickAt = now;
135
136
137 {
138 const transfers = [];
139 for (const worker of this.workers)
140 {
141 const result = worker.call({ type: WorkerMessage.stepSystems, now });
142 for (const event of result?.events ?? [])
143 {
144 if (event.type === "entity-move")
145 { this.#applyMoveToDirectory(event); }
146 if (event.type === "entity-despawn")
147 { this.#forget(event.entityId); }
148 this.#persistGroundEvent(event);
149 events.push(event);
150 }
151 for (const request of result?.transferRequests ?? [])
152 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
153 }
154 if (transfers.length)
155 {
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
158 }
159 }
160
136 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
161 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
137 this.movementAccumulator += dt * movementHz;
162 this.movementAccumulator += dt * movementHz;
138 while (this.movementAccumulator >= 1)
163 while (this.movementAccumulator >= 1)
@@ -184,20 +209,23 @@ export class Simulation
184 spawnCharacter (sessionId, character)
209 spawnCharacter (sessionId, character)
185 {
210 {
186 this.despawnCharacter(character.character_id);
211 this.despawnCharacter(character.character_id);
187 let tileX = character.tile_x;
212 // Despawn may have just written the live tile; never trust a stale row snapshot.
188 let tileY = character.tile_y;
213 const row = this.stateDb.getCharacter(character.character_id) ?? character;
189 if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY))
214 let tileX = row.tile_x;
215 let tileY = row.tile_y;
216 const gait = row.gait || character.gait || GAIT.walk;
217 const preferred = this.#findResumeTile(tileX, tileY);
218 if (!preferred)
190 {
219 {
191 const spawn = this.findOpenSpawn();
220 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
192 if (!spawn)
221 error.userFacing = true;
193 {
222 throw error;
194 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
223 }
195 error.userFacing = true;
224 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
196 throw error;
225 {
197 }
226 tileX = preferred.tileX;
198 tileX = spawn.tileX;
227 tileY = preferred.tileY;
199 tileY = spawn.tileY;
228 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
200 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, character.gait);
201 }
229 }
202
230
203 const bag = this.stateDb.getBag(character.character_id) ?? {
231 const bag = this.stateDb.getBag(character.character_id) ?? {
@@ -210,23 +238,26 @@ export class Simulation
210 const entityId = this.nextEntityId++;
238 const entityId = this.nextEntityId++;
211 const components = {
239 const components = {
212 position: { tileX, tileY },
240 position: { tileX, tileY },
213 movement: { gait: character.gait || GAIT.walk, walkCarry: 0 },
241 movement: { gait, walkCarry: 0 },
214 path: { tiles: [] },
242 path: { tiles: [] },
215 appearance: {
243 appearance: {
216 sex: character.sex,
244 sex: character.sex ?? row.sex,
217 firstName: character.first_name,
245 firstName: character.first_name ?? row.first_name,
218 lastName: character.last_name
246 lastName: character.last_name ?? row.last_name
219 },
247 },
220 character: {
248 character: {
221 characterId: character.character_id,
249 characterId: character.character_id ?? row.character_id,
222 accountId: character.account_id
250 accountId: character.account_id ?? row.account_id
223 },
251 },
224 networkIdentity: { sessionId },
252 networkIdentity: { sessionId },
225 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
253 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
226 inventory: { slots: bag.inventory ?? emptySlots() },
254 inventory: { slots: bag.inventory ?? emptySlots() },
227 equipment: bag.equipment ?? emptyEquipment(),
255 equipment: bag.equipment ?? emptyEquipment(),
228 currency: { amount: bag.currency ?? 0 },
256 currency: { amount: bag.currency ?? 0 },
229 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }
257 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
258 health: { current: 20, max: 20 },
259 combat: { targetEntityId: null, nextSwingAt: 0 },
260 skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
230 };
261 };
231 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
262 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
232 const workerId = this.#ownerOfTile(tileX, tileY);
263 const workerId = this.#ownerOfTile(tileX, tileY);
@@ -375,6 +406,32 @@ export class Simulation
375 return null;
406 return null;
376 }
407 }
377
408
409 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
410 #findResumeTile (tileX, tileY, radius = 24)
411 {
412 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
413 }
414
415 #findNearbyEnterable (originX, originY, maxRadius)
416 {
417 for (let radius = 0; radius <= maxRadius; radius++)
418 {
419 for (let dy = -radius; dy <= radius; dy++)
420 {
421 for (let dx = -radius; dx <= radius; dx++)
422 {
423 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
424 { continue; }
425 const tileX = originX + dx;
426 const tileY = originY + dy;
427 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
428 { return { tileX, tileY }; }
429 }
430 }
431 }
432 return null;
433 }
434
378 isEnterable (tileX, tileY)
435 isEnterable (tileX, tileY)
379 {
436 {
380 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
437 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
@@ -967,6 +1024,12 @@ export class Simulation
967 record.tileX = event.tileX;
1024 record.tileX = event.tileX;
968 record.tileY = event.tileY;
1025 record.tileY = event.tileY;
969 record.gait = event.gait;
1026 record.gait = event.gait;
1027 if (event.worldX != null)
1028 { record.worldX = event.worldX; }
1029 if (event.worldY != null)
1030 { record.worldY = event.worldY; }
1031 if (event.freeFlight != null)
1032 { record.freeFlight = !!event.freeFlight; }
970 }
1033 }
971
1034
972 #forget (entityId)
1035 #forget (entityId)
server/src/simulation/spawners.js +97 −6
@@ -1,8 +1,13 @@
1 1 import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { defaultSpawnerConfig, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3 import {
4 defaultSpawnerConfig,
5 listAmbientMobTypes,
6 mobDefinition,
7 mobSpriteName
8 } from "../../../shared/definitions/mobs.js";
4 9 import { Component } from "../ecs/components.js";
5 import { tileToRegion } from "../world/coordinates.js";
10 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
6 11
7 12 export function collectSpawnRequests (world)
8 13 {
@@ -25,7 +30,8 @@ export function collectSpawnRequests (world)
25 30 { continue; }
26 31 const originX = chunkX * CHUNK_SIZE + localX;
27 32 const originY = chunkY * CHUNK_SIZE + localY;
28 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles);
33 const flying = !!mobDefinition(config.mobTypeId)?.flying;
34 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying);
29 35 if (!tile)
30 36 { continue; }
31 37 requests.push({
@@ -38,6 +44,7 @@ export function collectSpawnRequests (world)
38 44 }
39 45 }
40 46 }
47 requests.push(...collectAmbientRequests(world));
41 48 return requests;
42 49 }
43 50
@@ -55,14 +62,75 @@ export function mobComponents (request)
55 62 sprite: mobSpriteName(def.mobTypeId)
56 63 },
57 64 creature: { mobTypeId: def.mobTypeId },
58 health: { current: def.health ?? 8, max: def.health ?? 8 },
59 spawnOrigin: { spawnerId: request.spawnerId }
65 health: { current: def.health ?? 8, max: def.health ?? 8 }
60 66 };
67 if (request.spawnerId)
68 { components.spawnOrigin = { spawnerId: request.spawnerId }; }
61 69 if (def.persistent)
62 70 { components.persistent = {}; }
71 if (def.freeFlight)
72 {
73 components.flight = {
74 x: request.tileX + 0.5,
75 y: request.tileY + 0.5,
76 targetX: request.tileX + 0.5,
77 targetY: request.tileY + 0.5,
78 speed: def.flightSpeedTilesPerSec ?? 2.5,
79 nextPickAt: 0,
80 lastAt: 0
81 };
82 }
83 if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels))
84 {
85 components.combat = { targetEntityId: null, nextSwingAt: 0 };
86 components.skills = { levels: { ...(def.skillLevels ?? {}) } };
87 }
63 88 return components;
64 89 }
65 90
91 function collectAmbientRequests (world)
92 {
93 const requests = [];
94 const ambientTypes = listAmbientMobTypes();
95 if (!ambientTypes.length)
96 { return requests; }
97
98 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
99 if (!loaders.length)
100 { return requests; }
101
102 for (const def of ambientTypes)
103 {
104 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
105 const alive = countCreatures(world, def.mobTypeId);
106 const budget = maxPerLoader * loaders.length;
107 if (alive >= budget)
108 { continue; }
109
110 for (const loader of loaders)
111 {
112 if (requests.length + alive >= budget)
113 { break; }
114 const tile = pickSpawnTile(
115 world,
116 loader.position.tileX,
117 loader.position.tileY,
118 8,
119 !!def.flying
120 );
121 if (!tile)
122 { continue; }
123 requests.push({
124 ...tile,
125 mobTypeId: def.mobTypeId,
126 spawnerId: null,
127 persistent: false
128 });
129 }
130 }
131 return requests;
132 }
133
66 134 function countBySpawner (world)
67 135 {
68 136 const counts = new Map();
@@ -74,7 +142,18 @@ function countBySpawner (world)
74 142 return counts;
75 143 }
76 144
77 function pickSpawnTile (world, originX, originY, range)
145 function countCreatures (world, mobTypeId)
146 {
147 let count = 0;
148 for (const entity of world.ecs.query(Component.creature))
149 {
150 if (entity.creature.mobTypeId === mobTypeId)
151 { count += 1; }
152 }
153 return count;
154 }
155
156 function pickSpawnTile (world, originX, originY, range, flying = false)
78 157 {
79 158 const radius = Math.max(1, range | 0);
80 159 for (let attempt = 0; attempt < 24; attempt++)
@@ -83,6 +162,12 @@ function pickSpawnTile (world, originX, originY, range)
83 162 const tileY = originY + randInt(-radius, radius);
84 163 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
85 164 { continue; }
165 if (flying)
166 {
167 if (!chunkIsOpen(world, tileX, tileY))
168 { continue; }
169 return { tileX, tileY };
170 }
86 171 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
87 172 { continue; }
88 173 return { tileX, tileY };
@@ -90,6 +175,12 @@ function pickSpawnTile (world, originX, originY, range)
90 175 return null;
91 176 }
92 177
178 function chunkIsOpen (world, tileX, tileY)
179 {
180 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
181 return !!data?.open;
182 }
183
93 184 function randInt (min, max)
94 185 {
95 186 return min + Math.floor(Math.random() * (max - min + 1));
@@ -1,8 +1,13 @@
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { defaultSpawnerConfig, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import {
4 defaultSpawnerConfig,
5 listAmbientMobTypes,
6 mobDefinition,
7 mobSpriteName
8} from "../../../shared/definitions/mobs.js";
4import { Component } from "../ecs/components.js";
9import { Component } from "../ecs/components.js";
5import { tileToRegion } from "../world/coordinates.js";
10import { tileToChunk, tileToRegion } from "../world/coordinates.js";
6
11
7export function collectSpawnRequests (world)
12export function collectSpawnRequests (world)
8{
13{
@@ -25,7 +30,8 @@ export function collectSpawnRequests (world)
25 { continue; }
30 { continue; }
26 const originX = chunkX * CHUNK_SIZE + localX;
31 const originX = chunkX * CHUNK_SIZE + localX;
27 const originY = chunkY * CHUNK_SIZE + localY;
32 const originY = chunkY * CHUNK_SIZE + localY;
28 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles);
33 const flying = !!mobDefinition(config.mobTypeId)?.flying;
34 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying);
29 if (!tile)
35 if (!tile)
30 { continue; }
36 { continue; }
31 requests.push({
37 requests.push({
@@ -38,6 +44,7 @@ export function collectSpawnRequests (world)
38 }
44 }
39 }
45 }
40 }
46 }
47 requests.push(...collectAmbientRequests(world));
41 return requests;
48 return requests;
42}
49}
43
50
@@ -55,14 +62,75 @@ export function mobComponents (request)
55 sprite: mobSpriteName(def.mobTypeId)
62 sprite: mobSpriteName(def.mobTypeId)
56 },
63 },
57 creature: { mobTypeId: def.mobTypeId },
64 creature: { mobTypeId: def.mobTypeId },
58 health: { current: def.health ?? 8, max: def.health ?? 8 },
65 health: { current: def.health ?? 8, max: def.health ?? 8 }
59 spawnOrigin: { spawnerId: request.spawnerId }
60 };
66 };
67 if (request.spawnerId)
68 { components.spawnOrigin = { spawnerId: request.spawnerId }; }
61 if (def.persistent)
69 if (def.persistent)
62 { components.persistent = {}; }
70 { components.persistent = {}; }
71 if (def.freeFlight)
72 {
73 components.flight = {
74 x: request.tileX + 0.5,
75 y: request.tileY + 0.5,
76 targetX: request.tileX + 0.5,
77 targetY: request.tileY + 0.5,
78 speed: def.flightSpeedTilesPerSec ?? 2.5,
79 nextPickAt: 0,
80 lastAt: 0
81 };
82 }
83 if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels))
84 {
85 components.combat = { targetEntityId: null, nextSwingAt: 0 };
86 components.skills = { levels: { ...(def.skillLevels ?? {}) } };
87 }
63 return components;
88 return components;
64}
89}
65
90
91function collectAmbientRequests (world)
92{
93 const requests = [];
94 const ambientTypes = listAmbientMobTypes();
95 if (!ambientTypes.length)
96 { return requests; }
97
98 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
99 if (!loaders.length)
100 { return requests; }
101
102 for (const def of ambientTypes)
103 {
104 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
105 const alive = countCreatures(world, def.mobTypeId);
106 const budget = maxPerLoader * loaders.length;
107 if (alive >= budget)
108 { continue; }
109
110 for (const loader of loaders)
111 {
112 if (requests.length + alive >= budget)
113 { break; }
114 const tile = pickSpawnTile(
115 world,
116 loader.position.tileX,
117 loader.position.tileY,
118 8,
119 !!def.flying
120 );
121 if (!tile)
122 { continue; }
123 requests.push({
124 ...tile,
125 mobTypeId: def.mobTypeId,
126 spawnerId: null,
127 persistent: false
128 });
129 }
130 }
131 return requests;
132}
133
66function countBySpawner (world)
134function countBySpawner (world)
67{
135{
68 const counts = new Map();
136 const counts = new Map();
@@ -74,7 +142,18 @@ function countBySpawner (world)
74 return counts;
142 return counts;
75}
143}
76
144
77function pickSpawnTile (world, originX, originY, range)
145function countCreatures (world, mobTypeId)
146{
147 let count = 0;
148 for (const entity of world.ecs.query(Component.creature))
149 {
150 if (entity.creature.mobTypeId === mobTypeId)
151 { count += 1; }
152 }
153 return count;
154}
155
156function pickSpawnTile (world, originX, originY, range, flying = false)
78{
157{
79 const radius = Math.max(1, range | 0);
158 const radius = Math.max(1, range | 0);
80 for (let attempt = 0; attempt < 24; attempt++)
159 for (let attempt = 0; attempt < 24; attempt++)
@@ -83,6 +162,12 @@ function pickSpawnTile (world, originX, originY, range)
83 const tileY = originY + randInt(-radius, radius);
162 const tileY = originY + randInt(-radius, radius);
84 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
163 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
85 { continue; }
164 { continue; }
165 if (flying)
166 {
167 if (!chunkIsOpen(world, tileX, tileY))
168 { continue; }
169 return { tileX, tileY };
170 }
86 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
171 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
87 { continue; }
172 { continue; }
88 return { tileX, tileY };
173 return { tileX, tileY };
@@ -90,6 +175,12 @@ function pickSpawnTile (world, originX, originY, range)
90 return null;
175 return null;
91}
176}
92
177
178function chunkIsOpen (world, tileX, tileY)
179{
180 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
181 return !!data?.open;
182}
183
93function randInt (min, max)
184function randInt (min, max)
94{
185{
95 return min + Math.floor(Math.random() * (max - min + 1));
186 return min + Math.floor(Math.random() * (max - min + 1));
server/src/simulation/workerWorld.js +281 −20
@@ -17,6 +17,7 @@ import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/ser
17 17 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18 18 import { WorkerMessage } from "./protocol.js";
19 19 import { collectSpawnRequests } from "./spawners.js";
20 import { mobDefinition } from "../../../shared/definitions/mobs.js";
20 21 import {
21 22 bagView,
22 23 expireGroundItems,
@@ -26,6 +27,14 @@ import {
26 27 removeGroundItem,
27 28 setGroundItemsForRegion
28 29 } from "../items/bags.js";
30 import {
31 clearEngage,
32 engageTarget,
33 isUntargetable,
34 stepCombat
35 } from "../combat/service.js";
36 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
37 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
29 38
30 39 export class WorkerWorld
31 40 {
@@ -74,6 +83,8 @@ export class WorkerWorld
74 83 return this.#command(message);
75 84 case WorkerMessage.stepMovement:
76 85 return this.#stepMovement(message.now);
86 case WorkerMessage.stepSystems:
87 return this.#stepSystems(message.now);
77 88 case WorkerMessage.stepSpawners:
78 89 return { spawnRequests: collectSpawnRequests(this) };
79 90 case WorkerMessage.setGroundItems:
@@ -244,15 +255,23 @@ export class WorkerWorld
244 255 this.ecs.destroy(handle);
245 256 throw new Error("Spawned entity is missing position.");
246 257 }
247 const occupant = this.#occupied(position.tileX, position.tileY);
248 if (occupant && occupant !== entityId)
258 const flying = this.#isFlying(handle);
259 if (!flying)
249 260 {
250 this.ecs.destroy(handle);
251 const error = new Error("That tile is occupied.");
252 error.userFacing = true;
253 throw error;
261 const occupant = this.#occupied(position.tileX, position.tileY);
262 if (occupant && occupant !== entityId)
263 {
264 this.ecs.destroy(handle);
265 const error = new Error("That tile is occupied.");
266 error.userFacing = true;
267 throw error;
268 }
269 this.#occupy(entityId, position.tileX, position.tileY);
254 270 }
255 this.#occupy(entityId, position.tileX, position.tileY);
271 const creature = this.ecs.get(handle, Component.creature);
272 const def = creature ? mobDefinition(creature.mobTypeId) : null;
273 if (def?.freeFlight)
274 { ensureFlightComponent(this.ecs, handle, position, def); }
256 275 const character = this.ecs.get(handle, Component.character);
257 276 if (character?.characterId)
258 277 { this.characterEntities.set(character.characterId, entityId); }
@@ -280,7 +299,7 @@ export class WorkerWorld
280 299 const view = publicEntityView(this.ecs, entityId);
281 300 const position = this.ecs.get(handle, Component.position);
282 301 const character = this.ecs.get(handle, Component.character);
283 if (position)
302 if (position && !this.#isFlying(handle))
284 303 { this.#vacate(entityId, position.tileX, position.tileY); }
285 304 if (character?.characterId)
286 305 { this.characterEntities.delete(character.characterId); }
@@ -300,6 +319,16 @@ export class WorkerWorld
300 319 case "set-gait":
301 320 this.#setGait(sessionId, command.characterId, command.gait);
302 321 return { events: [] };
322 case "attack":
323 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
324 case "cancel-attack":
325 return this.#cancelAttack(sessionId, command.characterId);
326 case "interact":
327 return this.#interact(sessionId, command.characterId, command.targetEntityId);
328 case "follow":
329 return this.#follow(sessionId, command.characterId, command.targetEntityId);
330 case "cancel-follow":
331 return this.#cancelFollow(sessionId, command.characterId);
303 332 default:
304 333 {
305 334 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
@@ -321,6 +350,8 @@ export class WorkerWorld
321 350 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
322 351 if (this.frozen.has(entityId))
323 352 { return; }
353 clearEngage(this.ecs, entityId);
354 clearFollow(this.ecs, entityId);
324 355 const position = this.ecs.get(handle, Component.position);
325 356 const movement = this.ecs.get(handle, Component.movement);
326 357 let path = this.ecs.get(handle, Component.path);
@@ -332,7 +363,7 @@ export class WorkerWorld
332 363 position.tileY,
333 364 tileX,
334 365 tileY,
335 (x, y) => this.#walkableFor(entityId, x, y),
366 (x, y) => this.walkableFor(entityId, x, y),
336 367 bounds.minX,
337 368 bounds.minY,
338 369 bounds.maxX,
@@ -341,6 +372,118 @@ export class WorkerWorld
341 372 movement.walkCarry = 0;
342 373 }
343 374
375 #attack (sessionId, characterId, targetEntityId, now)
376 {
377 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
378 const targetHandle = this.ecs.handleOf(targetEntityId);
379 if (targetHandle == null)
380 {
381 const error = new Error("Target is not here.");
382 error.userFacing = true;
383 throw error;
384 }
385 if (targetEntityId === entityId)
386 {
387 const error = new Error("Cannot attack yourself.");
388 error.userFacing = true;
389 throw error;
390 }
391 if (isUntargetable(this.ecs, targetHandle))
392 {
393 const error = new Error("That cannot be attacked.");
394 error.userFacing = true;
395 throw error;
396 }
397 const health = this.ecs.get(targetHandle, Component.health);
398 if (!health)
399 {
400 const error = new Error("That cannot be attacked.");
401 error.userFacing = true;
402 throw error;
403 }
404 if (!this.ecs.get(handle, Component.combat))
405 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
406 clearFollow(this.ecs, entityId);
407 engageTarget(this.ecs, entityId, targetEntityId, now);
408 if (this.ecs.get(targetHandle, Component.combat))
409 { engageTarget(this.ecs, targetEntityId, entityId, now); }
410 const path = this.ecs.get(handle, Component.path);
411 if (path)
412 { path.tiles = []; }
413 return { events: [] };
414 }
415
416 #cancelAttack (sessionId, characterId)
417 {
418 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
419 clearEngage(this.ecs, entityId);
420 return { events: [] };
421 }
422
423 #interact (sessionId, characterId, targetEntityId)
424 {
425 this.#requireOwnedEntity(sessionId, characterId);
426 const targetHandle = this.ecs.handleOf(targetEntityId);
427 if (targetHandle == null)
428 {
429 const error = new Error("Target is not here.");
430 error.userFacing = true;
431 throw error;
432 }
433 if (isUntargetable(this.ecs, targetHandle))
434 {
435 const error = new Error("Nothing to say.");
436 error.userFacing = true;
437 throw error;
438 }
439 const creature = this.ecs.get(targetHandle, Component.creature);
440 const def = creature ? mobDefinition(creature.mobTypeId) : null;
441 if (!def?.talkable)
442 {
443 const error = new Error("They have nothing to say.");
444 error.userFacing = true;
445 throw error;
446 }
447 return { events: [] };
448 }
449
450 #follow (sessionId, characterId, targetEntityId)
451 {
452 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
453 const targetHandle = this.ecs.handleOf(targetEntityId);
454 if (targetHandle == null)
455 {
456 const error = new Error("Target is not here.");
457 error.userFacing = true;
458 throw error;
459 }
460 if (targetEntityId === entityId)
461 {
462 const error = new Error("Cannot follow yourself.");
463 error.userFacing = true;
464 throw error;
465 }
466 if (!this.ecs.get(targetHandle, Component.position))
467 {
468 const error = new Error("That cannot be followed.");
469 error.userFacing = true;
470 throw error;
471 }
472 clearEngage(this.ecs, entityId);
473 setFollow(this.ecs, entityId, targetEntityId);
474 const path = this.ecs.get(handle, Component.path);
475 if (path)
476 { path.tiles = []; }
477 return { events: [] };
478 }
479
480 #cancelFollow (sessionId, characterId)
481 {
482 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
483 clearFollow(this.ecs, entityId);
484 return { events: [] };
485 }
486
344 487 #setGait (sessionId, characterId, gait)
345 488 {
346 489 if (gait !== GAIT.walk && gait !== GAIT.run)
@@ -373,18 +516,50 @@ export class WorkerWorld
373 516 return { handle, entityId };
374 517 }
375 518
519 #stepSystems (now = Date.now())
520 {
521 const events = [];
522 const transferRequests = [];
523 const flight = stepFreeFlight(this, now);
524 for (const event of flight)
525 {
526 if (event.type === "transfer-request")
527 {
528 const payload = serializeEntity(this.ecs, event.entityId);
529 transferRequests.push({
530 entityId: event.entityId,
531 fromTileX: event.fromTileX,
532 fromTileY: event.fromTileY,
533 destTileX: event.destTileX,
534 destTileY: event.destTileY,
535 toRegionX: event.toRegionX,
536 toRegionY: event.toRegionY,
537 payload
538 });
539 continue;
540 }
541 events.push(event);
542 }
543 events.push(...stepCombat(this, now));
544 stepFollow(this);
545 return { events, transferRequests };
546 }
547
376 548 #stepMovement (now = Date.now())
377 549 {
378 550 const events = expireGroundItems(this, now);
379 551 const transferRequests = [];
552 this.#queueAmbientWander();
380 553 for (const entity of this.ecs.query(Component.position, Component.movement))
381 554 {
382 555 const { handle, entityId, position, movement } = entity;
556 if (this.ecs.has(handle, Component.flight))
557 { continue; }
383 558 const path = this.ecs.get(handle, Component.path);
384 559 const tiles = path?.tiles;
385 560 if (this.frozen.has(entityId) || !tiles?.length)
386 561 { continue; }
387 if (!this.#chunkIsSimulating(position.tileX, position.tileY))
562 if (!this.chunkIsSimulating(position.tileX, position.tileY))
388 563 { continue; }
389 564
390 565 const isWalk = movement.gait !== GAIT.run;
@@ -414,21 +589,55 @@ export class WorkerWorld
414 589 continue;
415 590 }
416 591
417 if (!this.#walkableFor(entityId, next.x, next.y))
592 if (!this.walkableFor(entityId, next.x, next.y))
418 593 { continue; }
419 594
420 595 const fromTileX = position.tileX;
421 596 const fromTileY = position.tileY;
422 this.#vacate(entityId, fromTileX, fromTileY);
597 const flying = this.#isFlying(handle);
598 if (!flying)
599 { this.#vacate(entityId, fromTileX, fromTileY); }
423 600 position.tileX = next.x;
424 601 position.tileY = next.y;
425 602 tiles.shift();
426 this.#occupy(entityId, position.tileX, position.tileY);
603 if (!flying)
604 { this.#occupy(entityId, position.tileX, position.tileY); }
605 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
606 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
427 607 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
428 608 }
429 609 return { events, transferRequests };
430 610 }
431 611
612 #queueAmbientWander ()
613 {
614 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
615 {
616 const def = mobDefinition(entity.creature.mobTypeId);
617 if (!def?.ambient || def.freeFlight)
618 { continue; }
619 const path = this.ecs.get(entity.handle, Component.path);
620 if (!path)
621 { continue; }
622 if (path.tiles?.length)
623 { continue; }
624 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
625 { continue; }
626 if (Math.random() > 0.35)
627 { continue; }
628 const dirs = [
629 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
630 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
631 ];
632 const dir = dirs[Math.floor(Math.random() * dirs.length)];
633 const nextX = entity.position.tileX + dir.x;
634 const nextY = entity.position.tileY + dir.y;
635 if (!this.walkableFor(entity.entityId, nextX, nextY))
636 { continue; }
637 path.tiles = [{ x: nextX, y: nextY }];
638 }
639 }
640
432 641 #applyTransfer (message)
433 642 {
434 643 const payload = message.payload;
@@ -443,7 +652,16 @@ export class WorkerWorld
443 652 { return { accepted: false, reason: "missing-destination" }; }
444 653 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
445 654 { return { accepted: false, reason: "not-owner" }; }
446 if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
655
656 const creature = payload.components?.creature;
657 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
658 if (flying)
659 {
660 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
661 if (!data?.open)
662 { return { accepted: false, reason: "blocked" }; }
663 }
664 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
447 665 { return { accepted: false, reason: "blocked" }; }
448 666
449 667 deserializeEntity(this.ecs, payload);
@@ -454,7 +672,8 @@ export class WorkerWorld
454 672 livePosition.tileY = destTileY;
455 673 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
456 674 { path.tiles.shift(); }
457 this.#occupy(entityId, destTileX, destTileY);
675 if (!flying)
676 { this.#occupy(entityId, destTileX, destTileY); }
458 677 const character = this.ecs.get(handle, Component.character);
459 678 if (character?.characterId)
460 679 { this.characterEntities.set(character.characterId, entityId); }
@@ -542,16 +761,53 @@ export class WorkerWorld
542 761 fromTileY,
543 762 tileX: view.tileX,
544 763 tileY: view.tileY,
545 gait: view.gait
764 worldX: view.worldX,
765 worldY: view.worldY,
766 gait: view.gait,
767 freeFlight: !!view.freeFlight
546 768 };
547 769 }
548 770
549 #chunkIsSimulating (tileX, tileY)
771 chunkIsSimulating (tileX, tileY)
550 772 {
551 773 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
552 774 return !!chunk && !chunk.replica && chunk.simulating;
553 775 }
554 776
777 chunkData (chunkX, chunkY)
778 {
779 return this.#chunkData(chunkX, chunkY);
780 }
781
782 walkableFor (entityId, tileX, tileY)
783 {
784 const handle = this.ecs.handleOf(entityId);
785 if (this.#isFlying(handle))
786 {
787 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
788 return !!data?.open;
789 }
790 if (!this.isEnterable(tileX, tileY))
791 { return false; }
792 const occupant = this.#occupied(tileX, tileY);
793 return !occupant || occupant === entityId;
794 }
795
796 destroyEntity (entityId)
797 {
798 return this.#destroyEntity(entityId);
799 }
800
801 occupied (tileX, tileY)
802 {
803 return this.#occupied(tileX, tileY);
804 }
805
806 #chunkIsSimulating (tileX, tileY)
807 {
808 return this.chunkIsSimulating(tileX, tileY);
809 }
810
555 811 #chunkData (chunkX, chunkY)
556 812 {
557 813 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
@@ -570,10 +826,15 @@ export class WorkerWorld
570 826
571 827 #walkableFor (entityId, tileX, tileY)
572 828 {
573 if (!this.isEnterable(tileX, tileY))
829 return this.walkableFor(entityId, tileX, tileY);
830 }
831
832 #isFlying (handle)
833 {
834 if (handle == null)
574 835 { return false; }
575 const occupant = this.#occupied(tileX, tileY);
576 return !occupant || occupant === entityId;
836 const creature = this.ecs.get(handle, Component.creature);
837 return !!mobDefinition(creature?.mobTypeId)?.flying;
577 838 }
578 839
579 840 #occupy (entityId, tileX, tileY)
@@ -17,6 +17,7 @@ import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/ser
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { WorkerMessage } from "./protocol.js";
18import { WorkerMessage } from "./protocol.js";
19import { collectSpawnRequests } from "./spawners.js";
19import { collectSpawnRequests } from "./spawners.js";
20import { mobDefinition } from "../../../shared/definitions/mobs.js";
20import {
21import {
21 bagView,
22 bagView,
22 expireGroundItems,
23 expireGroundItems,
@@ -26,6 +27,14 @@ import {
26 removeGroundItem,
27 removeGroundItem,
27 setGroundItemsForRegion
28 setGroundItemsForRegion
28} from "../items/bags.js";
29} from "../items/bags.js";
30import {
31 clearEngage,
32 engageTarget,
33 isUntargetable,
34 stepCombat
35} from "../combat/service.js";
36import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
37import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
29
38
30export class WorkerWorld
39export class WorkerWorld
31{
40{
@@ -74,6 +83,8 @@ export class WorkerWorld
74 return this.#command(message);
83 return this.#command(message);
75 case WorkerMessage.stepMovement:
84 case WorkerMessage.stepMovement:
76 return this.#stepMovement(message.now);
85 return this.#stepMovement(message.now);
86 case WorkerMessage.stepSystems:
87 return this.#stepSystems(message.now);
77 case WorkerMessage.stepSpawners:
88 case WorkerMessage.stepSpawners:
78 return { spawnRequests: collectSpawnRequests(this) };
89 return { spawnRequests: collectSpawnRequests(this) };
79 case WorkerMessage.setGroundItems:
90 case WorkerMessage.setGroundItems:
@@ -244,15 +255,23 @@ export class WorkerWorld
244 this.ecs.destroy(handle);
255 this.ecs.destroy(handle);
245 throw new Error("Spawned entity is missing position.");
256 throw new Error("Spawned entity is missing position.");
246 }
257 }
247 const occupant = this.#occupied(position.tileX, position.tileY);
258 const flying = this.#isFlying(handle);
248 if (occupant && occupant !== entityId)
259 if (!flying)
249 {
260 {
250 this.ecs.destroy(handle);
261 const occupant = this.#occupied(position.tileX, position.tileY);
251 const error = new Error("That tile is occupied.");
262 if (occupant && occupant !== entityId)
252 error.userFacing = true;
263 {
253 throw error;
264 this.ecs.destroy(handle);
265 const error = new Error("That tile is occupied.");
266 error.userFacing = true;
267 throw error;
268 }
269 this.#occupy(entityId, position.tileX, position.tileY);
254 }
270 }
255 this.#occupy(entityId, position.tileX, position.tileY);
271 const creature = this.ecs.get(handle, Component.creature);
272 const def = creature ? mobDefinition(creature.mobTypeId) : null;
273 if (def?.freeFlight)
274 { ensureFlightComponent(this.ecs, handle, position, def); }
256 const character = this.ecs.get(handle, Component.character);
275 const character = this.ecs.get(handle, Component.character);
257 if (character?.characterId)
276 if (character?.characterId)
258 { this.characterEntities.set(character.characterId, entityId); }
277 { this.characterEntities.set(character.characterId, entityId); }
@@ -280,7 +299,7 @@ export class WorkerWorld
280 const view = publicEntityView(this.ecs, entityId);
299 const view = publicEntityView(this.ecs, entityId);
281 const position = this.ecs.get(handle, Component.position);
300 const position = this.ecs.get(handle, Component.position);
282 const character = this.ecs.get(handle, Component.character);
301 const character = this.ecs.get(handle, Component.character);
283 if (position)
302 if (position && !this.#isFlying(handle))
284 { this.#vacate(entityId, position.tileX, position.tileY); }
303 { this.#vacate(entityId, position.tileX, position.tileY); }
285 if (character?.characterId)
304 if (character?.characterId)
286 { this.characterEntities.delete(character.characterId); }
305 { this.characterEntities.delete(character.characterId); }
@@ -300,6 +319,16 @@ export class WorkerWorld
300 case "set-gait":
319 case "set-gait":
301 this.#setGait(sessionId, command.characterId, command.gait);
320 this.#setGait(sessionId, command.characterId, command.gait);
302 return { events: [] };
321 return { events: [] };
322 case "attack":
323 return this.#attack(sessionId, command.characterId, command.targetEntityId, message.now ?? Date.now());
324 case "cancel-attack":
325 return this.#cancelAttack(sessionId, command.characterId);
326 case "interact":
327 return this.#interact(sessionId, command.characterId, command.targetEntityId);
328 case "follow":
329 return this.#follow(sessionId, command.characterId, command.targetEntityId);
330 case "cancel-follow":
331 return this.#cancelFollow(sessionId, command.characterId);
303 default:
332 default:
304 {
333 {
305 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
334 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
@@ -321,6 +350,8 @@ export class WorkerWorld
321 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
350 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
322 if (this.frozen.has(entityId))
351 if (this.frozen.has(entityId))
323 { return; }
352 { return; }
353 clearEngage(this.ecs, entityId);
354 clearFollow(this.ecs, entityId);
324 const position = this.ecs.get(handle, Component.position);
355 const position = this.ecs.get(handle, Component.position);
325 const movement = this.ecs.get(handle, Component.movement);
356 const movement = this.ecs.get(handle, Component.movement);
326 let path = this.ecs.get(handle, Component.path);
357 let path = this.ecs.get(handle, Component.path);
@@ -332,7 +363,7 @@ export class WorkerWorld
332 position.tileY,
363 position.tileY,
333 tileX,
364 tileX,
334 tileY,
365 tileY,
335 (x, y) => this.#walkableFor(entityId, x, y),
366 (x, y) => this.walkableFor(entityId, x, y),
336 bounds.minX,
367 bounds.minX,
337 bounds.minY,
368 bounds.minY,
338 bounds.maxX,
369 bounds.maxX,
@@ -341,6 +372,118 @@ export class WorkerWorld
341 movement.walkCarry = 0;
372 movement.walkCarry = 0;
342 }
373 }
343
374
375 #attack (sessionId, characterId, targetEntityId, now)
376 {
377 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
378 const targetHandle = this.ecs.handleOf(targetEntityId);
379 if (targetHandle == null)
380 {
381 const error = new Error("Target is not here.");
382 error.userFacing = true;
383 throw error;
384 }
385 if (targetEntityId === entityId)
386 {
387 const error = new Error("Cannot attack yourself.");
388 error.userFacing = true;
389 throw error;
390 }
391 if (isUntargetable(this.ecs, targetHandle))
392 {
393 const error = new Error("That cannot be attacked.");
394 error.userFacing = true;
395 throw error;
396 }
397 const health = this.ecs.get(targetHandle, Component.health);
398 if (!health)
399 {
400 const error = new Error("That cannot be attacked.");
401 error.userFacing = true;
402 throw error;
403 }
404 if (!this.ecs.get(handle, Component.combat))
405 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
406 clearFollow(this.ecs, entityId);
407 engageTarget(this.ecs, entityId, targetEntityId, now);
408 if (this.ecs.get(targetHandle, Component.combat))
409 { engageTarget(this.ecs, targetEntityId, entityId, now); }
410 const path = this.ecs.get(handle, Component.path);
411 if (path)
412 { path.tiles = []; }
413 return { events: [] };
414 }
415
416 #cancelAttack (sessionId, characterId)
417 {
418 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
419 clearEngage(this.ecs, entityId);
420 return { events: [] };
421 }
422
423 #interact (sessionId, characterId, targetEntityId)
424 {
425 this.#requireOwnedEntity(sessionId, characterId);
426 const targetHandle = this.ecs.handleOf(targetEntityId);
427 if (targetHandle == null)
428 {
429 const error = new Error("Target is not here.");
430 error.userFacing = true;
431 throw error;
432 }
433 if (isUntargetable(this.ecs, targetHandle))
434 {
435 const error = new Error("Nothing to say.");
436 error.userFacing = true;
437 throw error;
438 }
439 const creature = this.ecs.get(targetHandle, Component.creature);
440 const def = creature ? mobDefinition(creature.mobTypeId) : null;
441 if (!def?.talkable)
442 {
443 const error = new Error("They have nothing to say.");
444 error.userFacing = true;
445 throw error;
446 }
447 return { events: [] };
448 }
449
450 #follow (sessionId, characterId, targetEntityId)
451 {
452 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
453 const targetHandle = this.ecs.handleOf(targetEntityId);
454 if (targetHandle == null)
455 {
456 const error = new Error("Target is not here.");
457 error.userFacing = true;
458 throw error;
459 }
460 if (targetEntityId === entityId)
461 {
462 const error = new Error("Cannot follow yourself.");
463 error.userFacing = true;
464 throw error;
465 }
466 if (!this.ecs.get(targetHandle, Component.position))
467 {
468 const error = new Error("That cannot be followed.");
469 error.userFacing = true;
470 throw error;
471 }
472 clearEngage(this.ecs, entityId);
473 setFollow(this.ecs, entityId, targetEntityId);
474 const path = this.ecs.get(handle, Component.path);
475 if (path)
476 { path.tiles = []; }
477 return { events: [] };
478 }
479
480 #cancelFollow (sessionId, characterId)
481 {
482 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
483 clearFollow(this.ecs, entityId);
484 return { events: [] };
485 }
486
344 #setGait (sessionId, characterId, gait)
487 #setGait (sessionId, characterId, gait)
345 {
488 {
346 if (gait !== GAIT.walk && gait !== GAIT.run)
489 if (gait !== GAIT.walk && gait !== GAIT.run)
@@ -373,18 +516,50 @@ export class WorkerWorld
373 return { handle, entityId };
516 return { handle, entityId };
374 }
517 }
375
518
519 #stepSystems (now = Date.now())
520 {
521 const events = [];
522 const transferRequests = [];
523 const flight = stepFreeFlight(this, now);
524 for (const event of flight)
525 {
526 if (event.type === "transfer-request")
527 {
528 const payload = serializeEntity(this.ecs, event.entityId);
529 transferRequests.push({
530 entityId: event.entityId,
531 fromTileX: event.fromTileX,
532 fromTileY: event.fromTileY,
533 destTileX: event.destTileX,
534 destTileY: event.destTileY,
535 toRegionX: event.toRegionX,
536 toRegionY: event.toRegionY,
537 payload
538 });
539 continue;
540 }
541 events.push(event);
542 }
543 events.push(...stepCombat(this, now));
544 stepFollow(this);
545 return { events, transferRequests };
546 }
547
376 #stepMovement (now = Date.now())
548 #stepMovement (now = Date.now())
377 {
549 {
378 const events = expireGroundItems(this, now);
550 const events = expireGroundItems(this, now);
379 const transferRequests = [];
551 const transferRequests = [];
552 this.#queueAmbientWander();
380 for (const entity of this.ecs.query(Component.position, Component.movement))
553 for (const entity of this.ecs.query(Component.position, Component.movement))
381 {
554 {
382 const { handle, entityId, position, movement } = entity;
555 const { handle, entityId, position, movement } = entity;
556 if (this.ecs.has(handle, Component.flight))
557 { continue; }
383 const path = this.ecs.get(handle, Component.path);
558 const path = this.ecs.get(handle, Component.path);
384 const tiles = path?.tiles;
559 const tiles = path?.tiles;
385 if (this.frozen.has(entityId) || !tiles?.length)
560 if (this.frozen.has(entityId) || !tiles?.length)
386 { continue; }
561 { continue; }
387 if (!this.#chunkIsSimulating(position.tileX, position.tileY))
562 if (!this.chunkIsSimulating(position.tileX, position.tileY))
388 { continue; }
563 { continue; }
389
564
390 const isWalk = movement.gait !== GAIT.run;
565 const isWalk = movement.gait !== GAIT.run;
@@ -414,21 +589,55 @@ export class WorkerWorld
414 continue;
589 continue;
415 }
590 }
416
591
417 if (!this.#walkableFor(entityId, next.x, next.y))
592 if (!this.walkableFor(entityId, next.x, next.y))
418 { continue; }
593 { continue; }
419
594
420 const fromTileX = position.tileX;
595 const fromTileX = position.tileX;
421 const fromTileY = position.tileY;
596 const fromTileY = position.tileY;
422 this.#vacate(entityId, fromTileX, fromTileY);
597 const flying = this.#isFlying(handle);
598 if (!flying)
599 { this.#vacate(entityId, fromTileX, fromTileY); }
423 position.tileX = next.x;
600 position.tileX = next.x;
424 position.tileY = next.y;
601 position.tileY = next.y;
425 tiles.shift();
602 tiles.shift();
426 this.#occupy(entityId, position.tileX, position.tileY);
603 if (!flying)
604 { this.#occupy(entityId, position.tileX, position.tileY); }
605 recordFollowTrail(this.ecs, entityId, fromTileX, fromTileY);
606 consumeFollowTrail(this.ecs, entityId, position.tileX, position.tileY);
427 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
607 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
428 }
608 }
429 return { events, transferRequests };
609 return { events, transferRequests };
430 }
610 }
431
611
612 #queueAmbientWander ()
613 {
614 for (const entity of this.ecs.query(Component.position, Component.movement, Component.creature))
615 {
616 const def = mobDefinition(entity.creature.mobTypeId);
617 if (!def?.ambient || def.freeFlight)
618 { continue; }
619 const path = this.ecs.get(entity.handle, Component.path);
620 if (!path)
621 { continue; }
622 if (path.tiles?.length)
623 { continue; }
624 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
625 { continue; }
626 if (Math.random() > 0.35)
627 { continue; }
628 const dirs = [
629 { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 },
630 { x: 1, y: 1 }, { x: 1, y: -1 }, { x: -1, y: 1 }, { x: -1, y: -1 }
631 ];
632 const dir = dirs[Math.floor(Math.random() * dirs.length)];
633 const nextX = entity.position.tileX + dir.x;
634 const nextY = entity.position.tileY + dir.y;
635 if (!this.walkableFor(entity.entityId, nextX, nextY))
636 { continue; }
637 path.tiles = [{ x: nextX, y: nextY }];
638 }
639 }
640
432 #applyTransfer (message)
641 #applyTransfer (message)
433 {
642 {
434 const payload = message.payload;
643 const payload = message.payload;
@@ -443,7 +652,16 @@ export class WorkerWorld
443 { return { accepted: false, reason: "missing-destination" }; }
652 { return { accepted: false, reason: "missing-destination" }; }
444 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
653 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
445 { return { accepted: false, reason: "not-owner" }; }
654 { return { accepted: false, reason: "not-owner" }; }
446 if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
655
656 const creature = payload.components?.creature;
657 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
658 if (flying)
659 {
660 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
661 if (!data?.open)
662 { return { accepted: false, reason: "blocked" }; }
663 }
664 else if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
447 { return { accepted: false, reason: "blocked" }; }
665 { return { accepted: false, reason: "blocked" }; }
448
666
449 deserializeEntity(this.ecs, payload);
667 deserializeEntity(this.ecs, payload);
@@ -454,7 +672,8 @@ export class WorkerWorld
454 livePosition.tileY = destTileY;
672 livePosition.tileY = destTileY;
455 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
673 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
456 { path.tiles.shift(); }
674 { path.tiles.shift(); }
457 this.#occupy(entityId, destTileX, destTileY);
675 if (!flying)
676 { this.#occupy(entityId, destTileX, destTileY); }
458 const character = this.ecs.get(handle, Component.character);
677 const character = this.ecs.get(handle, Component.character);
459 if (character?.characterId)
678 if (character?.characterId)
460 { this.characterEntities.set(character.characterId, entityId); }
679 { this.characterEntities.set(character.characterId, entityId); }
@@ -542,16 +761,53 @@ export class WorkerWorld
542 fromTileY,
761 fromTileY,
543 tileX: view.tileX,
762 tileX: view.tileX,
544 tileY: view.tileY,
763 tileY: view.tileY,
545 gait: view.gait
764 worldX: view.worldX,
765 worldY: view.worldY,
766 gait: view.gait,
767 freeFlight: !!view.freeFlight
546 };
768 };
547 }
769 }
548
770
549 #chunkIsSimulating (tileX, tileY)
771 chunkIsSimulating (tileX, tileY)
550 {
772 {
551 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
773 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
552 return !!chunk && !chunk.replica && chunk.simulating;
774 return !!chunk && !chunk.replica && chunk.simulating;
553 }
775 }
554
776
777 chunkData (chunkX, chunkY)
778 {
779 return this.#chunkData(chunkX, chunkY);
780 }
781
782 walkableFor (entityId, tileX, tileY)
783 {
784 const handle = this.ecs.handleOf(entityId);
785 if (this.#isFlying(handle))
786 {
787 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
788 return !!data?.open;
789 }
790 if (!this.isEnterable(tileX, tileY))
791 { return false; }
792 const occupant = this.#occupied(tileX, tileY);
793 return !occupant || occupant === entityId;
794 }
795
796 destroyEntity (entityId)
797 {
798 return this.#destroyEntity(entityId);
799 }
800
801 occupied (tileX, tileY)
802 {
803 return this.#occupied(tileX, tileY);
804 }
805
806 #chunkIsSimulating (tileX, tileY)
807 {
808 return this.chunkIsSimulating(tileX, tileY);
809 }
810
555 #chunkData (chunkX, chunkY)
811 #chunkData (chunkX, chunkY)
556 {
812 {
557 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
813 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
@@ -570,10 +826,15 @@ export class WorkerWorld
570
826
571 #walkableFor (entityId, tileX, tileY)
827 #walkableFor (entityId, tileX, tileY)
572 {
828 {
573 if (!this.isEnterable(tileX, tileY))
829 return this.walkableFor(entityId, tileX, tileY);
830 }
831
832 #isFlying (handle)
833 {
834 if (handle == null)
574 { return false; }
835 { return false; }
575 const occupant = this.#occupied(tileX, tileY);
836 const creature = this.ecs.get(handle, Component.creature);
576 return !occupant || occupant === entityId;
837 return !!mobDefinition(creature?.mobTypeId)?.flying;
577 }
838 }
578
839
579 #occupy (entityId, tileX, tileY)
840 #occupy (entityId, tileX, tileY)
server/tests/character-resume.test.js added +49 −0
@@ -0,0 +1,49 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5 test("logout saves tile and login resumes nearby that tile", () =>
6 {
7 const harness = makeSimulation({ workerCount: 1 });
8 try
9 {
10 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
11 const entityId = harness.simulation.spawnCharacter(1, character);
12 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 12, tileY: 8 });
13 stepTimes(harness.simulation, walkTicks(5));
14 const before = harness.simulation.entityRecord(entityId);
15 assert.equal(before.tileX, 12);
16 assert.equal(before.tileY, 8);
17
18 harness.simulation.despawnCharacter(character.character_id);
19 const saved = harness.stateDb.getCharacter(character.character_id);
20 assert.equal(saved.tile_x, 12);
21 assert.equal(saved.tile_y, 8);
22
23 const again = harness.simulation.spawnCharacter(2, saved);
24 const resumed = harness.simulation.entityRecord(again);
25 assert.equal(resumed.tileX, 12);
26 assert.equal(resumed.tileY, 8);
27 }
28 finally
29 { harness.close(); }
30 });
31
32 test("login prefers a nearby free tile over a distant world spawn when blocked", () =>
33 {
34 const harness = makeSimulation({ workerCount: 1 });
35 try
36 {
37 const blocker = makeCharacter(harness.stateDb, { tileX: 12, tileY: 8, firstName: "Block" });
38 harness.simulation.spawnCharacter(1, blocker);
39 const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 8, firstName: "Return" });
40 harness.stateDb.saveCharacterPosition(character.character_id, 12, 8, "walk");
41 const fresh = harness.stateDb.getCharacter(character.character_id);
42 const entityId = harness.simulation.spawnCharacter(2, fresh);
43 const resumed = harness.simulation.entityRecord(entityId);
44 assert.ok(Math.abs(resumed.tileX - 12) + Math.abs(resumed.tileY - 8) <= 2);
45 assert.ok(!(resumed.tileX === 12 && resumed.tileY === 8));
46 }
47 finally
48 { harness.close(); }
49 });
@@ -0,0 +1,49 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5test("logout saves tile and login resumes nearby that tile", () =>
6{
7 const harness = makeSimulation({ workerCount: 1 });
8 try
9 {
10 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
11 const entityId = harness.simulation.spawnCharacter(1, character);
12 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 12, tileY: 8 });
13 stepTimes(harness.simulation, walkTicks(5));
14 const before = harness.simulation.entityRecord(entityId);
15 assert.equal(before.tileX, 12);
16 assert.equal(before.tileY, 8);
17
18 harness.simulation.despawnCharacter(character.character_id);
19 const saved = harness.stateDb.getCharacter(character.character_id);
20 assert.equal(saved.tile_x, 12);
21 assert.equal(saved.tile_y, 8);
22
23 const again = harness.simulation.spawnCharacter(2, saved);
24 const resumed = harness.simulation.entityRecord(again);
25 assert.equal(resumed.tileX, 12);
26 assert.equal(resumed.tileY, 8);
27 }
28 finally
29 { harness.close(); }
30});
31
32test("login prefers a nearby free tile over a distant world spawn when blocked", () =>
33{
34 const harness = makeSimulation({ workerCount: 1 });
35 try
36 {
37 const blocker = makeCharacter(harness.stateDb, { tileX: 12, tileY: 8, firstName: "Block" });
38 harness.simulation.spawnCharacter(1, blocker);
39 const character = makeCharacter(harness.stateDb, { tileX: 12, tileY: 8, firstName: "Return" });
40 harness.stateDb.saveCharacterPosition(character.character_id, 12, 8, "walk");
41 const fresh = harness.stateDb.getCharacter(character.character_id);
42 const entityId = harness.simulation.spawnCharacter(2, fresh);
43 const resumed = harness.simulation.entityRecord(entityId);
44 assert.ok(Math.abs(resumed.tileX - 12) + Math.abs(resumed.tileY - 8) <= 2);
45 assert.ok(!(resumed.tileX === 12 && resumed.tileY === 8));
46 }
47 finally
48 { harness.close(); }
49});
server/tests/combat.test.js added +156 −0
@@ -0,0 +1,156 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mobComponents } from "../src/simulation/spawners.js";
4 import { MobId } from "../../shared/definitions/mobs.js";
5 import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6 import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7
8 function workerOf (simulation, entityId)
9 {
10 const record = simulation.entityRecord(entityId);
11 assert.ok(record, "entity must be remembered");
12 return simulation.workers[record.workerId];
13 }
14
15 function componentsOf (simulation, entityId)
16 {
17 const worker = workerOf(simulation, entityId);
18 const handle = worker.world.ecs.handleOf(entityId);
19 assert.ok(handle != null);
20 return worker.world.ecs.componentsOf(handle);
21 }
22
23 test("attack engages both combatants and retaliates", () =>
24 {
25 const harness = makeSimulation({ workerCount: 1 });
26 try
27 {
28 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
29 const playerId = harness.simulation.spawnCharacter(1, character);
30 const ratId = harness.simulation.spawnEntity(mobComponents({
31 tileX: 9,
32 tileY: 8,
33 mobTypeId: MobId.rat,
34 spawnerId: null
35 }));
36
37 harness.simulation.enqueue(1, {
38 type: "attack",
39 characterId: character.character_id,
40 targetEntityId: ratId
41 });
42 harness.simulation.step();
43
44 const player = componentsOf(harness.simulation, playerId);
45 const rat = componentsOf(harness.simulation, ratId);
46 assert.equal(player.combat.targetEntityId, ratId);
47 assert.equal(rat.combat.targetEntityId, playerId);
48 }
49 finally
50 { harness.close(); }
51 });
52
53 test("melee swing only resolves at Chebyshev distance 1", () =>
54 {
55 const harness = makeSimulation({ workerCount: 1 });
56 try
57 {
58 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
59 const playerId = harness.simulation.spawnCharacter(1, character);
60 const bag = harness.simulation.bagOf(playerId);
61 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
62 assert.ok(stickSlot >= 0);
63 harness.simulation.enqueue(1, {
64 type: "equip-item",
65 characterId: character.character_id,
66 slotIndex: stickSlot
67 });
68 harness.simulation.step();
69 assert.equal(
70 harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
71 ItemId.stick
72 );
73
74 const farRat = harness.simulation.spawnEntity(mobComponents({
75 tileX: 12,
76 tileY: 8,
77 mobTypeId: MobId.rat
78 }));
79 harness.simulation.enqueue(1, {
80 type: "attack",
81 characterId: character.character_id,
82 targetEntityId: farRat
83 });
84 const farEvents = harness.simulation.step().events;
85 assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);
86
87 const nearRat = harness.simulation.spawnEntity(mobComponents({
88 tileX: 9,
89 tileY: 8,
90 mobTypeId: MobId.rat
91 }));
92 harness.simulation.enqueue(1, {
93 type: "attack",
94 characterId: character.character_id,
95 targetEntityId: nearRat
96 });
97 const nearEvents = harness.simulation.step().events;
98 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
99 assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss"));
100 }
101 finally
102 { harness.close(); }
103 });
104
105 test("pigeons are untargetable free-flight and never get path tiles", () =>
106 {
107 const harness = makeSimulation({ workerCount: 1 });
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 harness.simulation.spawnCharacter(1, character);
112 const pigeonId = harness.simulation.spawnEntity(mobComponents({
113 tileX: 10,
114 tileY: 8,
115 mobTypeId: MobId.pigeon
116 }));
117
118 const before = componentsOf(harness.simulation, pigeonId);
119 assert.equal(before.flight != null, true);
120 assert.equal(before.combat == null, true);
121 assert.deepEqual(before.path?.tiles ?? [], []);
122
123 harness.setNow(harness.now() + 500);
124 stepTimes(harness.simulation, 10);
125 const after = componentsOf(harness.simulation, pigeonId);
126 assert.deepEqual(after.path?.tiles ?? [], []);
127 assert.equal(after.flight != null, true);
128
129 harness.simulation.enqueue(1, {
130 type: "attack",
131 characterId: character.character_id,
132 targetEntityId: pigeonId
133 });
134 const result = harness.simulation.step();
135 assert.ok(result.events.some((event) => event.type === "command-error"));
136 assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
137 }
138 finally
139 { harness.close(); }
140 });
141
142 test("player combat and skills components are present on spawn", () =>
143 {
144 const harness = makeSimulation({ workerCount: 1 });
145 try
146 {
147 const character = makeCharacter(harness.stateDb);
148 const playerId = harness.simulation.spawnCharacter(1, character);
149 const comps = componentsOf(harness.simulation, playerId);
150 assert.ok(comps.combat);
151 assert.ok(comps.skills?.levels?.clubfighting);
152 assert.ok(comps.health);
153 }
154 finally
155 { harness.close(); }
156 });
@@ -0,0 +1,156 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mobComponents } from "../src/simulation/spawners.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7
8function workerOf (simulation, entityId)
9{
10 const record = simulation.entityRecord(entityId);
11 assert.ok(record, "entity must be remembered");
12 return simulation.workers[record.workerId];
13}
14
15function componentsOf (simulation, entityId)
16{
17 const worker = workerOf(simulation, entityId);
18 const handle = worker.world.ecs.handleOf(entityId);
19 assert.ok(handle != null);
20 return worker.world.ecs.componentsOf(handle);
21}
22
23test("attack engages both combatants and retaliates", () =>
24{
25 const harness = makeSimulation({ workerCount: 1 });
26 try
27 {
28 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
29 const playerId = harness.simulation.spawnCharacter(1, character);
30 const ratId = harness.simulation.spawnEntity(mobComponents({
31 tileX: 9,
32 tileY: 8,
33 mobTypeId: MobId.rat,
34 spawnerId: null
35 }));
36
37 harness.simulation.enqueue(1, {
38 type: "attack",
39 characterId: character.character_id,
40 targetEntityId: ratId
41 });
42 harness.simulation.step();
43
44 const player = componentsOf(harness.simulation, playerId);
45 const rat = componentsOf(harness.simulation, ratId);
46 assert.equal(player.combat.targetEntityId, ratId);
47 assert.equal(rat.combat.targetEntityId, playerId);
48 }
49 finally
50 { harness.close(); }
51});
52
53test("melee swing only resolves at Chebyshev distance 1", () =>
54{
55 const harness = makeSimulation({ workerCount: 1 });
56 try
57 {
58 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
59 const playerId = harness.simulation.spawnCharacter(1, character);
60 const bag = harness.simulation.bagOf(playerId);
61 const stickSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.stick);
62 assert.ok(stickSlot >= 0);
63 harness.simulation.enqueue(1, {
64 type: "equip-item",
65 characterId: character.character_id,
66 slotIndex: stickSlot
67 });
68 harness.simulation.step();
69 assert.equal(
70 harness.simulation.bagOf(playerId).equipment.slots[EQUIPMENT_SLOT.weapon]?.itemId,
71 ItemId.stick
72 );
73
74 const farRat = harness.simulation.spawnEntity(mobComponents({
75 tileX: 12,
76 tileY: 8,
77 mobTypeId: MobId.rat
78 }));
79 harness.simulation.enqueue(1, {
80 type: "attack",
81 characterId: character.character_id,
82 targetEntityId: farRat
83 });
84 const farEvents = harness.simulation.step().events;
85 assert.equal(farEvents.some((event) => event.type === "combat-swing"), false);
86
87 const nearRat = harness.simulation.spawnEntity(mobComponents({
88 tileX: 9,
89 tileY: 8,
90 mobTypeId: MobId.rat
91 }));
92 harness.simulation.enqueue(1, {
93 type: "attack",
94 characterId: character.character_id,
95 targetEntityId: nearRat
96 });
97 const nearEvents = harness.simulation.step().events;
98 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
99 assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss"));
100 }
101 finally
102 { harness.close(); }
103});
104
105test("pigeons are untargetable free-flight and never get path tiles", () =>
106{
107 const harness = makeSimulation({ workerCount: 1 });
108 try
109 {
110 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
111 harness.simulation.spawnCharacter(1, character);
112 const pigeonId = harness.simulation.spawnEntity(mobComponents({
113 tileX: 10,
114 tileY: 8,
115 mobTypeId: MobId.pigeon
116 }));
117
118 const before = componentsOf(harness.simulation, pigeonId);
119 assert.equal(before.flight != null, true);
120 assert.equal(before.combat == null, true);
121 assert.deepEqual(before.path?.tiles ?? [], []);
122
123 harness.setNow(harness.now() + 500);
124 stepTimes(harness.simulation, 10);
125 const after = componentsOf(harness.simulation, pigeonId);
126 assert.deepEqual(after.path?.tiles ?? [], []);
127 assert.equal(after.flight != null, true);
128
129 harness.simulation.enqueue(1, {
130 type: "attack",
131 characterId: character.character_id,
132 targetEntityId: pigeonId
133 });
134 const result = harness.simulation.step();
135 assert.ok(result.events.some((event) => event.type === "command-error"));
136 assert.equal(componentsOf(harness.simulation, pigeonId).path?.tiles?.length ?? 0, 0);
137 }
138 finally
139 { harness.close(); }
140});
141
142test("player combat and skills components are present on spawn", () =>
143{
144 const harness = makeSimulation({ workerCount: 1 });
145 try
146 {
147 const character = makeCharacter(harness.stateDb);
148 const playerId = harness.simulation.spawnCharacter(1, character);
149 const comps = componentsOf(harness.simulation, playerId);
150 assert.ok(comps.combat);
151 assert.ok(comps.skills?.levels?.clubfighting);
152 assert.ok(comps.health);
153 }
154 finally
155 { harness.close(); }
156});
server/tests/follow.test.js added +199 −0
@@ -0,0 +1,199 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { GAIT } from "../../shared/protocol/constants.js";
4 import { MobId } from "../../shared/definitions/mobs.js";
5 import { mobComponents } from "../src/simulation/spawners.js";
6 import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7
8 function workerOf (simulation, entityId)
9 {
10 const record = simulation.entityRecord(entityId);
11 assert.ok(record);
12 return simulation.workers[record.workerId];
13 }
14
15 function componentsOf (simulation, entityId)
16 {
17 const worker = workerOf(simulation, entityId);
18 const handle = worker.world.ecs.handleOf(entityId);
19 assert.ok(handle != null);
20 return worker.world.ecs.componentsOf(handle);
21 }
22
23 test("follow stays put when already adjacent", () =>
24 {
25 const harness = makeSimulation({ workerCount: 1 });
26 try
27 {
28 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
29 const playerId = harness.simulation.spawnCharacter(1, character);
30 const deerId = harness.simulation.spawnEntity(mobComponents({
31 tileX: 9,
32 tileY: 8,
33 mobTypeId: MobId.deer
34 }));
35 harness.simulation.enqueue(1, {
36 type: "follow",
37 characterId: character.character_id,
38 targetEntityId: deerId
39 });
40 harness.simulation.step();
41 const comps = componentsOf(harness.simulation, playerId);
42 assert.equal(comps.follow.targetEntityId, deerId);
43 assert.deepEqual(comps.path?.tiles ?? [], []);
44 }
45 finally
46 { harness.close(); }
47 });
48
49 test("follow runs when more than three tiles away and breaks past a chunk", () =>
50 {
51 const harness = makeSimulation({ workerCount: 1 });
52 try
53 {
54 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
55 const playerId = harness.simulation.spawnCharacter(1, character);
56 const deerId = harness.simulation.spawnEntity(mobComponents({
57 tileX: 7,
58 tileY: 8,
59 mobTypeId: MobId.deer
60 }));
61 harness.simulation.enqueue(1, {
62 type: "follow",
63 characterId: character.character_id,
64 targetEntityId: deerId
65 });
66 harness.simulation.step();
67 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.run);
68 assert.ok((componentsOf(harness.simulation, playerId).path?.tiles?.length ?? 0) > 0);
69
70 const farDeer = harness.simulation.spawnEntity(mobComponents({
71 tileX: 20,
72 tileY: 8,
73 mobTypeId: MobId.deer
74 }));
75 harness.simulation.enqueue(1, {
76 type: "follow",
77 characterId: character.character_id,
78 targetEntityId: farDeer
79 });
80 harness.simulation.step();
81 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, null);
82 }
83 finally
84 { harness.close(); }
85 });
86
87 test("follow matches target gait within three tiles and works on any mobile", () =>
88 {
89 const harness = makeSimulation({ workerCount: 1 });
90 try
91 {
92 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
93 const playerId = harness.simulation.spawnCharacter(1, character);
94 const ratId = harness.simulation.spawnEntity(mobComponents({
95 tileX: 11,
96 tileY: 8,
97 mobTypeId: MobId.rat
98 }));
99 const ratHandle = workerOf(harness.simulation, ratId).world.ecs.handleOf(ratId);
100 workerOf(harness.simulation, ratId).world.ecs.get(ratHandle, "movement").gait = GAIT.run;
101
102 harness.simulation.enqueue(1, {
103 type: "follow",
104 characterId: character.character_id,
105 targetEntityId: ratId
106 });
107 harness.simulation.step();
108 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.run);
109
110 const pigeonId = harness.simulation.spawnEntity(mobComponents({
111 tileX: 10,
112 tileY: 8,
113 mobTypeId: MobId.pigeon
114 }));
115 harness.simulation.enqueue(1, {
116 type: "follow",
117 characterId: character.character_id,
118 targetEntityId: pigeonId
119 });
120 harness.simulation.step();
121 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, pigeonId);
122 }
123 finally
124 { harness.close(); }
125 });
126
127 test("move-to clears follow", () =>
128 {
129 const harness = makeSimulation({ workerCount: 1 });
130 try
131 {
132 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
133 const playerId = harness.simulation.spawnCharacter(1, character);
134 const deerId = harness.simulation.spawnEntity(mobComponents({
135 tileX: 10,
136 tileY: 8,
137 mobTypeId: MobId.deer
138 }));
139 harness.simulation.enqueue(1, {
140 type: "follow",
141 characterId: character.character_id,
142 targetEntityId: deerId
143 });
144 harness.simulation.step();
145 harness.simulation.enqueue(1, {
146 type: "move-to",
147 characterId: character.character_id,
148 tileX: 4,
149 tileY: 8
150 });
151 harness.simulation.step();
152 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, null);
153 }
154 finally
155 { harness.close(); }
156 });
157
158 test("follower reuses the target vacated trail and waits off their tile", () =>
159 {
160 const harness = makeSimulation({ workerCount: 1 });
161 try
162 {
163 const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });
164 const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Bot", tileX: 6, tileY: 8 });
165 const leaderId = harness.simulation.spawnCharacter(1, leader);
166 const followerId = harness.simulation.spawnCharacter(2, follower);
167
168 harness.simulation.enqueue(2, {
169 type: "follow",
170 characterId: follower.character_id,
171 targetEntityId: leaderId
172 });
173 harness.simulation.step();
174
175 harness.simulation.enqueue(1, {
176 type: "move-to",
177 characterId: leader.character_id,
178 tileX: 12,
179 tileY: 8
180 });
181 stepTimes(harness.simulation, 30);
182
183 const followerComps = componentsOf(harness.simulation, followerId);
184 const leaderComps = componentsOf(harness.simulation, leaderId);
185 assert.equal(followerComps.follow.targetEntityId, leaderId);
186 const dist = Math.max(
187 Math.abs(followerComps.position.tileX - leaderComps.position.tileX),
188 Math.abs(followerComps.position.tileY - leaderComps.position.tileY)
189 );
190 assert.ok(dist >= 1);
191 assert.ok(dist <= 3);
192 assert.ok(
193 followerComps.position.tileX > 6,
194 "follower should have advanced along the leader path"
195 );
196 }
197 finally
198 { harness.close(); }
199 });
@@ -0,0 +1,199 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { GAIT } from "../../shared/protocol/constants.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { mobComponents } from "../src/simulation/spawners.js";
6import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7
8function workerOf (simulation, entityId)
9{
10 const record = simulation.entityRecord(entityId);
11 assert.ok(record);
12 return simulation.workers[record.workerId];
13}
14
15function componentsOf (simulation, entityId)
16{
17 const worker = workerOf(simulation, entityId);
18 const handle = worker.world.ecs.handleOf(entityId);
19 assert.ok(handle != null);
20 return worker.world.ecs.componentsOf(handle);
21}
22
23test("follow stays put when already adjacent", () =>
24{
25 const harness = makeSimulation({ workerCount: 1 });
26 try
27 {
28 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
29 const playerId = harness.simulation.spawnCharacter(1, character);
30 const deerId = harness.simulation.spawnEntity(mobComponents({
31 tileX: 9,
32 tileY: 8,
33 mobTypeId: MobId.deer
34 }));
35 harness.simulation.enqueue(1, {
36 type: "follow",
37 characterId: character.character_id,
38 targetEntityId: deerId
39 });
40 harness.simulation.step();
41 const comps = componentsOf(harness.simulation, playerId);
42 assert.equal(comps.follow.targetEntityId, deerId);
43 assert.deepEqual(comps.path?.tiles ?? [], []);
44 }
45 finally
46 { harness.close(); }
47});
48
49test("follow runs when more than three tiles away and breaks past a chunk", () =>
50{
51 const harness = makeSimulation({ workerCount: 1 });
52 try
53 {
54 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
55 const playerId = harness.simulation.spawnCharacter(1, character);
56 const deerId = harness.simulation.spawnEntity(mobComponents({
57 tileX: 7,
58 tileY: 8,
59 mobTypeId: MobId.deer
60 }));
61 harness.simulation.enqueue(1, {
62 type: "follow",
63 characterId: character.character_id,
64 targetEntityId: deerId
65 });
66 harness.simulation.step();
67 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.run);
68 assert.ok((componentsOf(harness.simulation, playerId).path?.tiles?.length ?? 0) > 0);
69
70 const farDeer = harness.simulation.spawnEntity(mobComponents({
71 tileX: 20,
72 tileY: 8,
73 mobTypeId: MobId.deer
74 }));
75 harness.simulation.enqueue(1, {
76 type: "follow",
77 characterId: character.character_id,
78 targetEntityId: farDeer
79 });
80 harness.simulation.step();
81 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, null);
82 }
83 finally
84 { harness.close(); }
85});
86
87test("follow matches target gait within three tiles and works on any mobile", () =>
88{
89 const harness = makeSimulation({ workerCount: 1 });
90 try
91 {
92 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
93 const playerId = harness.simulation.spawnCharacter(1, character);
94 const ratId = harness.simulation.spawnEntity(mobComponents({
95 tileX: 11,
96 tileY: 8,
97 mobTypeId: MobId.rat
98 }));
99 const ratHandle = workerOf(harness.simulation, ratId).world.ecs.handleOf(ratId);
100 workerOf(harness.simulation, ratId).world.ecs.get(ratHandle, "movement").gait = GAIT.run;
101
102 harness.simulation.enqueue(1, {
103 type: "follow",
104 characterId: character.character_id,
105 targetEntityId: ratId
106 });
107 harness.simulation.step();
108 assert.equal(componentsOf(harness.simulation, playerId).movement.gait, GAIT.run);
109
110 const pigeonId = harness.simulation.spawnEntity(mobComponents({
111 tileX: 10,
112 tileY: 8,
113 mobTypeId: MobId.pigeon
114 }));
115 harness.simulation.enqueue(1, {
116 type: "follow",
117 characterId: character.character_id,
118 targetEntityId: pigeonId
119 });
120 harness.simulation.step();
121 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, pigeonId);
122 }
123 finally
124 { harness.close(); }
125});
126
127test("move-to clears follow", () =>
128{
129 const harness = makeSimulation({ workerCount: 1 });
130 try
131 {
132 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
133 const playerId = harness.simulation.spawnCharacter(1, character);
134 const deerId = harness.simulation.spawnEntity(mobComponents({
135 tileX: 10,
136 tileY: 8,
137 mobTypeId: MobId.deer
138 }));
139 harness.simulation.enqueue(1, {
140 type: "follow",
141 characterId: character.character_id,
142 targetEntityId: deerId
143 });
144 harness.simulation.step();
145 harness.simulation.enqueue(1, {
146 type: "move-to",
147 characterId: character.character_id,
148 tileX: 4,
149 tileY: 8
150 });
151 harness.simulation.step();
152 assert.equal(componentsOf(harness.simulation, playerId).follow.targetEntityId, null);
153 }
154 finally
155 { harness.close(); }
156});
157
158test("follower reuses the target vacated trail and waits off their tile", () =>
159{
160 const harness = makeSimulation({ workerCount: 1 });
161 try
162 {
163 const leader = makeCharacter(harness.stateDb, { firstName: "Lead", tileX: 8, tileY: 8 });
164 const follower = makeCharacter(harness.stateDb, { firstName: "Follow", lastName: "Bot", tileX: 6, tileY: 8 });
165 const leaderId = harness.simulation.spawnCharacter(1, leader);
166 const followerId = harness.simulation.spawnCharacter(2, follower);
167
168 harness.simulation.enqueue(2, {
169 type: "follow",
170 characterId: follower.character_id,
171 targetEntityId: leaderId
172 });
173 harness.simulation.step();
174
175 harness.simulation.enqueue(1, {
176 type: "move-to",
177 characterId: leader.character_id,
178 tileX: 12,
179 tileY: 8
180 });
181 stepTimes(harness.simulation, 30);
182
183 const followerComps = componentsOf(harness.simulation, followerId);
184 const leaderComps = componentsOf(harness.simulation, leaderId);
185 assert.equal(followerComps.follow.targetEntityId, leaderId);
186 const dist = Math.max(
187 Math.abs(followerComps.position.tileX - leaderComps.position.tileX),
188 Math.abs(followerComps.position.tileY - leaderComps.position.tileY)
189 );
190 assert.ok(dist >= 1);
191 assert.ok(dist <= 3);
192 assert.ok(
193 followerComps.position.tileX > 6,
194 "follower should have advanced along the leader path"
195 );
196 }
197 finally
198 { harness.close(); }
199});
server/tests/inventory.test.js +3 −1
@@ -124,9 +124,11 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
124 124 harness.simulation.spawnCharacter(1, character);
125 125 for (let i = 0; i < 80; i++)
126 126 { harness.simulation.step(); }
127 const deer = harness.simulation.debugWorld().entities.filter((entity) => !entity.characterId);
127 const deer = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Deer");
128 128 assert.ok(deer.length >= 1);
129 129 assert.ok(deer.length <= 2);
130 const pigeons = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Pigeon");
131 assert.equal(pigeons.length, 0);
130 132 }
131 133 finally
132 134 { harness.close(); }
@@ -124,9 +124,11 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
124 harness.simulation.spawnCharacter(1, character);
124 harness.simulation.spawnCharacter(1, character);
125 for (let i = 0; i < 80; i++)
125 for (let i = 0; i < 80; i++)
126 { harness.simulation.step(); }
126 { harness.simulation.step(); }
127 const deer = harness.simulation.debugWorld().entities.filter((entity) => !entity.characterId);
127 const deer = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Deer");
128 assert.ok(deer.length >= 1);
128 assert.ok(deer.length >= 1);
129 assert.ok(deer.length <= 2);
129 assert.ok(deer.length <= 2);
130 const pigeons = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Pigeon");
131 assert.equal(pigeons.length, 0);
130 }
132 }
131 finally
133 finally
132 { harness.close(); }
134 { harness.close(); }
server/tests/tile-states.test.js +4 −0
@@ -30,6 +30,10 @@ test("bloom companions are not visual states", () =>
30 30 assert.ok(!catalog.images.some((image) => image.name === "item:stick:stick:equip:bloom"));
31 31 assert.ok(catalog.images.some((image) => image.name === "item:paper:paper"));
32 32 assert.ok(catalog.images.some((image) => image.name === "mob:deer:deer"));
33 assert.ok(catalog.images.some((image) => image.name === "mob:pigeon:pigeon-flying"));
34 const pigeon = catalog.images.find((image) => image.name === "mob:pigeon:pigeon-flying");
35 assert.equal(pigeon.subImgTotal, 2);
36 assert.equal(pigeon.perRow, 2);
33 37 assert.ok(catalog.images.some((image) => image.name === "character:player-body-male:player-body-male"));
34 38 assert.ok(!catalog.blocks.torch.states.includes("torch-bloom"));
35 39 assert.ok(!catalog.blocks.torch.states.some((state) => state.includes("equip")));
@@ -30,6 +30,10 @@ test("bloom companions are not visual states", () =>
30 assert.ok(!catalog.images.some((image) => image.name === "item:stick:stick:equip:bloom"));
30 assert.ok(!catalog.images.some((image) => image.name === "item:stick:stick:equip:bloom"));
31 assert.ok(catalog.images.some((image) => image.name === "item:paper:paper"));
31 assert.ok(catalog.images.some((image) => image.name === "item:paper:paper"));
32 assert.ok(catalog.images.some((image) => image.name === "mob:deer:deer"));
32 assert.ok(catalog.images.some((image) => image.name === "mob:deer:deer"));
33 assert.ok(catalog.images.some((image) => image.name === "mob:pigeon:pigeon-flying"));
34 const pigeon = catalog.images.find((image) => image.name === "mob:pigeon:pigeon-flying");
35 assert.equal(pigeon.subImgTotal, 2);
36 assert.equal(pigeon.perRow, 2);
33 assert.ok(catalog.images.some((image) => image.name === "character:player-body-male:player-body-male"));
37 assert.ok(catalog.images.some((image) => image.name === "character:player-body-male:player-body-male"));
34 assert.ok(!catalog.blocks.torch.states.includes("torch-bloom"));
38 assert.ok(!catalog.blocks.torch.states.includes("torch-bloom"));
35 assert.ok(!catalog.blocks.torch.states.some((state) => state.includes("equip")));
39 assert.ok(!catalog.blocks.torch.states.some((state) => state.includes("equip")));
shared/definitions/items.js +10 −1
@@ -1,4 +1,5 @@
1 1 import { equipImageName, spriteImageName } from "./tileSprites.js";
2 import { SkillId } from "./skills.js";
2 3
3 4 export const ItemId = Object.freeze({
4 5 paper: 1,
@@ -62,7 +63,15 @@ export const ITEM_DEFINITIONS = Object.freeze({
62 63 uniqueInstance: false,
63 64 category: "finished",
64 65 equipment: Object.freeze({
65 slot: EQUIPMENT_SLOT.weapon
66 slot: EQUIPMENT_SLOT.weapon,
67 attack: Object.freeze({
68 mode: "melee",
69 rangeTiles: 1,
70 hitSkillId: SkillId.clubfighting,
71 damageSkillId: SkillId.strength,
72 cooldownMs: 700,
73 baseDamage: 2
74 })
66 75 })
67 76 }),
68 77 [ItemId.blankCheque]: Object.freeze({
@@ -1,4 +1,5 @@
1import { equipImageName, spriteImageName } from "./tileSprites.js";
1import { equipImageName, spriteImageName } from "./tileSprites.js";
2import { SkillId } from "./skills.js";
2
3
3export const ItemId = Object.freeze({
4export const ItemId = Object.freeze({
4 paper: 1,
5 paper: 1,
@@ -62,7 +63,15 @@ export const ITEM_DEFINITIONS = Object.freeze({
62 uniqueInstance: false,
63 uniqueInstance: false,
63 category: "finished",
64 category: "finished",
64 equipment: Object.freeze({
65 equipment: Object.freeze({
65 slot: EQUIPMENT_SLOT.weapon
66 slot: EQUIPMENT_SLOT.weapon,
67 attack: Object.freeze({
68 mode: "melee",
69 rangeTiles: 1,
70 hitSkillId: SkillId.clubfighting,
71 damageSkillId: SkillId.strength,
72 cooldownMs: 700,
73 baseDamage: 2
74 })
66 })
75 })
67 }),
76 }),
68 [ItemId.blankCheque]: Object.freeze({
77 [ItemId.blankCheque]: Object.freeze({
shared/definitions/mobs.js +70 −3
@@ -1,18 +1,77 @@
1 1 import { spriteImageName } from "./tileSprites.js";
2 import { SkillId, UNARMED_ATTACK } from "./skills.js";
2 3
3 4 export const MobId = Object.freeze({
4 deer: "deer"
5 deer: "deer",
6 pigeon: "pigeon",
7 rat: "rat"
5 8 });
6 9
7 10 export const MOB_DEFINITIONS = Object.freeze({
8 11 [MobId.deer]: Object.freeze({
9 12 mobTypeId: MobId.deer,
10 13 key: "deer",
14 assetFolder: "mobs",
11 15 displayName: "Deer",
12 16 persistent: false,
17 flying: false,
18 freeFlight: false,
19 ambient: false,
20 hostile: false,
21 talkable: false,
22 untargetable: false,
13 23 gait: "walk",
14 24 sex: "male",
15 health: 8
25 health: 8,
26 frames: 1,
27 framesPerRow: 1,
28 animationSpeed: 0
29 }),
30 [MobId.pigeon]: Object.freeze({
31 mobTypeId: MobId.pigeon,
32 key: "pigeon",
33 assetFolder: "pigeons",
34 displayName: "Pigeon",
35 persistent: false,
36 flying: true,
37 freeFlight: true,
38 ambient: false,
39 hostile: false,
40 talkable: false,
41 untargetable: true,
42 gait: "walk",
43 sex: "male",
44 health: 1,
45 frames: 2,
46 framesPerRow: 2,
47 animationSpeed: 0.18,
48 defaultState: "pigeon-flying",
49 flightSpeedTilesPerSec: 2.5
50 }),
51 [MobId.rat]: Object.freeze({
52 mobTypeId: MobId.rat,
53 key: "rat",
54 assetFolder: "mobs",
55 displayName: "Rat",
56 persistent: false,
57 flying: false,
58 freeFlight: false,
59 ambient: false,
60 hostile: true,
61 talkable: false,
62 untargetable: false,
63 gait: "walk",
64 sex: "male",
65 health: 12,
66 frames: 1,
67 framesPerRow: 1,
68 animationSpeed: 0,
69 skillLevels: Object.freeze({
70 [SkillId.unarmed]: 3,
71 [SkillId.strength]: 3,
72 [SkillId.defence]: 1
73 }),
74 defaultAttack: Object.freeze({ ...UNARMED_ATTACK, baseDamage: 2, cooldownMs: 900 })
16 75 })
17 76 });
18 77
@@ -25,7 +84,10 @@ export function mobSpriteName (mobTypeId)
25 84 {
26 85 const def = mobDefinition(mobTypeId);
27 86 const key = def?.key ?? def?.mobTypeId ?? "deer";
28 return def?.sprite ?? spriteImageName("mob", key, key);
87 if (def?.sprite)
88 { return def.sprite; }
89 const state = def?.defaultState ?? key;
90 return spriteImageName("mob", key, state);
29 91 }
30 92
31 93 export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
@@ -37,3 +99,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
37 99 spawnRangeTiles: 4
38 100 };
39 101 }
102
103 export function listAmbientMobTypes ()
104 {
105 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
106 }
@@ -1,18 +1,77 @@
1import { spriteImageName } from "./tileSprites.js";
1import { spriteImageName } from "./tileSprites.js";
2import { SkillId, UNARMED_ATTACK } from "./skills.js";
2
3
3export const MobId = Object.freeze({
4export const MobId = Object.freeze({
4 deer: "deer"
5 deer: "deer",
6 pigeon: "pigeon",
7 rat: "rat"
5});
8});
6
9
7export const MOB_DEFINITIONS = Object.freeze({
10export const MOB_DEFINITIONS = Object.freeze({
8 [MobId.deer]: Object.freeze({
11 [MobId.deer]: Object.freeze({
9 mobTypeId: MobId.deer,
12 mobTypeId: MobId.deer,
10 key: "deer",
13 key: "deer",
14 assetFolder: "mobs",
11 displayName: "Deer",
15 displayName: "Deer",
12 persistent: false,
16 persistent: false,
17 flying: false,
18 freeFlight: false,
19 ambient: false,
20 hostile: false,
21 talkable: false,
22 untargetable: false,
13 gait: "walk",
23 gait: "walk",
14 sex: "male",
24 sex: "male",
15 health: 8
25 health: 8,
26 frames: 1,
27 framesPerRow: 1,
28 animationSpeed: 0
29 }),
30 [MobId.pigeon]: Object.freeze({
31 mobTypeId: MobId.pigeon,
32 key: "pigeon",
33 assetFolder: "pigeons",
34 displayName: "Pigeon",
35 persistent: false,
36 flying: true,
37 freeFlight: true,
38 ambient: false,
39 hostile: false,
40 talkable: false,
41 untargetable: true,
42 gait: "walk",
43 sex: "male",
44 health: 1,
45 frames: 2,
46 framesPerRow: 2,
47 animationSpeed: 0.18,
48 defaultState: "pigeon-flying",
49 flightSpeedTilesPerSec: 2.5
50 }),
51 [MobId.rat]: Object.freeze({
52 mobTypeId: MobId.rat,
53 key: "rat",
54 assetFolder: "mobs",
55 displayName: "Rat",
56 persistent: false,
57 flying: false,
58 freeFlight: false,
59 ambient: false,
60 hostile: true,
61 talkable: false,
62 untargetable: false,
63 gait: "walk",
64 sex: "male",
65 health: 12,
66 frames: 1,
67 framesPerRow: 1,
68 animationSpeed: 0,
69 skillLevels: Object.freeze({
70 [SkillId.unarmed]: 3,
71 [SkillId.strength]: 3,
72 [SkillId.defence]: 1
73 }),
74 defaultAttack: Object.freeze({ ...UNARMED_ATTACK, baseDamage: 2, cooldownMs: 900 })
16 })
75 })
17});
76});
18
77
@@ -25,7 +84,10 @@ export function mobSpriteName (mobTypeId)
25{
84{
26 const def = mobDefinition(mobTypeId);
85 const def = mobDefinition(mobTypeId);
27 const key = def?.key ?? def?.mobTypeId ?? "deer";
86 const key = def?.key ?? def?.mobTypeId ?? "deer";
28 return def?.sprite ?? spriteImageName("mob", key, key);
87 if (def?.sprite)
88 { return def.sprite; }
89 const state = def?.defaultState ?? key;
90 return spriteImageName("mob", key, state);
29}
91}
30
92
31export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
93export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
@@ -37,3 +99,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
37 spawnRangeTiles: 4
99 spawnRangeTiles: 4
38 };
100 };
39}
101}
102
103export function listAmbientMobTypes ()
104{
105 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
106}
shared/definitions/skills.js added +53 −0
@@ -0,0 +1,53 @@
1 export const SkillId = Object.freeze({
2 clubfighting: "clubfighting",
3 swordfighting: "swordfighting",
4 axefighting: "axefighting",
5 archery: "archery",
6 unarmed: "unarmed",
7 magic: "magic",
8 strength: "strength",
9 dexterity: "dexterity",
10 mind: "mind",
11 defence: "defence"
12 });
13
14 export const SKILL_DEFINITIONS = Object.freeze({
15 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
16 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
17 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axe fighting" }),
18 [SkillId.archery]: Object.freeze({ skillId: SkillId.archery, displayName: "Archery" }),
19 [SkillId.unarmed]: Object.freeze({ skillId: SkillId.unarmed, displayName: "Unarmed" }),
20 [SkillId.magic]: Object.freeze({ skillId: SkillId.magic, displayName: "Magic" }),
21 [SkillId.strength]: Object.freeze({ skillId: SkillId.strength, displayName: "Strength" }),
22 [SkillId.dexterity]: Object.freeze({ skillId: SkillId.dexterity, displayName: "Dexterity" }),
23 [SkillId.mind]: Object.freeze({ skillId: SkillId.mind, displayName: "Mind" }),
24 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" })
25 });
26
27 export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze({
28 [SkillId.clubfighting]: 1,
29 [SkillId.swordfighting]: 1,
30 [SkillId.axefighting]: 1,
31 [SkillId.archery]: 1,
32 [SkillId.unarmed]: 1,
33 [SkillId.magic]: 1,
34 [SkillId.strength]: 1,
35 [SkillId.dexterity]: 1,
36 [SkillId.mind]: 1,
37 [SkillId.defence]: 1
38 });
39
40 export const UNARMED_ATTACK = Object.freeze({
41 mode: "melee",
42 rangeTiles: 1,
43 hitSkillId: SkillId.unarmed,
44 damageSkillId: SkillId.strength,
45 cooldownMs: 800,
46 baseDamage: 1
47 });
48
49 export function skillLevel (skills, skillId)
50 {
51 const levels = skills?.levels ?? skills ?? {};
52 return Math.max(1, levels[skillId] | 0 || 1);
53 }
@@ -0,0 +1,53 @@
1export const SkillId = Object.freeze({
2 clubfighting: "clubfighting",
3 swordfighting: "swordfighting",
4 axefighting: "axefighting",
5 archery: "archery",
6 unarmed: "unarmed",
7 magic: "magic",
8 strength: "strength",
9 dexterity: "dexterity",
10 mind: "mind",
11 defence: "defence"
12});
13
14export const SKILL_DEFINITIONS = Object.freeze({
15 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
16 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
17 [SkillId.axefighting]: Object.freeze({ skillId: SkillId.axefighting, displayName: "Axe fighting" }),
18 [SkillId.archery]: Object.freeze({ skillId: SkillId.archery, displayName: "Archery" }),
19 [SkillId.unarmed]: Object.freeze({ skillId: SkillId.unarmed, displayName: "Unarmed" }),
20 [SkillId.magic]: Object.freeze({ skillId: SkillId.magic, displayName: "Magic" }),
21 [SkillId.strength]: Object.freeze({ skillId: SkillId.strength, displayName: "Strength" }),
22 [SkillId.dexterity]: Object.freeze({ skillId: SkillId.dexterity, displayName: "Dexterity" }),
23 [SkillId.mind]: Object.freeze({ skillId: SkillId.mind, displayName: "Mind" }),
24 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" })
25});
26
27export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze({
28 [SkillId.clubfighting]: 1,
29 [SkillId.swordfighting]: 1,
30 [SkillId.axefighting]: 1,
31 [SkillId.archery]: 1,
32 [SkillId.unarmed]: 1,
33 [SkillId.magic]: 1,
34 [SkillId.strength]: 1,
35 [SkillId.dexterity]: 1,
36 [SkillId.mind]: 1,
37 [SkillId.defence]: 1
38});
39
40export const UNARMED_ATTACK = Object.freeze({
41 mode: "melee",
42 rangeTiles: 1,
43 hitSkillId: SkillId.unarmed,
44 damageSkillId: SkillId.strength,
45 cooldownMs: 800,
46 baseDamage: 1
47});
48
49export function skillLevel (skills, skillId)
50{
51 const levels = skills?.levels ?? skills ?? {};
52 return Math.max(1, levels[skillId] | 0 || 1);
53}
shared/protocol/constants.js +9 −1
@@ -98,6 +98,14 @@ export const MessageType = Object.freeze({
98 98 bankSnapshot: "BANK_SNAPSHOT",
99 99 bankDeposit: "BANK_DEPOSIT",
100 100 bankWithdraw: "BANK_WITHDRAW",
101 claimInheritance: "CLAIM_INHERITANCE"
101 claimInheritance: "CLAIM_INHERITANCE",
102 attack: "ATTACK",
103 cancelAttack: "CANCEL_ATTACK",
104 interact: "INTERACT",
105 combatSwing: "COMBAT_SWING",
106 combatHit: "COMBAT_HIT",
107 combatMiss: "COMBAT_MISS",
108 follow: "FOLLOW",
109 cancelFollow: "CANCEL_FOLLOW"
102 110 });
103 111
@@ -98,6 +98,14 @@ export const MessageType = Object.freeze({
98 bankSnapshot: "BANK_SNAPSHOT",
98 bankSnapshot: "BANK_SNAPSHOT",
99 bankDeposit: "BANK_DEPOSIT",
99 bankDeposit: "BANK_DEPOSIT",
100 bankWithdraw: "BANK_WITHDRAW",
100 bankWithdraw: "BANK_WITHDRAW",
101 claimInheritance: "CLAIM_INHERITANCE"
101 claimInheritance: "CLAIM_INHERITANCE",
102 attack: "ATTACK",
103 cancelAttack: "CANCEL_ATTACK",
104 interact: "INTERACT",
105 combatSwing: "COMBAT_SWING",
106 combatHit: "COMBAT_HIT",
107 combatMiss: "COMBAT_MISS",
108 follow: "FOLLOW",
109 cancelFollow: "CANCEL_FOLLOW"
102});
110});
103
111
tile_mmo_server_technical_design_v0.6.md +127 −105
@@ -1,13 +1,13 @@
1 1 ---
2 2 title: Tile MMO Server Technical Design
3 version: 0.20
3 version: 0.21
4 4 status: proposed
5 5 format: living-design-document
6 6 ---
7 7
8 8 # Tile MMO Server Technical Design
9 9
10 **Version:** 0.20
10 **Version:** 0.21
11 11 **Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12 12 **Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13 13
@@ -632,6 +632,15 @@ so a torch fades tile-by-tile rather than lighting a hard disc. Peak
632 632 unlit darkness is `nightDarkness` (a live world setting). It is
633 633 replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
634 634
635 On the client, immobile ground and ≤16×16 static blocks (plus their
636 bloom companions) are composited into per-chunk atlases when a snapshot
637 arrives: one ground image, one block strip per tile row (so Y-sort still
638 interleaves mobiles between rows), and one bloom image for the bloom
639 render layer. Blocks taller than 16×16 or with animation stay as
640 individual sprites. Night shade overlays darken the baked atlases per
641 tile; oversized sprites and mobiles instead receive a uniform shade from
642 the darkness of the tile they stand on.
643
635 644 Runtime door open/close does not rebake static light unless a later
636 645 iteration adds live lighting. Baked light is authored geometry.
637 646
@@ -2563,141 +2572,154 @@ attempted, or a tooltip refresh is requested.
2563 2572 ## 26.1 Every combatant can attack
2564 2573
2565 2574 Players, enemies, animals and any other mobile with a `Combat` component can
2566 attack. Shopkeepers and other non-fighting NPCs simply omit `Combat`, or
2567 never issue attack commands.
2568
2569 Attacking is an intention. The client (or AI, or a future script) sends
2570 `ATTACK(targetEntityId)`. The owning worker validates range, line-of-use,
2571 the current attack profile and cooldown, then resolves hit and damage
2572 authoritatively. The client never supplies a hit result or a damage number.
2573
2574 Cross-worker attacks already use `REMOTE_ACTION(attack intent)`: the worker
2575 that owns the target applies the authoritative result.
2575 attack. Shopkeepers and other non-fighting NPCs omit `Combat`, or never issue
2576 attack commands. Courier **pigeons** are **untargetable**: they have no `Combat`
2577 component and cannot be selected for Attack, Talk, or spells. They are not
2578 ambient wildlife; the courier/mail system spawns them for player↔player or
2579 player↔bank delivery and they fly in straight world-space lines.
2580
2581 Attacking is an intention. The client (or AI) sends `ATTACK(targetEntityId)`.
2582 The owning worker validates range, line of sight when required, the current
2583 attack profile and cooldown, then resolves hit and damage authoritatively.
2584 The client never supplies a hit result or a damage number.
2585
2586 `CANCEL_ATTACK` clears the actor's engage target. Cross-worker attacks use
2587 `REMOTE_ACTION(attack intent)` so the worker that owns the target applies the
2588 authoritative result.
2589
2590 ## 26.1b Client targeting and context menus
2591
2592 | Input | Target | Action |
2593 |-------|--------|--------|
2594 | LMB | other player | inspect (existing social UI) |
2595 | LMB | talkable friendly mob | `INTERACT` / open dialogue (shop content later) |
2596 | LMB | hostile combatant | `ATTACK` (auto-engage) |
2597 | LMB | ground / empty | `MOVE_TO` that tile (or pickup/bank as today) |
2598 | RMB | other player | Walk here · Follow · `<name> info` · Attack |
2599 | RMB | mob | Walk here · Follow · Talk (if talkable) · Attack |
2600 | Any | untargetable (pigeon) | Follow allowed; no Attack/Talk |
2601
2602 Walk here issues `MOVE_TO` for the entity's tile (or the tile under the cursor
2603 when RMB is on empty ground).
2604
2605 ## 26.1b2 Follow
2606
2607 `FOLLOW(targetEntityId)` makes the actor trail another mobile. No line of
2608 sight is required. Follow works on every mobile (players, wildlife, pigeons).
2609
2610 | Chebyshev distance | Behaviour |
2611 |--------------------|-----------|
2612 | ≤ 1 | Stay put (already in good position) |
2613 | 2–3 | Follow the target's vacated trail and remaining path; walk, or run if the target is running |
2614 | > 3 and ≤ chunk width (16) | Same route reuse, always run |
2615 | > chunk width | Break follow |
2616
2617 The follower reuses the target's path instead of independent A* once a trail
2618 exists: each time the target leaves a tile that tile is appended to the
2619 follower trail, combined with the target's remaining `path.tiles`. The
2620 follower stops one tile short of the target's current tile and waits until
2621 that tile is vacated; every step still checks walkability. If there is no
2622 shared trail yet, a one-shot catch-up path to an 8-neighbour is used.
2623
2624 `MOVE_TO` and `ATTACK` clear follow. `CANCEL_FOLLOW` clears it explicitly.
2625
2626 ## 26.1c Auto-attack and retaliation
2627
2628 Engaging sets `Combat.targetEntityId`. The weapon supplies a single
2629 `AttackProfile` that repeats until cancel, death, or the target leaves
2630 reachable range (then re-path / re-close).
2631
2632 When a combatant is hit, if it has `Combat` it **immediately engages** the
2633 attacker (players and mobs). Peaceful NPCs without `Combat` do not retaliate.
2634
2635 - **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2636 exactly 1.
2637 - **Ranged:** pathfind until Chebyshev distance ≤ `rangeTiles`, then fire.
2638 Requires line of sight through passable tiles (same obstruction rule as
2639 baked light).
2640 - **Magic:** not a default auto-attack. The player opens a spell menu, picks a
2641 known spell, then clicks a target. Utility spells cast once; attack spells
2642 repeat like weapon auto-attack. Full spell targeting (tiles, blocks, ground
2643 items) is a later batch.
2576 2644
2577 2645 ## 26.2 Attack profiles
2578 2646
2579 The current attack comes from the wielder's selected profile: a wielded
2580 weapon's `AttackProfile`, a selected spell, or a default unarmed melee
2581 profile when nothing is wielded.
2647 The current attack comes from the weapon slot's `AttackProfile`, a selected
2648 spell, or a default unarmed melee profile when nothing is wielded.
2582 2649
2583 2650 ```text
2584 2651 AttackProfile
2585 - attackId
2586 2652 - mode: melee | ranged | magic
2587 - rangeTiles // melee is always 1; ranged/magic from the item or spell
2653 - rangeTiles // melee is always 1
2588 2654 - hitSkillId
2589 2655 - damageSkillId
2656 - cooldownMs
2657 - baseDamage
2590 2658 ```
2591 2659
2592 2660 ```text
2593 SpellDefinition
2661 SpellDefinition (content; full cast UI later)
2594 2662 - spellId
2595 2663 - displayName
2596 - AttackProfile // mode = magic, hitSkillId = Magic, damageSkillId = Mind
2597 - other costs/effects // later content
2664 - minSkillLevel
2665 - AttackProfile // mode = magic
2666 - castKind: utility | attack
2598 2667 ```
2599 2668
2669 A single **spellbook** item type carries one chosen `spellId` in its instance
2670 config (shop, drop, or spawner). If the character's Magic skill meets
2671 `minSkillLevel`, using the book teaches the spell and consumes the book.
2672
2600 2673 Typical weapon mappings:
2601 2674
2602 2675 ```text
2603 Sword -> melee, range 1, hit Swordfighting, damage Strength
2604 Axe -> melee, range 1, hit Axefighting, damage Strength
2605 Bow -> ranged, range from item, hit Archery, damage Dexterity
2606 Spell -> magic, range from spell, hit Magic, damage Mind
2607 Unarmed -> melee, range 1, hit Unarmed, damage Strength
2676 Stick/club -> melee, range 1, hit Clubfighting, damage Strength
2677 Sword -> melee, range 1, hit Swordfighting, damage Strength
2678 Bow -> ranged, range from item, hit Archery, damage Dexterity
2679 Spell -> magic, range from spell, hit Magic, damage Mind
2680 Unarmed -> melee, range 1, hit Unarmed, damage Strength
2608 2681 ```
2609 2682
2610 The exact weapon and spell catalogue is content. The pairing rule is not:
2611 melee weapons use a weapon skill plus **Strength**, ranged weapons use a
2612 weapon skill plus **Dexterity**, and spells use **Magic** plus **Mind**.
2613
2614 `EquipItem(slotIndex)` moves a legal item from inventory into the matching
2615 equipment slot (section 21.6). The **weapon** slot supplies the current
2616 `AttackProfile`. `SelectSpell(spellId)` selects a spell the actor is
2617 allowed to use. The selected profile determines range and both skills.
2618
2619 2683 ## 26.3 Melee range
2620 2684
2621 A melee attack is legal only when the attacker stands on **one of the eight
2622 tiles surrounding** the target's tile: orthogonal or diagonal, Chebyshev
2623 distance exactly 1. The attacker cannot melee from the target's own tile.
2624
2625 ```text
2626 . . .
2627 . T . attacker must occupy one of the eight `.` tiles
2628 . . .
2629 ```
2630
2631 This adjacency rule is independent of whether ordinary walking is four- or
2632 eight-directional.
2633
2634 ## 26.4 Ranged attacks and spells
2635
2636 Ranged weapons and spells may fire from further away. Maximum Chebyshev
2637 distance is `rangeTiles` on that item or spell. Distance 0 (same tile) is
2638 not a legal ranged/spell attack unless a later exception is defined.
2685 A melee attack is legal only on one of the eight tiles surrounding the
2686 target (Chebyshev distance exactly 1). Same-tile melee is illegal.
2639 2687
2640 The attacker must still occupy a simulating chunk and satisfy any later
2641 line-of-sight rule. Exact obstruction rules are an open content decision;
2642 range itself is not.
2688 ## 26.4 Ranged attacks, spells and LOS
2643 2689
2644 ## 26.5 Hit roll
2645
2646 Whether the attack lands is a server-side roll driven by the **hit skill**
2647 of the current profile (Swordfighting, Axefighting, Archery, Magic, Unarmed,
2648 and so on). The client does not roll.
2649
2650 The exact hit curve, any defender contribution from Defence, and the RNG
2651 are later tuning. The invariant is that the hit chance is a function of the
2652 attacker's hit-skill level, not of Strength, Dexterity or Mind.
2653
2654 A miss deals no damage.
2655
2656 ## 26.6 Damage
2657
2658 On a hit, damage is determined by the **damage skill**:
2659
2660 - Melee → Strength
2661 - Ranged → Dexterity
2662 - Magic → Mind
2663
2664 Weapon or spell base damage and the defender's mitigation (including whether
2665 Defence reduces damage) are later tuning. The governing damage skill is not.
2666
2667 ## 26.7 Experience split
2668
2669 When a **player** successfully hits, the attack's XP award is split equally
2670 between the hit skill and the damage skill:
2671
2672 ```text
2673 totalXp = attack xp formula for this successful hit
2674 hitSkill += totalXp / 2
2675 damageSkill += totalXp / 2
2676 ```
2690 Maximum Chebyshev distance is `rangeTiles`. Distance 0 is not legal unless a
2691 later exception is defined. Ranged and magic require line of sight: a ray
2692 through tile centres fails if it crosses an impassable block (same rule as
2693 baked lighting).
2677 2694
2678 Example: a sword hit awards half its XP to Swordfighting and half to
2679 Strength. A bow hit splits Archery and Dexterity. A spell hit splits Magic
2680 and Mind.
2695 ## 26.4b Presentation: swipe, projectiles, dynamic lights
2681 2696
2682 If an unusual profile ever named the same skill twice, XP is awarded once,
2683 not doubled. Misses award no combat XP. Ordinary mobs do not earn XP; their
2684 `Skills` component is filled from the mob archetype and stays at those
2685 levels.
2697 - **Melee:** clients draw a swipe sprite for ~0.5s between attacker and
2698 defender, rotated toward the defender, on `COMBAT_SWING`.
2699 - **Ranged / spell:** straight-line world-space projectiles (not grid steps)
2700 toward the defender tile or a miss tile beside it. Spell projectiles may
2701 use a `-bloom` companion.
2702 - **Dynamic lights (client-only):** short flashes on cast/hit; equipment with
2703 `lightRadiusTiles` (e.g. lantern) as a moving point light. Per-tile shade
2704 blends `max(bakedNightShade, dynamicContribution)`.
2686 2705
2687 Non-combat actions remain single-skill as in section 27.4.
2706 ## 26.5–26.8 Hit, damage, XP, mob stats
2688 2707
2689 ## 26.8 Mob combat stats
2708 Hit chance uses the profile's hit skill (server RNG). Damage uses Strength
2709 (melee), Dexterity (ranged), or Mind (magic). Player hit XP splits equally
2710 between hit and damage skills. Mobs use archetype skill levels and do not
2711 earn XP.
2690 2712
2691 2713 ```text
2692 2714 MobDefinition
2693 - ...
2694 - skillLevels: { skillId → level }
2695 - defaultAttack: attackId | unarmed
2715 - hostile / talkable / untargetable / freeFlight / flying
2716 - skillLevels, defaultAttack
2717 - Combat omitted when untargetable or peaceful non-fighter
2696 2718 ```
2697 2719
2698 A wolf might have Unarmed and Strength. An archer guard might have Archery
2699 and Dexterity. Those levels feed the same hit and damage resolution as
2700 players.
2720 Courier **pigeons** use free-flight: straight-line world motion between
2721 delivery endpoints, no pathfinding, not bound to the navigation grid, and
2722 untargetable for all attacks and spells. They are not ambient fauna.
2701 2723
2702 2724 # 27. Player-driven economy and skill progression
2703 2725
@@ -3443,8 +3465,8 @@ CourierService → pigeons carrying money or one item stack through durable tran
3443 3465 BankService → shared unlimited vaults, cheque reservations and redemption
3444 3466 MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3445 3467 Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3446 Combat → 8-tile melee, item/spell ranged range; hit skill roll; Strength / Dexterity / Mind damage; equal XP split
3447 Skills → classless progression; non-combat XP to one skill; attack XP split hit/damage
3468 Combat → melee auto-attack + retaliate; 8-neighbour melee; ranged/spell later; courier pigeon free-flight untargetable
3469 Skills → classless progression; Clubfighting/Strength on stick; attack XP split hit/damage (curves later)
3448 3470
3449 3471
3450 3472 # 34. Version history
@@ -1,13 +1,13 @@
1---
1---
2title: Tile MMO Server Technical Design
2title: Tile MMO Server Technical Design
3version: 0.20
3version: 0.21
4status: proposed
4status: proposed
5format: living-design-document
5format: living-design-document
6---
6---
7
7
8# Tile MMO Server Technical Design
8# Tile MMO Server Technical Design
9
9
10**Version:** 0.20
10**Version:** 0.21
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
13
@@ -632,6 +632,15 @@ so a torch fades tile-by-tile rather than lighting a hard disc. Peak
632unlit darkness is `nightDarkness` (a live world setting). It is
632unlit darkness is `nightDarkness` (a live world setting). It is
633replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
633replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
634
634
635On the client, immobile ground and ≤16×16 static blocks (plus their
636bloom companions) are composited into per-chunk atlases when a snapshot
637arrives: one ground image, one block strip per tile row (so Y-sort still
638interleaves mobiles between rows), and one bloom image for the bloom
639render layer. Blocks taller than 16×16 or with animation stay as
640individual sprites. Night shade overlays darken the baked atlases per
641tile; oversized sprites and mobiles instead receive a uniform shade from
642the darkness of the tile they stand on.
643
635Runtime door open/close does not rebake static light unless a later
644Runtime door open/close does not rebake static light unless a later
636iteration adds live lighting. Baked light is authored geometry.
645iteration adds live lighting. Baked light is authored geometry.
637
646
@@ -2563,141 +2572,154 @@ attempted, or a tooltip refresh is requested.
2563## 26.1 Every combatant can attack
2572## 26.1 Every combatant can attack
2564
2573
2565Players, enemies, animals and any other mobile with a `Combat` component can
2574Players, enemies, animals and any other mobile with a `Combat` component can
2566attack. Shopkeepers and other non-fighting NPCs simply omit `Combat`, or
2575attack. Shopkeepers and other non-fighting NPCs omit `Combat`, or never issue
2567never issue attack commands.
2576attack commands. Courier **pigeons** are **untargetable**: they have no `Combat`
2568
2577component and cannot be selected for Attack, Talk, or spells. They are not
2569Attacking is an intention. The client (or AI, or a future script) sends
2578ambient wildlife; the courier/mail system spawns them for player↔player or
2570`ATTACK(targetEntityId)`. The owning worker validates range, line-of-use,
2579player↔bank delivery and they fly in straight world-space lines.
2571the current attack profile and cooldown, then resolves hit and damage
2580
2572authoritatively. The client never supplies a hit result or a damage number.
2581Attacking is an intention. The client (or AI) sends `ATTACK(targetEntityId)`.
2573
2582The owning worker validates range, line of sight when required, the current
2574Cross-worker attacks already use `REMOTE_ACTION(attack intent)`: the worker
2583attack profile and cooldown, then resolves hit and damage authoritatively.
2575that owns the target applies the authoritative result.
2584The client never supplies a hit result or a damage number.
2585
2586`CANCEL_ATTACK` clears the actor's engage target. Cross-worker attacks use
2587`REMOTE_ACTION(attack intent)` so the worker that owns the target applies the
2588authoritative result.
2589
2590## 26.1b Client targeting and context menus
2591
2592| Input | Target | Action |
2593|-------|--------|--------|
2594| LMB | other player | inspect (existing social UI) |
2595| LMB | talkable friendly mob | `INTERACT` / open dialogue (shop content later) |
2596| LMB | hostile combatant | `ATTACK` (auto-engage) |
2597| LMB | ground / empty | `MOVE_TO` that tile (or pickup/bank as today) |
2598| RMB | other player | Walk here · Follow · `<name> info` · Attack |
2599| RMB | mob | Walk here · Follow · Talk (if talkable) · Attack |
2600| Any | untargetable (pigeon) | Follow allowed; no Attack/Talk |
2601
2602Walk here issues `MOVE_TO` for the entity's tile (or the tile under the cursor
2603when RMB is on empty ground).
2604
2605## 26.1b2 Follow
2606
2607`FOLLOW(targetEntityId)` makes the actor trail another mobile. No line of
2608sight is required. Follow works on every mobile (players, wildlife, pigeons).
2609
2610| Chebyshev distance | Behaviour |
2611|--------------------|-----------|
2612| ≤ 1 | Stay put (already in good position) |
2613| 2–3 | Follow the target's vacated trail and remaining path; walk, or run if the target is running |
2614| > 3 and ≤ chunk width (16) | Same route reuse, always run |
2615| > chunk width | Break follow |
2616
2617The follower reuses the target's path instead of independent A* once a trail
2618exists: each time the target leaves a tile that tile is appended to the
2619follower trail, combined with the target's remaining `path.tiles`. The
2620follower stops one tile short of the target's current tile and waits until
2621that tile is vacated; every step still checks walkability. If there is no
2622shared trail yet, a one-shot catch-up path to an 8-neighbour is used.
2623
2624`MOVE_TO` and `ATTACK` clear follow. `CANCEL_FOLLOW` clears it explicitly.
2625
2626## 26.1c Auto-attack and retaliation
2627
2628Engaging sets `Combat.targetEntityId`. The weapon supplies a single
2629`AttackProfile` that repeats until cancel, death, or the target leaves
2630reachable range (then re-path / re-close).
2631
2632When a combatant is hit, if it has `Combat` it **immediately engages** the
2633attacker (players and mobs). Peaceful NPCs without `Combat` do not retaliate.
2634
2635- **Melee:** pathfind to an 8-neighbour tile, swing when Chebyshev distance is
2636 exactly 1.
2637- **Ranged:** pathfind until Chebyshev distance ≤ `rangeTiles`, then fire.
2638 Requires line of sight through passable tiles (same obstruction rule as
2639 baked light).
2640- **Magic:** not a default auto-attack. The player opens a spell menu, picks a
2641 known spell, then clicks a target. Utility spells cast once; attack spells
2642 repeat like weapon auto-attack. Full spell targeting (tiles, blocks, ground
2643 items) is a later batch.
2576
2644
2577## 26.2 Attack profiles
2645## 26.2 Attack profiles
2578
2646
2579The current attack comes from the wielder's selected profile: a wielded
2647The current attack comes from the weapon slot's `AttackProfile`, a selected
2580weapon's `AttackProfile`, a selected spell, or a default unarmed melee
2648spell, or a default unarmed melee profile when nothing is wielded.
2581profile when nothing is wielded.
2582
2649
2583```text
2650```text
2584AttackProfile
2651AttackProfile
2585- attackId
2586- mode: melee | ranged | magic
2652- mode: melee | ranged | magic
2587- rangeTiles // melee is always 1; ranged/magic from the item or spell
2653- rangeTiles // melee is always 1
2588- hitSkillId
2654- hitSkillId
2589- damageSkillId
2655- damageSkillId
2656- cooldownMs
2657- baseDamage
2590```
2658```
2591
2659
2592```text
2660```text
2593SpellDefinition
2661SpellDefinition (content; full cast UI later)
2594- spellId
2662- spellId
2595- displayName
2663- displayName
2596- AttackProfile // mode = magic, hitSkillId = Magic, damageSkillId = Mind
2664- minSkillLevel
2597- other costs/effects // later content
2665- AttackProfile // mode = magic
2666- castKind: utility | attack
2598```
2667```
2599
2668
2669A single **spellbook** item type carries one chosen `spellId` in its instance
2670config (shop, drop, or spawner). If the character's Magic skill meets
2671`minSkillLevel`, using the book teaches the spell and consumes the book.
2672
2600Typical weapon mappings:
2673Typical weapon mappings:
2601
2674
2602```text
2675```text
2603Sword -> melee, range 1, hit Swordfighting, damage Strength
2676Stick/club -> melee, range 1, hit Clubfighting, damage Strength
2604Axe -> melee, range 1, hit Axefighting, damage Strength
2677Sword -> melee, range 1, hit Swordfighting, damage Strength
2605Bow -> ranged, range from item, hit Archery, damage Dexterity
2678Bow -> ranged, range from item, hit Archery, damage Dexterity
2606Spell -> magic, range from spell, hit Magic, damage Mind
2679Spell -> magic, range from spell, hit Magic, damage Mind
2607Unarmed -> melee, range 1, hit Unarmed, damage Strength
2680Unarmed -> melee, range 1, hit Unarmed, damage Strength
2608```
2681```
2609
2682
2610The exact weapon and spell catalogue is content. The pairing rule is not:
2611melee weapons use a weapon skill plus **Strength**, ranged weapons use a
2612weapon skill plus **Dexterity**, and spells use **Magic** plus **Mind**.
2613
2614`EquipItem(slotIndex)` moves a legal item from inventory into the matching
2615equipment slot (section 21.6). The **weapon** slot supplies the current
2616`AttackProfile`. `SelectSpell(spellId)` selects a spell the actor is
2617allowed to use. The selected profile determines range and both skills.
2618
2619## 26.3 Melee range
2683## 26.3 Melee range
2620
2684
2621A melee attack is legal only when the attacker stands on **one of the eight
2685A melee attack is legal only on one of the eight tiles surrounding the
2622tiles surrounding** the target's tile: orthogonal or diagonal, Chebyshev
2686target (Chebyshev distance exactly 1). Same-tile melee is illegal.
2623distance exactly 1. The attacker cannot melee from the target's own tile.
2624
2625```text
2626. . .
2627. T . attacker must occupy one of the eight `.` tiles
2628. . .
2629```
2630
2631This adjacency rule is independent of whether ordinary walking is four- or
2632eight-directional.
2633
2634## 26.4 Ranged attacks and spells
2635
2636Ranged weapons and spells may fire from further away. Maximum Chebyshev
2637distance is `rangeTiles` on that item or spell. Distance 0 (same tile) is
2638not a legal ranged/spell attack unless a later exception is defined.
2639
2687
2640The attacker must still occupy a simulating chunk and satisfy any later
2688## 26.4 Ranged attacks, spells and LOS
2641line-of-sight rule. Exact obstruction rules are an open content decision;
2642range itself is not.
2643
2689
2644## 26.5 Hit roll
2690Maximum Chebyshev distance is `rangeTiles`. Distance 0 is not legal unless a
2645
2691later exception is defined. Ranged and magic require line of sight: a ray
2646Whether the attack lands is a server-side roll driven by the **hit skill**
2692through tile centres fails if it crosses an impassable block (same rule as
2647of the current profile (Swordfighting, Axefighting, Archery, Magic, Unarmed,
2693baked lighting).
2648and so on). The client does not roll.
2649
2650The exact hit curve, any defender contribution from Defence, and the RNG
2651are later tuning. The invariant is that the hit chance is a function of the
2652attacker's hit-skill level, not of Strength, Dexterity or Mind.
2653
2654A miss deals no damage.
2655
2656## 26.6 Damage
2657
2658On a hit, damage is determined by the **damage skill**:
2659
2660- Melee → Strength
2661- Ranged → Dexterity
2662- Magic → Mind
2663
2664Weapon or spell base damage and the defender's mitigation (including whether
2665Defence reduces damage) are later tuning. The governing damage skill is not.
2666
2667## 26.7 Experience split
2668
2669When a **player** successfully hits, the attack's XP award is split equally
2670between the hit skill and the damage skill:
2671
2672```text
2673totalXp = attack xp formula for this successful hit
2674hitSkill += totalXp / 2
2675damageSkill += totalXp / 2
2676```
2677
2694
2678Example: a sword hit awards half its XP to Swordfighting and half to
2695## 26.4b Presentation: swipe, projectiles, dynamic lights
2679Strength. A bow hit splits Archery and Dexterity. A spell hit splits Magic
2680and Mind.
2681
2696
2682If an unusual profile ever named the same skill twice, XP is awarded once,
2697- **Melee:** clients draw a swipe sprite for ~0.5s between attacker and
2683not doubled. Misses award no combat XP. Ordinary mobs do not earn XP; their
2698 defender, rotated toward the defender, on `COMBAT_SWING`.
2684`Skills` component is filled from the mob archetype and stays at those
2699- **Ranged / spell:** straight-line world-space projectiles (not grid steps)
2685levels.
2700 toward the defender tile or a miss tile beside it. Spell projectiles may
2701 use a `-bloom` companion.
2702- **Dynamic lights (client-only):** short flashes on cast/hit; equipment with
2703 `lightRadiusTiles` (e.g. lantern) as a moving point light. Per-tile shade
2704 blends `max(bakedNightShade, dynamicContribution)`.
2686
2705
2687Non-combat actions remain single-skill as in section 27.4.
2706## 26.5–26.8 Hit, damage, XP, mob stats
2688
2707
2689## 26.8 Mob combat stats
2708Hit chance uses the profile's hit skill (server RNG). Damage uses Strength
2709(melee), Dexterity (ranged), or Mind (magic). Player hit XP splits equally
2710between hit and damage skills. Mobs use archetype skill levels and do not
2711earn XP.
2690
2712
2691```text
2713```text
2692MobDefinition
2714MobDefinition
2693- ...
2715- hostile / talkable / untargetable / freeFlight / flying
2694- skillLevels: { skillId → level }
2716- skillLevels, defaultAttack
2695- defaultAttack: attackId | unarmed
2717- Combat omitted when untargetable or peaceful non-fighter
2696```
2718```
2697
2719
2698A wolf might have Unarmed and Strength. An archer guard might have Archery
2720Courier **pigeons** use free-flight: straight-line world motion between
2699and Dexterity. Those levels feed the same hit and damage resolution as
2721delivery endpoints, no pathfinding, not bound to the navigation grid, and
2700players.
2722untargetable for all attacks and spells. They are not ambient fauna.
2701
2723
2702# 27. Player-driven economy and skill progression
2724# 27. Player-driven economy and skill progression
2703
2725
@@ -3443,8 +3465,8 @@ CourierService → pigeons carrying money or one item stack through durable tran
3443BankService → shared unlimited vaults, cheque reservations and redemption
3465BankService → shared unlimited vaults, cheque reservations and redemption
3444MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3466MarketService → durable escrowed order book, matching, last-sale index and pigeon-to-bank settlement
3445Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3467Shop NPCs → sell allowed stock; price lerps toward last player-market sale over shopPriceLerpDuration, times a hidden discount
3446Combat → 8-tile melee, item/spell ranged range; hit skill roll; Strength / Dexterity / Mind damage; equal XP split
3468Combat → melee auto-attack + retaliate; 8-neighbour melee; ranged/spell later; courier pigeon free-flight untargetable
3447Skills → classless progression; non-combat XP to one skill; attack XP split hit/damage
3469Skills → classless progression; Clubfighting/Strength on stick; attack XP split hit/damage (curves later)
3448
3470
3449
3471
3450# 34. Version history
3472# 34. Version history