import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js"; import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js"; import { bloomCompanionName, bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js"; import { itemSpriteName } from "/shared/definitions/items.js"; import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; const LAYER_GROUND = 0; const LAYER_SHADE = 500000; const LAYER_EDGE = 900000; const SORT_BLOCK = 1; const SORT_ENTITY = 2; const RENDER_LAYER_BLOOM = "bloom"; export class WorldView { constructor (game, scene, catalog = { grounds: {}, blocks: {} }) { this.game = game; this.scene = scene; this.catalog = catalog; this.preview = null; this.zoom = 2; this.chunks = new Map(); this.tiles = new Map(); this.entities = new Map(); this.groundItems = new Map(); this.edges = new Map(); this.localEntityId = null; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.worldHour = 12; this.nightPreview = null; this.followPlayer = true; this.#syncBloomLayer(); } setSettings (settings) { this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; this.#syncBloomLayer(); } setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null) { this.localEntityId = entityId; this.#upsertEntity({ entityId, characterId, tileX, tileY, gait, sex, firstName, lastName, layers: layers ?? undefined }); } applySnapshot (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; this.chunks.set(key, snapshot); this.#rebuildChunk(snapshot); this.#redrawPreview(); for (const entity of snapshot.entities ?? []) { this.#upsertEntity(entity); } const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) { this.despawnGroundItem(id); } } for (const item of snapshot.groundItems ?? []) { this.upsertGroundItem(item); } this.#rebuildAllEdges(); } removeChunk (chunkX, chunkY) { const key = `${chunkX},${chunkY}`; this.chunks.delete(key); this.#destroyEdges(key); for (const [tileKey, objects] of [...this.tiles.entries()]) { if (objects.chunkX === chunkX && objects.chunkY === chunkY) { objects.ground?.destroy(); objects.groundBloom?.destroy(); objects.block?.destroy(); objects.blockBloom?.destroy(); objects.shade?.destroy(); this.tiles.delete(tileKey); } } for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } } this.#rebuildAllEdges(); } setChunkOpen (chunkX, chunkY, open) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } snapshot.open = !!open; this.#rebuildAllEdges(); } spawnEntity (payload) { this.#upsertEntity(payload); } moveEntity (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { this.#upsertEntity(payload); return; } existing.fromX = existing.visualX; existing.fromY = existing.visualY; existing.tileX = payload.tileX; existing.tileY = payload.tileY; existing.gait = payload.gait; existing.lerpStarted = performance.now(); existing.lerpMs = this.#lerpMs(payload.gait); } despawnEntity (entityId) { const existing = this.entities.get(entityId); if (!existing) { return; } existing.object?.destroy(); for (const overlay of existing.overlays ?? []) { overlay.destroy(); } for (const overlay of existing.bloomOverlays ?? []) { overlay.destroy(); } this.entities.delete(entityId); } setAppearance (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { return; } this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#placeEntity(existing); } upsertGroundItem (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let item = this.groundItems.get(payload.groundItemId); if (!item) { const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); this.scene.addObject(object); item = { object }; this.groundItems.set(payload.groundItemId, item); } item.groundItemId = payload.groundItemId; item.tileX = payload.tileX; item.tileY = payload.tileY; item.itemId = payload.itemId; item.quantity = payload.quantity; item.displayName = payload.displayName; item.sprite = payload.sprite; this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); } despawnGroundItem (groundItemId) { const item = this.groundItems.get(groundItemId); if (!item) { return; } item.object?.destroy(); this.groundItems.delete(groundItemId); } groundItemAtTile (tileX, tileY) { for (const item of this.groundItems.values()) { if (item.tileX === tileX && item.tileY === tileY) { return item; } } return null; } setZoom (zoom, limits = { min: 1, max: 4 }) { const min = limits.min ?? 1; const max = limits.max ?? 4; this.zoom = Math.min(max, Math.max(min, zoom)); for (const snapshot of this.chunks.values()) { this.#rebuildChunk(snapshot); } const size = this.tileSize(); for (const entity of this.entities.values()) { entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; entity.fromX = entity.visualX; entity.fromY = entity.visualY; entity.lerpStarted = null; this.#placeEntity(entity); } for (const item of this.groundItems.values()) { const pivot = tilePivot(item.tileX, item.tileY, size); this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); } this.#rebuildAllEdges(); this.#redrawPreview(); } tileSize () { return SPRITE_SIZE_PX * this.zoom; } screenToTile (mouseX, mouseY) { const size = this.tileSize(); const worldX = mouseX - this.scene.cameraPosition.x; const worldY = mouseY - this.scene.cameraPosition.y; return { tileX: Math.floor(worldX / size), tileY: Math.floor(worldY / size) }; } entityAtScreen (mouseX, mouseY) { let best = null; let bestLayer = -Infinity; for (const entity of this.entities.values()) { const box = this.#entityScreenBox(entity); if (!box) { continue; } if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) { const layer = entity.object?.layer ?? 0; if (layer >= bestLayer) { best = entity; bestLayer = layer; } } } return best; } nametagAnchor (entity) { const box = this.#entityScreenBox(entity); if (!box) { return null; } return { x: (box.left + box.right) / 2, y: box.top }; } #entityScreenBox (entity) { const object = entity?.object; if (!object) { return null; } const size = object.transform.size; const x = object.transform.position.x + this.scene.cameraPosition.x; const y = object.transform.position.y + this.scene.cameraPosition.y; return { left: x - size.x / 2, right: x + size.x / 2, top: y - size.y / 2, bottom: y + size.y / 2 }; } update (deltaTime) { const now = performance.now(); const size = this.tileSize(); for (const entity of this.entities.values()) { const target = tilePivot(entity.tileX, entity.tileY, size); if (entity.lerpStarted != null) { const t = Math.min(1, (now - entity.lerpStarted) / entity.lerpMs); entity.visualX = entity.fromX + (target.x - entity.fromX) * t; entity.visualY = entity.fromY + (target.y - entity.fromY) * t; if (t >= 1) { entity.lerpStarted = null; } } else { entity.visualX = target.x; entity.visualY = target.y; } this.#placeEntity(entity); } this.#centerCamera(); this.#updateShade(deltaTime); } updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const index = localY * CHUNK_SIZE + localX; if (ground !== undefined) { snapshot.grounds[index] = ground; } if (block !== undefined) { snapshot.blocks[index] = block; } if (light !== undefined) { snapshot.light[index] = light; } this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY); } setTilePreview (tileX, tileY, override) { const previous = this.preview; this.preview = { tileX, tileY, ...override }; if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) { this.#drawTile(previous.tileX, previous.tileY); } this.#drawTile(tileX, tileY); } clearTilePreview () { const previous = this.preview; this.preview = null; if (previous) { this.#drawTile(previous.tileX, previous.tileY); } } #lerpMs (gait) { const walk = this.settings.walkTilesPerSecond || 2; const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; return seconds * 1000; } #centerCamera () { if (!this.followPlayer) { return; } const local = this.entities.get(this.localEntityId); if (!local) { return; } this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX; this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY; } #upsertEntity (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let entity = this.entities.get(payload.entityId); if (!entity) { const spriteName = payload.layers?.[0]?.sprite ?? payload.sprite ?? bodySpriteName(payload.sex); const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); this.scene.addObject(object); entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; this.entities.set(payload.entityId, entity); } entity.entityId = payload.entityId; entity.tileX = payload.tileX; entity.tileY = payload.tileY; entity.gait = payload.gait; entity.sex = payload.sex ?? entity.sex; entity.characterId = payload.characterId ?? entity.characterId ?? null; if (payload.firstName) { entity.firstName = payload.firstName; } if (payload.lastName) { entity.lastName = payload.lastName; } entity.firstName = entity.firstName ?? ""; entity.lastName = entity.lastName ?? ""; entity.visualX = pivot.x; entity.visualY = pivot.y; entity.fromX = pivot.x; entity.fromY = pivot.y; if (payload.layers) { this.#applyLayers(entity, payload.layers); } this.#placeEntity(entity); } #applyLayers (entity, layers) { const base = layers[0]?.sprite ?? bodySpriteName(entity.sex); if (this.game.images[base]) { entity.object.renderer.sprite = this.game.images[base]; } for (const overlay of entity.overlays ?? []) { overlay.destroy(); } for (const overlay of entity.bloomOverlays ?? []) { overlay.destroy(); } entity.overlays = []; entity.bloomOverlays = []; for (const layer of layers.slice(1)) { const image = this.game.images[layer.sprite]; if (!image) { continue; } const object = new GameObject(0, 0, image, SORT_ENTITY); this.scene.addObject(object); entity.overlays.push(object); const bloomName = bloomCompanionName(layer.sprite); const bloomImage = this.game.images[bloomName]; if (!bloomImage) { continue; } const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); bloom.renderer.layer = RENDER_LAYER_BLOOM; this.scene.addObject(bloom); entity.bloomOverlays.push(bloom); } } #placeEntity (entity) { this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY); for (const overlay of entity.overlays ?? []) { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); } for (const overlay of entity.bloomOverlays ?? []) { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); } } #rebuildChunk (snapshot) { for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); } } } #redrawPreview () { if (this.preview) { this.#drawTile(this.preview.tileX, this.preview.tileY); } } #drawTile (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; const key = `${tileX},${tileY}`; let objects = this.tiles.get(key); if (!objects) { objects = { chunkX, chunkY }; this.tiles.set(key, objects); } let ground = snapshot.grounds[index]; let block = snapshot.blocks[index]; const preview = this.preview; if (preview && preview.tileX === tileX && preview.tileY === tileY) { if (preview.ground !== undefined) { ground = preview.ground; } if (preview.block !== undefined) { block = preview.block; } } const size = this.tileSize(); const pivot = tilePivot(tileX, tileY, size); const groundName = this.#groundSpriteName(ground); objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND); if (objects.ground) { this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0); objects.ground.layer = LAYER_GROUND; } objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, this.#groundBloomName(ground), pivot); const blockName = this.#blockSpriteName(block); if (blockName) { objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK); if (objects.block) { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); } } else if (objects.block) { objects.block.destroy(); objects.block = null; } objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, this.#blockBloomName(block), pivot); objects.light = snapshot.light[index] ?? 0; const previousShade = objects.shade; objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY); if (objects.shade && objects.shade !== previousShade) { objects.shade.renderer.alpha = 0; } } #groundSpriteName (ground) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const states = this.catalog.grounds?.[def.key]?.states ?? []; const state = resolveState(states, entry.state); return spriteImageName("ground", def.key, state); } #blockSpriteName (block) { const entry = normalizeBlock(block); if (!entry) { return null; } const def = BLOCK_DEFINITIONS[entry.typeId]; if (!def) { return null; } const states = this.catalog.blocks?.[def.key]?.states ?? []; const state = resolveState(states, entry.state); return spriteImageName("block", def.key, state); } #groundBloomName (ground) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const type = this.catalog.grounds?.[def.key]; const state = resolveState(type?.states ?? [], entry.state); if (!state || !type?.blooms?.[state]) { return null; } return bloomImageName("ground", def.key, state); } #blockBloomName (block) { const entry = normalizeBlock(block); if (!entry) { return null; } const def = BLOCK_DEFINITIONS[entry.typeId]; if (!def) { return null; } const type = this.catalog.blocks?.[def.key]; const state = resolveState(type?.states ?? [], entry.state); if (!state || !type?.blooms?.[state]) { return null; } return bloomImageName("block", def.key, state); } #placeBloomOverlay (existing, name, pivot) { if (!name) { existing?.destroy(); return null; } const object = this.#ensureSprite(existing, name, SORT_BLOCK); if (!object) { return null; } object.renderer.layer = RENDER_LAYER_BLOOM; this.#placePivoted(object, pivot.x, pivot.y, pivot.y, SORT_BLOCK); return object; } #tileFill (existing, name, x, y, layer) { existing = this.#ensureSprite(existing, name, layer); if (!existing) { return null; } const size = this.tileSize(); existing.transform.position.x = x; existing.transform.position.y = y; existing.transform.size = new vector(size, size); existing.layer = layer; this.#markSortDirty(); return existing; } #placePivoted (object, pivotX, pivotY, sortY, subOrder) { const sprite = object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom); object.transform.position.x = center.x; object.transform.position.y = center.y; object.transform.size = new vector(draw.w, draw.h); object.layer = ySortLayer(sortY, subOrder); this.#markSortDirty(); } #ensureSprite (existing, name, layer) { const sprite = this.game.images[name]; if (!sprite) { existing?.destroy(); return null; } if (!existing || existing.renderer.sprite !== sprite) { existing?.destroy(); existing = new GameObject(0, 0, sprite, layer); this.scene.addObject(existing); if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); } } return existing; } #neighborClosed (snapshot, dir, dx, dy) { const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); if (other) { return !other.open; } return !!snapshot.closedEdges?.[dir]; } #rebuildAllEdges () { const seen = new Set(); for (const snapshot of this.chunks.values()) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; seen.add(key); this.#rebuildChunkEdges(snapshot); } for (const key of [...this.edges.keys()]) { if (!seen.has(key)) { this.#destroyEdges(key); } } } #rebuildChunkEdges (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; let bars = this.edges.get(key); if (!bars) { bars = {}; this.edges.set(key, bars); } const size = this.tileSize(); const chunkPx = CHUNK_SIZE * size; const left = snapshot.chunkX * CHUNK_SIZE * size; const top = snapshot.chunkY * CHUNK_SIZE * size; const centerX = left + chunkPx / 2; const centerY = top + chunkPx / 2; const thickness = Math.max(2, Math.round(2 * this.zoom)); const draw = snapshot.open === true; bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), centerX, top, chunkPx, thickness, true); bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), centerX, top + chunkPx, chunkPx, thickness, true); bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), left, centerY, chunkPx, thickness, false); bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), left + chunkPx, centerY, chunkPx, thickness, false); } #edgeBar (existing, visible, x, y, length, thickness, horizontal) { if (!visible) { if (existing) { existing.renderer.visible = false; } return existing; } existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); existing.renderer.visible = true; existing.transform.position.x = x; existing.transform.position.y = y; existing.transform.size = horizontal ? new vector(length, thickness) : new vector(thickness, length); existing.layer = LAYER_EDGE; this.#markSortDirty(); return existing; } #destroyEdges (key) { const bars = this.edges.get(key); if (!bars) { return; } bars.north?.destroy(); bars.east?.destroy(); bars.south?.destroy(); bars.west?.destroy(); this.edges.delete(key); } #markSortDirty () { this.scene._sortDirty = true; } #updateShade () { const hour = this.nightPreview ?? this.worldHour; const ambientDark = nightFactor(hour, this.settings.nightDarkness); for (const objects of this.tiles.values()) { if (!objects.shade) { continue; } const intensity = Math.min(1, Math.max(0, (objects.light ?? 0) / 255)); objects.shade.renderer.alpha = ambientDark * (1 - intensity); } } #syncBloomLayer () { const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; this.scene.setLayers([ { name: "default" }, { name: RENDER_LAYER_BLOOM, composite: "add", postShaders: Shader.getBloomPostChain({ threshold: settings.bloomThreshold, softKnee: settings.bloomSoftKnee, intensity: settings.bloomIntensity, blurSize: settings.bloomBlurSize, saturation: settings.bloomSaturation, colorPreserve: settings.bloomColorPreserve, dilate: settings.bloomDilate, scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 }) } ]); } } export function nightFactor (hour, nightDarkness = 0.72) { const peak = Math.min(1, Math.max(0, nightDarkness)); if (hour >= 8 && hour <= 16) { return 0; } if (hour >= 22 || hour <= 5) { return peak; } if (hour < 8) { return lerp(peak, 0, (hour - 5) / 3); } return lerp(0, peak, (hour - 16) / 6); } function bodySpriteName (sex) { const key = sex === "female" ? "player-body-female" : "player-body-male"; return spriteImageName("character", key, key); } function lerp (a, b, t) { return a + (b - a) * Math.min(1, Math.max(0, t)); }