| 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 { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 4 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; |
| 5 | |
| 6 | const LAYER_GROUND = 0; |
| 7 | const LAYER_SHADE = 500000; |
| 8 | const LAYER_EDGE = 900000; |
| 9 | const SORT_BLOCK = 1; |
| 10 | const SORT_ENTITY = 2; |
| 11 | |
| 12 | export class WorldView |
| 13 | { |
| 14 | constructor (game, scene, catalog = { grounds: {}, blocks: {} }) |
| 15 | { |
| 16 | this.game = game; |
| 17 | this.scene = scene; |
| 18 | this.catalog = catalog; |
| 19 | this.preview = null; |
| 20 | this.zoom = 2; |
| 21 | this.chunks = new Map(); |
| 22 | this.tiles = new Map(); |
| 23 | this.entities = new Map(); |
| 24 | this.edges = new Map(); |
| 25 | this.localEntityId = null; |
| 26 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 27 | this.worldHour = 12; |
| 28 | this.nightPreview = null; |
| 29 | this.followPlayer = true; |
| 30 | } |
| 31 | |
| 32 | setLocalEntity (entityId, tileX, tileY, gait, sex) |
| 33 | { |
| 34 | this.localEntityId = entityId; |
| 35 | this.#upsertEntity({ |
| 36 | entityId, |
| 37 | tileX, |
| 38 | tileY, |
| 39 | gait, |
| 40 | sex, |
| 41 | firstName: "", |
| 42 | lastName: "" |
| 43 | }); |
| 44 | } |
| 45 | |
| 46 | applySnapshot (snapshot) |
| 47 | { |
| 48 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 49 | this.chunks.set(key, snapshot); |
| 50 | this.#rebuildChunk(snapshot); |
| 51 | this.#redrawPreview(); |
| 52 | for (const entity of snapshot.entities ?? []) |
| 53 | { this.#upsertEntity(entity); } |
| 54 | this.#rebuildAllEdges(); |
| 55 | } |
| 56 | |
| 57 | removeChunk (chunkX, chunkY) |
| 58 | { |
| 59 | const key = `${chunkX},${chunkY}`; |
| 60 | this.chunks.delete(key); |
| 61 | this.#destroyEdges(key); |
| 62 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 63 | { |
| 64 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 65 | { |
| 66 | objects.ground?.destroy(); |
| 67 | objects.block?.destroy(); |
| 68 | objects.shade?.destroy(); |
| 69 | this.tiles.delete(tileKey); |
| 70 | } |
| 71 | } |
| 72 | this.#rebuildAllEdges(); |
| 73 | } |
| 74 | |
| 75 | setChunkOpen (chunkX, chunkY, open) |
| 76 | { |
| 77 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 78 | if (!snapshot) |
| 79 | { return; } |
| 80 | snapshot.open = !!open; |
| 81 | this.#rebuildAllEdges(); |
| 82 | } |
| 83 | |
| 84 | moveEntity (payload) |
| 85 | { |
| 86 | const existing = this.entities.get(payload.entityId); |
| 87 | if (!existing) |
| 88 | { |
| 89 | this.#upsertEntity({ |
| 90 | entityId: payload.entityId, |
| 91 | tileX: payload.tileX, |
| 92 | tileY: payload.tileY, |
| 93 | gait: payload.gait, |
| 94 | sex: "male" |
| 95 | }); |
| 96 | return; |
| 97 | } |
| 98 | existing.fromX = existing.visualX; |
| 99 | existing.fromY = existing.visualY; |
| 100 | existing.tileX = payload.tileX; |
| 101 | existing.tileY = payload.tileY; |
| 102 | existing.gait = payload.gait; |
| 103 | existing.lerpStarted = performance.now(); |
| 104 | existing.lerpMs = this.#lerpMs(payload.gait); |
| 105 | } |
| 106 | |
| 107 | despawnEntity (entityId) |
| 108 | { |
| 109 | const existing = this.entities.get(entityId); |
| 110 | if (!existing) |
| 111 | { return; } |
| 112 | existing.object?.destroy(); |
| 113 | this.entities.delete(entityId); |
| 114 | } |
| 115 | |
| 116 | setZoom (zoom, limits = { min: 1, max: 4 }) |
| 117 | { |
| 118 | const min = limits.min ?? 1; |
| 119 | const max = limits.max ?? 4; |
| 120 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 121 | for (const snapshot of this.chunks.values()) |
| 122 | { this.#rebuildChunk(snapshot); } |
| 123 | const size = this.tileSize(); |
| 124 | for (const entity of this.entities.values()) |
| 125 | { |
| 126 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 127 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 128 | entity.fromX = entity.visualX; |
| 129 | entity.fromY = entity.visualY; |
| 130 | entity.lerpStarted = null; |
| 131 | this.#placeEntity(entity); |
| 132 | } |
| 133 | this.#rebuildAllEdges(); |
| 134 | this.#redrawPreview(); |
| 135 | } |
| 136 | |
| 137 | tileSize () |
| 138 | { |
| 139 | return SPRITE_SIZE_PX * this.zoom; |
| 140 | } |
| 141 | |
| 142 | screenToTile (mouseX, mouseY) |
| 143 | { |
| 144 | const size = this.tileSize(); |
| 145 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 146 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 147 | return { |
| 148 | tileX: Math.floor(worldX / size), |
| 149 | tileY: Math.floor(worldY / size) |
| 150 | }; |
| 151 | } |
| 152 | |
| 153 | update (deltaTime) |
| 154 | { |
| 155 | const now = performance.now(); |
| 156 | const size = this.tileSize(); |
| 157 | for (const entity of this.entities.values()) |
| 158 | { |
| 159 | const target = tilePivot(entity.tileX, entity.tileY, size); |
| 160 | if (entity.lerpStarted != null) |
| 161 | { |
| 162 | const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs); |
| 163 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 164 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 165 | if (t >= 1) |
| 166 | { entity.lerpStarted = null; } |
| 167 | } |
| 168 | else |
| 169 | { |
| 170 | entity.visualX = target.x; |
| 171 | entity.visualY = target.y; |
| 172 | } |
| 173 | this.#placeEntity(entity); |
| 174 | } |
| 175 | |
| 176 | this.#centerCamera(); |
| 177 | this.#updateShade(deltaTime); |
| 178 | } |
| 179 | |
| 180 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 181 | { |
| 182 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 183 | if (!snapshot) |
| 184 | { return; } |
| 185 | const index = localY * CHUNK_SIZE + localX; |
| 186 | if (ground !== undefined) |
| 187 | { snapshot.grounds[index] = ground; } |
| 188 | if (block !== undefined) |
| 189 | { snapshot.blocks[index] = block; } |
| 190 | if (light !== undefined) |
| 191 | { snapshot.light[index] = light; } |
| 192 | this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY); |
| 193 | } |
| 194 | |
| 195 | setTilePreview (tileX, tileY, override) |
| 196 | { |
| 197 | const previous = this.preview; |
| 198 | this.preview = { tileX, tileY, ...override }; |
| 199 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 200 | { this.#drawTile(previous.tileX, previous.tileY); } |
| 201 | this.#drawTile(tileX, tileY); |
| 202 | } |
| 203 | |
| 204 | clearTilePreview () |
| 205 | { |
| 206 | const previous = this.preview; |
| 207 | this.preview = null; |
| 208 | if (previous) |
| 209 | { this.#drawTile(previous.tileX, previous.tileY); } |
| 210 | } |
| 211 | |
| 212 | #lerpMs (gait) |
| 213 | { |
| 214 | const walk = this.settings.walkTilesPerSecond || 2; |
| 215 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 216 | return seconds * 1000; |
| 217 | } |
| 218 | |
| 219 | #centerCamera () |
| 220 | { |
| 221 | if (!this.followPlayer) |
| 222 | { return; } |
| 223 | const local = this.entities.get(this.localEntityId); |
| 224 | if (!local) |
| 225 | { return; } |
| 226 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; |
| 227 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; |
| 228 | } |
| 229 | |
| 230 | #upsertEntity (payload) |
| 231 | { |
| 232 | const size = this.tileSize(); |
| 233 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 234 | let entity = this.entities.get(payload.entityId); |
| 235 | if (!entity) |
| 236 | { |
| 237 | const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male"; |
| 238 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 239 | this.scene.addObject(object); |
| 240 | entity = { object, visualX: pivot.x, visualY: pivot.y }; |
| 241 | this.entities.set(payload.entityId, entity); |
| 242 | } |
| 243 | entity.tileX = payload.tileX; |
| 244 | entity.tileY = payload.tileY; |
| 245 | entity.gait = payload.gait; |
| 246 | entity.sex = payload.sex; |
| 247 | entity.visualX = pivot.x; |
| 248 | entity.visualY = pivot.y; |
| 249 | entity.fromX = pivot.x; |
| 250 | entity.fromY = pivot.y; |
| 251 | this.#placeEntity(entity); |
| 252 | } |
| 253 | |
| 254 | #placeEntity (entity) |
| 255 | { |
| 256 | this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY); |
| 257 | } |
| 258 | |
| 259 | #rebuildChunk (snapshot) |
| 260 | { |
| 261 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 262 | { |
| 263 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 264 | { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | #redrawPreview () |
| 269 | { |
| 270 | if (this.preview) |
| 271 | { this.#drawTile(this.preview.tileX, this.preview.tileY); } |
| 272 | } |
| 273 | |
| 274 | #drawTile (tileX, tileY) |
| 275 | { |
| 276 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 277 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 278 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 279 | if (!snapshot) |
| 280 | { return; } |
| 281 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 282 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 283 | const index = localY * CHUNK_SIZE + localX; |
| 284 | const key = `${tileX},${tileY}`; |
| 285 | let objects = this.tiles.get(key); |
| 286 | if (!objects) |
| 287 | { |
| 288 | objects = { chunkX, chunkY }; |
| 289 | this.tiles.set(key, objects); |
| 290 | } |
| 291 | |
| 292 | let ground = snapshot.grounds[index]; |
| 293 | let block = snapshot.blocks[index]; |
| 294 | const preview = this.preview; |
| 295 | if (preview && preview.tileX === tileX && preview.tileY === tileY) |
| 296 | { |
| 297 | if (preview.ground !== undefined) |
| 298 | { ground = preview.ground; } |
| 299 | if (preview.block !== undefined) |
| 300 | { block = preview.block; } |
| 301 | } |
| 302 | |
| 303 | const size = this.tileSize(); |
| 304 | const pivot = tilePivot(tileX, tileY, size); |
| 305 | const groundName = this.#groundSpriteName(ground); |
| 306 | objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND); |
| 307 | if (objects.ground) |
| 308 | { |
| 309 | this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0); |
| 310 | objects.ground.layer = LAYER_GROUND; |
| 311 | } |
| 312 | |
| 313 | const blockName = this.#blockSpriteName(block); |
| 314 | if (blockName) |
| 315 | { |
| 316 | objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK); |
| 317 | if (objects.block) |
| 318 | { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); } |
| 319 | } |
| 320 | else if (objects.block) |
| 321 | { |
| 322 | objects.block.destroy(); |
| 323 | objects.block = null; |
| 324 | } |
| 325 | |
| 326 | objects.light = snapshot.light[index] ?? 0; |
| 327 | const previousShade = objects.shade; |
| 328 | objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY); |
| 329 | if (objects.shade && objects.shade !== previousShade) |
| 330 | { objects.shade.renderer.alpha = 0; } |
| 331 | } |
| 332 | |
| 333 | #groundSpriteName (ground) |
| 334 | { |
| 335 | const entry = normalizeGround(ground); |
| 336 | const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; |
| 337 | const states = this.catalog.grounds?.[def.key]?.states ?? []; |
| 338 | const state = resolveState(states, entry.state); |
| 339 | return spriteImageName("ground", def.key, state); |
| 340 | } |
| 341 | |
| 342 | #blockSpriteName (block) |
| 343 | { |
| 344 | const entry = normalizeBlock(block); |
| 345 | if (!entry) |
| 346 | { return null; } |
| 347 | const def = BLOCK_DEFINITIONS[entry.typeId]; |
| 348 | if (!def) |
| 349 | { return null; } |
| 350 | const states = this.catalog.blocks?.[def.key]?.states ?? []; |
| 351 | const state = resolveState(states, entry.state); |
| 352 | return spriteImageName("block", def.key, state); |
| 353 | } |
| 354 | |
| 355 | #tileFill (existing, name, x, y, layer) |
| 356 | { |
| 357 | existing = this.#ensureSprite(existing, name, layer); |
| 358 | if (!existing) |
| 359 | { return null; } |
| 360 | const size = this.tileSize(); |
| 361 | existing.transform.position.x = x; |
| 362 | existing.transform.position.y = y; |
| 363 | existing.transform.size = new vector(size, size); |
| 364 | existing.layer = layer; |
| 365 | this.#markSortDirty(); |
| 366 | return existing; |
| 367 | } |
| 368 | |
| 369 | #placePivoted (object, pivotX, pivotY, sortY, subOrder) |
| 370 | { |
| 371 | const sprite = object?.renderer?.sprite; |
| 372 | if (!sprite) |
| 373 | { return; } |
| 374 | const zoom = this.zoom; |
| 375 | const draw = spriteDrawSize(sprite.width, sprite.height, zoom); |
| 376 | const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); |
| 377 | object.transform.position.x = center.x; |
| 378 | object.transform.position.y = center.y; |
| 379 | object.transform.size = new vector(draw.w, draw.h); |
| 380 | object.layer = ySortLayer(sortY, subOrder); |
| 381 | this.#markSortDirty(); |
| 382 | } |
| 383 | |
| 384 | #ensureSprite (existing, name, layer) |
| 385 | { |
| 386 | const sprite = this.game.images[name]; |
| 387 | if (!sprite) |
| 388 | { |
| 389 | existing?.destroy(); |
| 390 | return null; |
| 391 | } |
| 392 | if (!existing || existing.renderer.sprite !== sprite) |
| 393 | { |
| 394 | existing?.destroy(); |
| 395 | existing = new GameObject(0, 0, sprite, layer); |
| 396 | this.scene.addObject(existing); |
| 397 | if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) |
| 398 | { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); } |
| 399 | } |
| 400 | return existing; |
| 401 | } |
| 402 | |
| 403 | #neighborClosed (snapshot, dir, dx, dy) |
| 404 | { |
| 405 | const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 406 | if (other) |
| 407 | { return !other.open; } |
| 408 | return !!snapshot.closedEdges?.[dir]; |
| 409 | } |
| 410 | |
| 411 | #rebuildAllEdges () |
| 412 | { |
| 413 | const seen = new Set(); |
| 414 | for (const snapshot of this.chunks.values()) |
| 415 | { |
| 416 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 417 | seen.add(key); |
| 418 | this.#rebuildChunkEdges(snapshot); |
| 419 | } |
| 420 | for (const key of [...this.edges.keys()]) |
| 421 | { |
| 422 | if (!seen.has(key)) |
| 423 | { this.#destroyEdges(key); } |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | #rebuildChunkEdges (snapshot) |
| 428 | { |
| 429 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 430 | let bars = this.edges.get(key); |
| 431 | if (!bars) |
| 432 | { |
| 433 | bars = {}; |
| 434 | this.edges.set(key, bars); |
| 435 | } |
| 436 | |
| 437 | const size = this.tileSize(); |
| 438 | const chunkPx = CHUNK_SIZE * size; |
| 439 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 440 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 441 | const centerX = left + chunkPx / 2; |
| 442 | const centerY = top + chunkPx / 2; |
| 443 | const thickness = Math.max(2, Math.round(2 * this.zoom)); |
| 444 | const draw = snapshot.open === true; |
| 445 | |
| 446 | bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), |
| 447 | centerX, top, chunkPx, thickness, true); |
| 448 | bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), |
| 449 | centerX, top + chunkPx, chunkPx, thickness, true); |
| 450 | bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), |
| 451 | left, centerY, chunkPx, thickness, false); |
| 452 | bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), |
| 453 | left + chunkPx, centerY, chunkPx, thickness, false); |
| 454 | } |
| 455 | |
| 456 | #edgeBar (existing, visible, x, y, length, thickness, horizontal) |
| 457 | { |
| 458 | if (!visible) |
| 459 | { |
| 460 | if (existing) |
| 461 | { existing.renderer.visible = false; } |
| 462 | return existing; |
| 463 | } |
| 464 | |
| 465 | existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); |
| 466 | existing.renderer.visible = true; |
| 467 | existing.transform.position.x = x; |
| 468 | existing.transform.position.y = y; |
| 469 | existing.transform.size = horizontal |
| 470 | ? new vector(length, thickness) |
| 471 | : new vector(thickness, length); |
| 472 | existing.layer = LAYER_EDGE; |
| 473 | this.#markSortDirty(); |
| 474 | return existing; |
| 475 | } |
| 476 | |
| 477 | #destroyEdges (key) |
| 478 | { |
| 479 | const bars = this.edges.get(key); |
| 480 | if (!bars) |
| 481 | { return; } |
| 482 | bars.north?.destroy(); |
| 483 | bars.east?.destroy(); |
| 484 | bars.south?.destroy(); |
| 485 | bars.west?.destroy(); |
| 486 | this.edges.delete(key); |
| 487 | } |
| 488 | |
| 489 | #markSortDirty () |
| 490 | { |
| 491 | this.scene._sortDirty = true; |
| 492 | } |
| 493 | |
| 494 | #updateShade () |
| 495 | { |
| 496 | const hour = this.nightPreview ?? this.worldHour; |
| 497 | const ambientDark = nightFactor(hour, this.settings.nightDarkness); |
| 498 | for (const objects of this.tiles.values()) |
| 499 | { |
| 500 | if (!objects.shade) |
| 501 | { continue; } |
| 502 | const intensity = Math.min(1, Math.max(0, (objects.light ?? 0) / 255)); |
| 503 | objects.shade.renderer.alpha = ambientDark * (1 - intensity); |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | export function nightFactor (hour, nightDarkness = 0.72) |
| 509 | { |
| 510 | const peak = Math.min(1, Math.max(0, nightDarkness)); |
| 511 | if (hour >= 8 && hour <= 16) |
| 512 | { return 0; } |
| 513 | if (hour >= 22 || hour <= 5) |
| 514 | { return peak; } |
| 515 | if (hour < 8) |
| 516 | { return lerp(peak, 0, (hour - 5) / 3); } |
| 517 | return lerp(0, peak, (hour - 16) / 6); |
| 518 | } |
| 519 | |
| 520 | function lerp (a, b, t) |
| 521 | { |
| 522 | return a + (b - a) * Math.min(1, Math.max(0, t)); |
| 523 | } |