BlueGit

timfa questward

Add the play client with player camera, movement lerp, and night shade.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
7dc40a482eab573b3ef3b740fe245d0f18f6fd52
Parent
ef410fa0
6 files changed +615 −15
client/index.html added +38 −0
@@ -0,0 +1,38 @@
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Tile MMO</title>
6 <link rel="stylesheet" href="/ui/play.css">
7 </head>
8 <body>
9 <div id="hud" hidden>
10 <span id="you"></span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="leave" type="button">Leave world</button>
14 </div>
15 <div id="overlay">
16 <section class="panel">
17 <h1>Tile MMO</h1>
18 <p id="status">Connecting…</p>
19 <p id="error" class="error"></p>
20 <form id="create-form">
21 <label>First name <input id="first-name" required></label>
22 <label>Last name <input id="last-name" required></label>
23 <label>Sex
24 <select id="sex">
25 <option value="male">Male</option>
26 <option value="female">Female</option>
27 </select>
28 </label>
29 <button type="submit">Create character</button>
30 </form>
31 <div id="character-list"></div>
32 <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
33 </section>
34 </div>
35 <script src="/framework/framework.js"></script>
36 <script type="module" src="/src/play/main.js"></script>
37 </body>
38 </html>
@@ -0,0 +1,38 @@
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="utf-8">
5 <title>Tile MMO</title>
6 <link rel="stylesheet" href="/ui/play.css">
7</head>
8<body>
9 <div id="hud" hidden>
10 <span id="you"></span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="leave" type="button">Leave world</button>
14 </div>
15 <div id="overlay">
16 <section class="panel">
17 <h1>Tile MMO</h1>
18 <p id="status">Connecting…</p>
19 <p id="error" class="error"></p>
20 <form id="create-form">
21 <label>First name <input id="first-name" required></label>
22 <label>Last name <input id="last-name" required></label>
23 <label>Sex
24 <select id="sex">
25 <option value="male">Male</option>
26 <option value="female">Female</option>
27 </select>
28 </label>
29 <button type="submit">Create character</button>
30 </form>
31 <div id="character-list"></div>
32 <p class="hint">Open chunk 0,0 in the <a href="/editor">world editor</a>, save, then Apply now before walking.</p>
33 </section>
34 </div>
35 <script src="/framework/framework.js"></script>
36 <script type="module" src="/src/play/main.js"></script>
37</body>
38</html>
client/src/net/socket.js added +34 −0
@@ -0,0 +1,34 @@
1 export class GameSocket
2 {
3 constructor (url, onMessage)
4 {
5 this.url = url;
6 this.onMessage = onMessage;
7 this.socket = null;
8 }
9
10 connect ()
11 {
12 this.socket = new WebSocket(this.url);
13 this.socket.addEventListener("message", (event) =>
14 {
15 this.onMessage(JSON.parse(event.data));
16 });
17 return new Promise((resolve, reject) =>
18 {
19 this.socket.addEventListener("open", resolve, { once: true });
20 this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });
21 });
22 }
23
24 send (payload)
25 {
26 this.socket.send(JSON.stringify(payload));
27 }
28 }
29
30 export function defaultSocketUrl ()
31 {
32 const protocol = location.protocol === "https:" ? "wss:" : "ws:";
33 return `${protocol}//${location.host}/ws`;
34 }
@@ -0,0 +1,34 @@
1export class GameSocket
2{
3 constructor (url, onMessage)
4 {
5 this.url = url;
6 this.onMessage = onMessage;
7 this.socket = null;
8 }
9
10 connect ()
11 {
12 this.socket = new WebSocket(this.url);
13 this.socket.addEventListener("message", (event) =>
14 {
15 this.onMessage(JSON.parse(event.data));
16 });
17 return new Promise((resolve, reject) =>
18 {
19 this.socket.addEventListener("open", resolve, { once: true });
20 this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });
21 });
22 }
23
24 send (payload)
25 {
26 this.socket.send(JSON.stringify(payload));
27 }
28}
29
30export function defaultSocketUrl ()
31{
32 const protocol = location.protocol === "https:" ? "wss:" : "ws:";
33 return `${protocol}//${location.host}/ws`;
34}
client/src/play/main.js added +178 −0
@@ -0,0 +1,178 @@
1 import { MessageType, GAIT } from "/shared/protocol/constants.js";
2 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3 import { PLAY_IMAGES, assertSpriteSizes, useNearestNeighbour } from "../render/sprites.js";
4 import { WorldView } from "../render/worldView.js";
5
6 const game = new Game();
7 const hud = document.getElementById("hud");
8 const overlay = document.getElementById("overlay");
9 const statusEl = document.getElementById("status");
10 const characterList = document.getElementById("character-list");
11 const errorEl = document.getElementById("error");
12
13 let socket;
14 let session = null;
15 let playing = false;
16 let view = null;
17 let scene = null;
18 let gait = GAIT.walk;
19
20 function showError (message)
21 {
22 errorEl.textContent = message ?? "";
23 }
24
25 function renderCharacters (characters)
26 {
27 characterList.innerHTML = "";
28 for (const character of characters)
29 {
30 const row = document.createElement("div");
31 row.className = "character-row";
32 const pending = character.deletionScheduledAt
33 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
34 : "";
35 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
36 const play = document.createElement("button");
37 play.textContent = "Play";
38 play.disabled = !!character.deletionScheduledAt;
39 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
40 const del = document.createElement("button");
41 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
42 del.addEventListener("click", () =>
43 {
44 socket.send({
45 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
46 characterId: character.characterId
47 });
48 });
49 row.append(play, del);
50 characterList.append(row);
51 }
52 }
53
54 function startPlay (payload)
55 {
56 playing = true;
57 overlay.hidden = true;
58 hud.hidden = false;
59 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
60 gait = payload.gait ?? GAIT.walk;
61 document.getElementById("gait").textContent = gait;
62 if (!scene)
63 {
64 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
65 game.loadScene(scene);
66 useNearestNeighbour(scene, game.images);
67 view = new WorldView(game, scene);
68 const ticker = new GameObject(0, 0, null, 10);
69 ticker.update = (dt) =>
70 {
71 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing)
72 {
73 const tile = view.screenToTile(GameInput.mousePosition.x, GameInput.mousePosition.y);
74 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
75 }
76 if (GameInput.isPressed(82))
77 {
78 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
79 socket.send({ type: MessageType.setGait, gait });
80 document.getElementById("gait").textContent = gait;
81 }
82 view.update(dt);
83 };
84 scene.addObject(ticker);
85 window.addEventListener("resize", () =>
86 {
87 scene.size.x = window.innerWidth;
88 scene.size.y = window.innerHeight;
89 scene.g_fixSize();
90 });
91 window.addEventListener("wheel", (event) =>
92 {
93 if (!playing)
94 { return; }
95 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
96 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
97 }, { passive: true });
98 }
99 view.settings = payload.settings ?? view.settings;
100 view.worldHour = payload.worldTime?.hour ?? 12;
101 view.setLocalEntity(payload.entityId, payload.tileX, payload.tileY, payload.gait, payload.sex);
102 }
103
104 async function main ()
105 {
106 await game.preloadImages(PLAY_IMAGES);
107 assertSpriteSizes(game.images);
108 game.startGame();
109
110 socket = new GameSocket(defaultSocketUrl(), (message) =>
111 {
112 switch (message.type)
113 {
114 case MessageType.session:
115 session = message;
116 statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
117 renderCharacters(message.characters);
118 break;
119 case MessageType.characterList:
120 renderCharacters(message.characters);
121 if (!playing)
122 { overlay.hidden = false; }
123 break;
124 case MessageType.enterWorld:
125 startPlay(message);
126 break;
127 case MessageType.chunkSnapshot:
128 view?.applySnapshot(message);
129 break;
130 case MessageType.unsubscribeChunk:
131 view?.removeChunk(message.chunkX, message.chunkY);
132 break;
133 case MessageType.entityMove:
134 view?.moveEntity(message);
135 break;
136 case MessageType.entityDespawn:
137 view?.despawnEntity(message.entityId);
138 break;
139 case MessageType.worldStatus:
140 if (view)
141 {
142 view.settings = message.settings ?? view.settings;
143 view.worldHour = message.worldTime?.hour ?? view.worldHour;
144 }
145 break;
146 case MessageType.error:
147 showError(message.message);
148 break;
149 }
150 });
151 await socket.connect();
152 }
153
154 document.getElementById("create-form").addEventListener("submit", (event) =>
155 {
156 event.preventDefault();
157 showError("");
158 socket.send({
159 type: MessageType.createCharacter,
160 firstName: document.getElementById("first-name").value,
161 lastName: document.getElementById("last-name").value,
162 sex: document.getElementById("sex").value
163 });
164 });
165
166 document.getElementById("leave").addEventListener("click", () =>
167 {
168 socket.send({ type: MessageType.leaveWorld });
169 playing = false;
170 overlay.hidden = false;
171 hud.hidden = true;
172 });
173
174 main().catch((error) =>
175 {
176 showError(error.message);
177 console.error(error);
178 });
@@ -0,0 +1,178 @@
1import { MessageType, GAIT } from "/shared/protocol/constants.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { PLAY_IMAGES, assertSpriteSizes, useNearestNeighbour } from "../render/sprites.js";
4import { WorldView } from "../render/worldView.js";
5
6const game = new Game();
7const hud = document.getElementById("hud");
8const overlay = document.getElementById("overlay");
9const statusEl = document.getElementById("status");
10const characterList = document.getElementById("character-list");
11const errorEl = document.getElementById("error");
12
13let socket;
14let session = null;
15let playing = false;
16let view = null;
17let scene = null;
18let gait = GAIT.walk;
19
20function showError (message)
21{
22 errorEl.textContent = message ?? "";
23}
24
25function renderCharacters (characters)
26{
27 characterList.innerHTML = "";
28 for (const character of characters)
29 {
30 const row = document.createElement("div");
31 row.className = "character-row";
32 const pending = character.deletionScheduledAt
33 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
34 : "";
35 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
36 const play = document.createElement("button");
37 play.textContent = "Play";
38 play.disabled = !!character.deletionScheduledAt;
39 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
40 const del = document.createElement("button");
41 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
42 del.addEventListener("click", () =>
43 {
44 socket.send({
45 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
46 characterId: character.characterId
47 });
48 });
49 row.append(play, del);
50 characterList.append(row);
51 }
52}
53
54function startPlay (payload)
55{
56 playing = true;
57 overlay.hidden = true;
58 hud.hidden = false;
59 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
60 gait = payload.gait ?? GAIT.walk;
61 document.getElementById("gait").textContent = gait;
62 if (!scene)
63 {
64 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
65 game.loadScene(scene);
66 useNearestNeighbour(scene, game.images);
67 view = new WorldView(game, scene);
68 const ticker = new GameObject(0, 0, null, 10);
69 ticker.update = (dt) =>
70 {
71 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing)
72 {
73 const tile = view.screenToTile(GameInput.mousePosition.x, GameInput.mousePosition.y);
74 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
75 }
76 if (GameInput.isPressed(82))
77 {
78 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
79 socket.send({ type: MessageType.setGait, gait });
80 document.getElementById("gait").textContent = gait;
81 }
82 view.update(dt);
83 };
84 scene.addObject(ticker);
85 window.addEventListener("resize", () =>
86 {
87 scene.size.x = window.innerWidth;
88 scene.size.y = window.innerHeight;
89 scene.g_fixSize();
90 });
91 window.addEventListener("wheel", (event) =>
92 {
93 if (!playing)
94 { return; }
95 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
96 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
97 }, { passive: true });
98 }
99 view.settings = payload.settings ?? view.settings;
100 view.worldHour = payload.worldTime?.hour ?? 12;
101 view.setLocalEntity(payload.entityId, payload.tileX, payload.tileY, payload.gait, payload.sex);
102}
103
104async function main ()
105{
106 await game.preloadImages(PLAY_IMAGES);
107 assertSpriteSizes(game.images);
108 game.startGame();
109
110 socket = new GameSocket(defaultSocketUrl(), (message) =>
111 {
112 switch (message.type)
113 {
114 case MessageType.session:
115 session = message;
116 statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
117 renderCharacters(message.characters);
118 break;
119 case MessageType.characterList:
120 renderCharacters(message.characters);
121 if (!playing)
122 { overlay.hidden = false; }
123 break;
124 case MessageType.enterWorld:
125 startPlay(message);
126 break;
127 case MessageType.chunkSnapshot:
128 view?.applySnapshot(message);
129 break;
130 case MessageType.unsubscribeChunk:
131 view?.removeChunk(message.chunkX, message.chunkY);
132 break;
133 case MessageType.entityMove:
134 view?.moveEntity(message);
135 break;
136 case MessageType.entityDespawn:
137 view?.despawnEntity(message.entityId);
138 break;
139 case MessageType.worldStatus:
140 if (view)
141 {
142 view.settings = message.settings ?? view.settings;
143 view.worldHour = message.worldTime?.hour ?? view.worldHour;
144 }
145 break;
146 case MessageType.error:
147 showError(message.message);
148 break;
149 }
150 });
151 await socket.connect();
152}
153
154document.getElementById("create-form").addEventListener("submit", (event) =>
155{
156 event.preventDefault();
157 showError("");
158 socket.send({
159 type: MessageType.createCharacter,
160 firstName: document.getElementById("first-name").value,
161 lastName: document.getElementById("last-name").value,
162 sex: document.getElementById("sex").value
163 });
164});
165
166document.getElementById("leave").addEventListener("click", () =>
167{
168 socket.send({ type: MessageType.leaveWorld });
169 playing = false;
170 overlay.hidden = false;
171 hud.hidden = true;
172});
173
174main().catch((error) =>
175{
176 showError(error.message);
177 console.error(error);
178});
client/src/render/worldView.js added +282 −0
@@ -0,0 +1,282 @@
1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
3
4 export class WorldView
5 {
6 constructor (game, scene)
7 {
8 this.game = game;
9 this.scene = scene;
10 this.zoom = 2;
11 this.chunks = new Map();
12 this.tiles = new Map();
13 this.entities = new Map();
14 this.localEntityId = null;
15 this.settings = { walkTilesPerSecond: 2 };
16 this.worldHour = 12;
17 this.nightPreview = null;
18 this.followPlayer = true;
19 }
20
21 setLocalEntity (entityId, tileX, tileY, gait, sex)
22 {
23 this.localEntityId = entityId;
24 this.#upsertEntity({
25 entityId,
26 tileX,
27 tileY,
28 gait,
29 sex,
30 firstName: "",
31 lastName: ""
32 });
33 }
34
35 applySnapshot (snapshot)
36 {
37 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
38 this.chunks.set(key, snapshot);
39 this.#rebuildChunk(snapshot);
40 for (const entity of snapshot.entities)
41 { this.#upsertEntity(entity); }
42 }
43
44 removeChunk (chunkX, chunkY)
45 {
46 const key = `${chunkX},${chunkY}`;
47 this.chunks.delete(key);
48 for (const [tileKey, objects] of [...this.tiles.entries()])
49 {
50 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
51 {
52 objects.ground?.destroy();
53 objects.block?.destroy();
54 objects.shade?.destroy();
55 this.tiles.delete(tileKey);
56 }
57 }
58 }
59
60 moveEntity (payload)
61 {
62 const existing = this.entities.get(payload.entityId);
63 if (!existing)
64 {
65 this.#upsertEntity({
66 entityId: payload.entityId,
67 tileX: payload.tileX,
68 tileY: payload.tileY,
69 gait: payload.gait,
70 sex: "male"
71 });
72 return;
73 }
74 existing.fromX = existing.visualX;
75 existing.fromY = existing.visualY;
76 existing.tileX = payload.tileX;
77 existing.tileY = payload.tileY;
78 existing.gait = payload.gait;
79 existing.lerpStarted = performance.now();
80 existing.lerpMs = this.#lerpMs(payload.gait);
81 }
82
83 despawnEntity (entityId)
84 {
85 const existing = this.entities.get(entityId);
86 if (!existing)
87 { return; }
88 existing.object?.destroy();
89 this.entities.delete(entityId);
90 }
91
92 setZoom (zoom)
93 {
94 this.zoom = Math.min(4, Math.max(1, zoom));
95 for (const snapshot of this.chunks.values())
96 { this.#rebuildChunk(snapshot); }
97 const size = this.tileSize();
98 for (const entity of this.entities.values())
99 {
100 entity.visualX = entity.tileX * size + size / 2;
101 entity.visualY = entity.tileY * size + size / 2;
102 entity.fromX = entity.visualX;
103 entity.fromY = entity.visualY;
104 entity.lerpStarted = null;
105 if (entity.object)
106 { entity.object.transform.size = new vector(size, size); }
107 }
108 }
109
110 tileSize ()
111 {
112 return SPRITE_SIZE_PX * this.zoom;
113 }
114
115 screenToTile (mouseX, mouseY)
116 {
117 const size = this.tileSize();
118 const worldX = mouseX - this.scene.cameraPosition.x;
119 const worldY = mouseY - this.scene.cameraPosition.y;
120 return {
121 tileX: Math.floor(worldX / size),
122 tileY: Math.floor(worldY / size)
123 };
124 }
125
126 update (deltaTime)
127 {
128 const now = performance.now();
129 const size = this.tileSize();
130 for (const entity of this.entities.values())
131 {
132 const targetX = entity.tileX * size + size / 2;
133 const targetY = entity.tileY * size + size / 2;
134 if (entity.lerpStarted != null)
135 {
136 const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs);
137 entity.visualX = entity.fromX + (targetX - entity.fromX) * t;
138 entity.visualY = entity.fromY + (targetY - entity.fromY) * t;
139 if (t >= 1)
140 { entity.lerpStarted = null; }
141 }
142 else
143 {
144 entity.visualX = targetX;
145 entity.visualY = targetY;
146 }
147 if (entity.object)
148 {
149 entity.object.transform.position.x = entity.visualX;
150 entity.object.transform.position.y = entity.visualY;
151 entity.object.transform.size = new vector(size, size);
152 }
153 }
154
155 this.#centerCamera();
156 this.#updateShade(deltaTime);
157 }
158
159 #lerpMs (gait)
160 {
161 const walk = this.settings.walkTilesPerSecond || 2;
162 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
163 return seconds * 1000;
164 }
165
166 #centerCamera ()
167 {
168 if (!this.followPlayer)
169 { return; }
170 const local = this.entities.get(this.localEntityId);
171 if (!local)
172 { return; }
173 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
174 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
175 }
176
177 #upsertEntity (payload)
178 {
179 const size = this.tileSize();
180 let entity = this.entities.get(payload.entityId);
181 if (!entity)
182 {
183 const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male";
184 const object = new GameObject(0, 0, this.game.images[spriteName], 2);
185 this.scene.addObject(object);
186 entity = { object, visualX: 0, visualY: 0 };
187 this.entities.set(payload.entityId, entity);
188 }
189 entity.tileX = payload.tileX;
190 entity.tileY = payload.tileY;
191 entity.gait = payload.gait;
192 entity.sex = payload.sex;
193 entity.visualX = payload.tileX * size + size / 2;
194 entity.visualY = payload.tileY * size + size / 2;
195 entity.fromX = entity.visualX;
196 entity.fromY = entity.visualY;
197 entity.object.transform.position.x = entity.visualX;
198 entity.object.transform.position.y = entity.visualY;
199 entity.object.transform.size = new vector(size, size);
200 }
201
202 #rebuildChunk (snapshot)
203 {
204 const size = this.tileSize();
205 for (let localY = 0; localY < CHUNK_SIZE; localY++)
206 {
207 for (let localX = 0; localX < CHUNK_SIZE; localX++)
208 {
209 const index = localY * CHUNK_SIZE + localX;
210 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
211 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
212 const key = `${tileX},${tileY}`;
213 let objects = this.tiles.get(key);
214 if (!objects)
215 {
216 objects = { chunkX: snapshot.chunkX, chunkY: snapshot.chunkY };
217 this.tiles.set(key, objects);
218 }
219 const px = tileX * size + size / 2;
220 const py = tileY * size + size / 2;
221 const groundName = GROUND_DEFINITIONS[snapshot.grounds[index]]?.sprite ?? "ground-grass";
222 objects.ground = this.#sprite(objects.ground, groundName, px, py, 0, size);
223 const block = snapshot.blocks[index];
224 const blockName = block ? BLOCK_DEFINITIONS[block.typeId]?.sprite : null;
225 if (blockName)
226 { objects.block = this.#sprite(objects.block, blockName, px, py, 1, size); }
227 else if (objects.block)
228 {
229 objects.block.destroy();
230 objects.block = null;
231 }
232 objects.light = snapshot.light[index] ?? 0;
233 objects.shade = this.#sprite(objects.shade, "night-shade", px, py, 3, size);
234 objects.shade.renderer.alpha = 0;
235 }
236 }
237 }
238
239 #sprite (existing, name, x, y, layer, size)
240 {
241 if (!existing || existing.renderer.sprite !== this.game.images[name])
242 {
243 existing?.destroy();
244 existing = new GameObject(x, y, this.game.images[name], layer);
245 this.scene.addObject(existing);
246 }
247 existing.transform.position.x = x;
248 existing.transform.position.y = y;
249 existing.transform.size = new vector(size, size);
250 existing.layer = layer;
251 return existing;
252 }
253
254 #updateShade ()
255 {
256 const hour = this.nightPreview ?? this.worldHour;
257 const ambientDark = nightFactor(hour);
258 for (const objects of this.tiles.values())
259 {
260 if (!objects.shade)
261 { continue; }
262 const lit = (objects.light ?? 0) > 0;
263 objects.shade.renderer.alpha = lit ? ambientDark * 0.12 : ambientDark;
264 }
265 }
266 }
267
268 export function nightFactor (hour)
269 {
270 if (hour >= 8 && hour <= 16)
271 { return 0; }
272 if (hour >= 22 || hour <= 5)
273 { return 0.72; }
274 if (hour < 8)
275 { return lerp(0.72, 0, (hour - 5) / 3); }
276 return lerp(0, 0.72, (hour - 16) / 6);
277 }
278
279 function lerp (a, b, t)
280 {
281 return a + (b - a) * Math.min(1, Math.max(0, t));
282 }
@@ -0,0 +1,282 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
3
4export class WorldView
5{
6 constructor (game, scene)
7 {
8 this.game = game;
9 this.scene = scene;
10 this.zoom = 2;
11 this.chunks = new Map();
12 this.tiles = new Map();
13 this.entities = new Map();
14 this.localEntityId = null;
15 this.settings = { walkTilesPerSecond: 2 };
16 this.worldHour = 12;
17 this.nightPreview = null;
18 this.followPlayer = true;
19 }
20
21 setLocalEntity (entityId, tileX, tileY, gait, sex)
22 {
23 this.localEntityId = entityId;
24 this.#upsertEntity({
25 entityId,
26 tileX,
27 tileY,
28 gait,
29 sex,
30 firstName: "",
31 lastName: ""
32 });
33 }
34
35 applySnapshot (snapshot)
36 {
37 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
38 this.chunks.set(key, snapshot);
39 this.#rebuildChunk(snapshot);
40 for (const entity of snapshot.entities)
41 { this.#upsertEntity(entity); }
42 }
43
44 removeChunk (chunkX, chunkY)
45 {
46 const key = `${chunkX},${chunkY}`;
47 this.chunks.delete(key);
48 for (const [tileKey, objects] of [...this.tiles.entries()])
49 {
50 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
51 {
52 objects.ground?.destroy();
53 objects.block?.destroy();
54 objects.shade?.destroy();
55 this.tiles.delete(tileKey);
56 }
57 }
58 }
59
60 moveEntity (payload)
61 {
62 const existing = this.entities.get(payload.entityId);
63 if (!existing)
64 {
65 this.#upsertEntity({
66 entityId: payload.entityId,
67 tileX: payload.tileX,
68 tileY: payload.tileY,
69 gait: payload.gait,
70 sex: "male"
71 });
72 return;
73 }
74 existing.fromX = existing.visualX;
75 existing.fromY = existing.visualY;
76 existing.tileX = payload.tileX;
77 existing.tileY = payload.tileY;
78 existing.gait = payload.gait;
79 existing.lerpStarted = performance.now();
80 existing.lerpMs = this.#lerpMs(payload.gait);
81 }
82
83 despawnEntity (entityId)
84 {
85 const existing = this.entities.get(entityId);
86 if (!existing)
87 { return; }
88 existing.object?.destroy();
89 this.entities.delete(entityId);
90 }
91
92 setZoom (zoom)
93 {
94 this.zoom = Math.min(4, Math.max(1, zoom));
95 for (const snapshot of this.chunks.values())
96 { this.#rebuildChunk(snapshot); }
97 const size = this.tileSize();
98 for (const entity of this.entities.values())
99 {
100 entity.visualX = entity.tileX * size + size / 2;
101 entity.visualY = entity.tileY * size + size / 2;
102 entity.fromX = entity.visualX;
103 entity.fromY = entity.visualY;
104 entity.lerpStarted = null;
105 if (entity.object)
106 { entity.object.transform.size = new vector(size, size); }
107 }
108 }
109
110 tileSize ()
111 {
112 return SPRITE_SIZE_PX * this.zoom;
113 }
114
115 screenToTile (mouseX, mouseY)
116 {
117 const size = this.tileSize();
118 const worldX = mouseX - this.scene.cameraPosition.x;
119 const worldY = mouseY - this.scene.cameraPosition.y;
120 return {
121 tileX: Math.floor(worldX / size),
122 tileY: Math.floor(worldY / size)
123 };
124 }
125
126 update (deltaTime)
127 {
128 const now = performance.now();
129 const size = this.tileSize();
130 for (const entity of this.entities.values())
131 {
132 const targetX = entity.tileX * size + size / 2;
133 const targetY = entity.tileY * size + size / 2;
134 if (entity.lerpStarted != null)
135 {
136 const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs);
137 entity.visualX = entity.fromX + (targetX - entity.fromX) * t;
138 entity.visualY = entity.fromY + (targetY - entity.fromY) * t;
139 if (t >= 1)
140 { entity.lerpStarted = null; }
141 }
142 else
143 {
144 entity.visualX = targetX;
145 entity.visualY = targetY;
146 }
147 if (entity.object)
148 {
149 entity.object.transform.position.x = entity.visualX;
150 entity.object.transform.position.y = entity.visualY;
151 entity.object.transform.size = new vector(size, size);
152 }
153 }
154
155 this.#centerCamera();
156 this.#updateShade(deltaTime);
157 }
158
159 #lerpMs (gait)
160 {
161 const walk = this.settings.walkTilesPerSecond || 2;
162 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
163 return seconds * 1000;
164 }
165
166 #centerCamera ()
167 {
168 if (!this.followPlayer)
169 { return; }
170 const local = this.entities.get(this.localEntityId);
171 if (!local)
172 { return; }
173 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
174 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
175 }
176
177 #upsertEntity (payload)
178 {
179 const size = this.tileSize();
180 let entity = this.entities.get(payload.entityId);
181 if (!entity)
182 {
183 const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male";
184 const object = new GameObject(0, 0, this.game.images[spriteName], 2);
185 this.scene.addObject(object);
186 entity = { object, visualX: 0, visualY: 0 };
187 this.entities.set(payload.entityId, entity);
188 }
189 entity.tileX = payload.tileX;
190 entity.tileY = payload.tileY;
191 entity.gait = payload.gait;
192 entity.sex = payload.sex;
193 entity.visualX = payload.tileX * size + size / 2;
194 entity.visualY = payload.tileY * size + size / 2;
195 entity.fromX = entity.visualX;
196 entity.fromY = entity.visualY;
197 entity.object.transform.position.x = entity.visualX;
198 entity.object.transform.position.y = entity.visualY;
199 entity.object.transform.size = new vector(size, size);
200 }
201
202 #rebuildChunk (snapshot)
203 {
204 const size = this.tileSize();
205 for (let localY = 0; localY < CHUNK_SIZE; localY++)
206 {
207 for (let localX = 0; localX < CHUNK_SIZE; localX++)
208 {
209 const index = localY * CHUNK_SIZE + localX;
210 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
211 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
212 const key = `${tileX},${tileY}`;
213 let objects = this.tiles.get(key);
214 if (!objects)
215 {
216 objects = { chunkX: snapshot.chunkX, chunkY: snapshot.chunkY };
217 this.tiles.set(key, objects);
218 }
219 const px = tileX * size + size / 2;
220 const py = tileY * size + size / 2;
221 const groundName = GROUND_DEFINITIONS[snapshot.grounds[index]]?.sprite ?? "ground-grass";
222 objects.ground = this.#sprite(objects.ground, groundName, px, py, 0, size);
223 const block = snapshot.blocks[index];
224 const blockName = block ? BLOCK_DEFINITIONS[block.typeId]?.sprite : null;
225 if (blockName)
226 { objects.block = this.#sprite(objects.block, blockName, px, py, 1, size); }
227 else if (objects.block)
228 {
229 objects.block.destroy();
230 objects.block = null;
231 }
232 objects.light = snapshot.light[index] ?? 0;
233 objects.shade = this.#sprite(objects.shade, "night-shade", px, py, 3, size);
234 objects.shade.renderer.alpha = 0;
235 }
236 }
237 }
238
239 #sprite (existing, name, x, y, layer, size)
240 {
241 if (!existing || existing.renderer.sprite !== this.game.images[name])
242 {
243 existing?.destroy();
244 existing = new GameObject(x, y, this.game.images[name], layer);
245 this.scene.addObject(existing);
246 }
247 existing.transform.position.x = x;
248 existing.transform.position.y = y;
249 existing.transform.size = new vector(size, size);
250 existing.layer = layer;
251 return existing;
252 }
253
254 #updateShade ()
255 {
256 const hour = this.nightPreview ?? this.worldHour;
257 const ambientDark = nightFactor(hour);
258 for (const objects of this.tiles.values())
259 {
260 if (!objects.shade)
261 { continue; }
262 const lit = (objects.light ?? 0) > 0;
263 objects.shade.renderer.alpha = lit ? ambientDark * 0.12 : ambientDark;
264 }
265 }
266}
267
268export function nightFactor (hour)
269{
270 if (hour >= 8 && hour <= 16)
271 { return 0; }
272 if (hour >= 22 || hour <= 5)
273 { return 0.72; }
274 if (hour < 8)
275 { return lerp(0.72, 0, (hour - 5) / 3); }
276 return lerp(0, 0.72, (hour - 16) / 6);
277}
278
279function lerp (a, b, t)
280{
281 return a + (b - a) * Math.min(1, Math.max(0, t));
282}
client/ui/play.css added +68 −0
@@ -0,0 +1,68 @@
1 :root {
2 color-scheme: dark;
3 font-family: "Segoe UI", sans-serif;
4 background: #101216;
5 color: #e8e4d9;
6 }
7
8 html, body {
9 margin: 0;
10 height: 100%;
11 overflow: hidden;
12 }
13
14 #hud {
15 position: fixed;
16 z-index: 2;
17 top: 0;
18 left: 0;
19 right: 0;
20 display: flex;
21 gap: 1.25rem;
22 align-items: center;
23 padding: 0.5rem 0.75rem;
24 background: rgba(12, 14, 18, 0.82);
25 }
26
27 #overlay {
28 position: fixed;
29 inset: 0;
30 z-index: 3;
31 display: grid;
32 place-items: center;
33 background: #101216;
34 }
35
36 #overlay[hidden], #hud[hidden] {
37 display: none !important;
38 }
39
40 .panel {
41 width: min(420px, 92vw);
42 background: #1a1e26;
43 border: 1px solid #2c3340;
44 padding: 1.25rem;
45 }
46
47 label, .character-row {
48 display: flex;
49 gap: 0.5rem;
50 align-items: center;
51 margin: 0.5rem 0;
52 }
53
54 input, select, button {
55 font: inherit;
56 background: #101216;
57 color: inherit;
58 border: 1px solid #3a4250;
59 padding: 0.3rem 0.5rem;
60 }
61
62 button {
63 cursor: pointer;
64 }
65
66 .error { color: #f0a0a0; min-height: 1.2em; }
67 .hint { color: #9aa3b2; font-size: 0.9rem; }
68 a { color: #d4c48a; }
@@ -0,0 +1,68 @@
1:root {
2 color-scheme: dark;
3 font-family: "Segoe UI", sans-serif;
4 background: #101216;
5 color: #e8e4d9;
6}
7
8html, body {
9 margin: 0;
10 height: 100%;
11 overflow: hidden;
12}
13
14#hud {
15 position: fixed;
16 z-index: 2;
17 top: 0;
18 left: 0;
19 right: 0;
20 display: flex;
21 gap: 1.25rem;
22 align-items: center;
23 padding: 0.5rem 0.75rem;
24 background: rgba(12, 14, 18, 0.82);
25}
26
27#overlay {
28 position: fixed;
29 inset: 0;
30 z-index: 3;
31 display: grid;
32 place-items: center;
33 background: #101216;
34}
35
36#overlay[hidden], #hud[hidden] {
37 display: none !important;
38}
39
40.panel {
41 width: min(420px, 92vw);
42 background: #1a1e26;
43 border: 1px solid #2c3340;
44 padding: 1.25rem;
45}
46
47label, .character-row {
48 display: flex;
49 gap: 0.5rem;
50 align-items: center;
51 margin: 0.5rem 0;
52}
53
54input, select, button {
55 font: inherit;
56 background: #101216;
57 color: inherit;
58 border: 1px solid #3a4250;
59 padding: 0.3rem 0.5rem;
60}
61
62button {
63 cursor: pointer;
64}
65
66.error { color: #f0a0a0; min-height: 1.2em; }
67.hint { color: #9aa3b2; font-size: 0.9rem; }
68a { color: #d4c48a; }
docs/FEATURES.md +15 −15
@@ -123,9 +123,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
123 123
124 124 ## Client movement interpolation
125 125
126 **Status:** not implemented
127 **Spec:** Client lerps sprites between replicated tiles over the walk or run interval.
128 **Code:** —
126 **Status:** full
127 **Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
128 **Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
129
130 ## Play viewport and camera
131
132 **Status:** full
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility.
134 **Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
135
136 ## Night shading
137
138 **Status:** full
139 **Spec:** World time is server time minus 1200 years. At night, tiles the baked light map cannot reach are darkened; lit tiles stay brighter.
140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
129 141
130 142 ## FrameworkV3 client bootstrap
131 143
@@ -139,18 +151,6 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
139 151 **Spec:** World sprites must be exactly 16×16. Reject at client load. The unit test walks `client/assets/{grounds,blocks,characters,...}` and fails listing every offender.
140 152 **Code:** `client/src/render/sprites.js` (`assertSpriteSizes`), `client/tests/sprite-size.test.js`, art in `client/assets/`
141 153
142 ## Play viewport and camera
143
144 **Status:** not implemented
145 **Spec:** Camera stays centered on the local player. Zoom is viewport-only and does not change server visibility.
146 **Code:** —
147
148 ## Night shading
149
150 **Status:** not implemented
151 **Spec:** World time is server time minus 1200 years. At night, tiles the baked light map cannot reach are darkened.
152 **Code:** —
153
154 154 ## Region workers and cross-worker transfer
155 155
156 156 **Status:** not implemented
@@ -123,9 +123,21 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
123
123
124## Client movement interpolation
124## Client movement interpolation
125
125
126**Status:** not implemented
126**Status:** full
127**Spec:** Client lerps sprites between replicated tiles over the walk or run interval.
127**Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
128**Code:** —
128**Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
129
130## Play viewport and camera
131
132**Status:** full
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility.
134**Code:** `client/src/render/worldView.js`, `client/src/play/main.js`, `client/index.html`
135
136## Night shading
137
138**Status:** full
139**Spec:** World time is server time minus 1200 years. At night, tiles the baked light map cannot reach are darkened; lit tiles stay brighter.
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
129
141
130## FrameworkV3 client bootstrap
142## FrameworkV3 client bootstrap
131
143
@@ -139,18 +151,6 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
139**Spec:** World sprites must be exactly 16×16. Reject at client load. The unit test walks `client/assets/{grounds,blocks,characters,...}` and fails listing every offender.
151**Spec:** World sprites must be exactly 16×16. Reject at client load. The unit test walks `client/assets/{grounds,blocks,characters,...}` and fails listing every offender.
140**Code:** `client/src/render/sprites.js` (`assertSpriteSizes`), `client/tests/sprite-size.test.js`, art in `client/assets/`
152**Code:** `client/src/render/sprites.js` (`assertSpriteSizes`), `client/tests/sprite-size.test.js`, art in `client/assets/`
141
153
142## Play viewport and camera
143
144**Status:** not implemented
145**Spec:** Camera stays centered on the local player. Zoom is viewport-only and does not change server visibility.
146**Code:** —
147
148## Night shading
149
150**Status:** not implemented
151**Spec:** World time is server time minus 1200 years. At night, tiles the baked light map cannot reach are darkened.
152**Code:** —
153
154## Region workers and cross-worker transfer
154## Region workers and cross-worker transfer
155
155
156**Status:** not implemented
156**Status:** not implemented