import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js"; import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js"; import { GameSocket, defaultSocketUrl } from "../net/socket.js"; import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; import { WorldView } from "../render/worldView.js"; import { initSettingsModal } from "./settingsModal.js"; const game = new Game(); let socket; let scene; let view; let draft = null; let chunkX = 0; let chunkY = 0; let tool = { kind: "ground", typeId: GroundType.grass, state: null }; let settingsModal; let catalog = { grounds: {}, blocks: {} }; let hoverLocal = null; let editorZoom = null; let activeRevisionId = null; let pendingRevisionId = null; let applyInFlight = false; const EDITOR_ZOOM_MIN = 0.25; const EDITOR_ZOOM_MAX = 8; const EDITOR_ZOOM_STEP = 1.12; function $ (id) { return document.getElementById(id); } function selectedToolLabel () { if (tool.kind === "erase") { return "Erase block"; } const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; const layer = tool.kind === "ground" ? "ground" : "block"; const states = statesForType(catalog, layer, def.key); const state = resolveState(states, tool.state); if (states.length > 1) { return `${def.displayName} (${state})`; } return def.displayName; } function selectTool (next) { if (next.kind === "erase") { tool = { kind: "erase" }; return; } const layer = next.kind === "ground" ? "ground" : "block"; const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId]; tool = { kind: next.kind, typeId: next.typeId, state: defaultStateForType(catalog, layer, def.key) }; } function placeableToolState () { if (tool.kind === "erase") { return null; } const layer = tool.kind === "ground" ? "ground" : "block"; const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; return resolveState(statesForType(catalog, layer, def.key), tool.state); } function previewFromTool () { if (tool.kind === "erase") { return { block: null }; } const state = placeableToolState(); if (tool.kind === "ground") { return { ground: { typeId: tool.typeId, state } }; } return { block: { typeId: tool.typeId, state, config: null } }; } function inEditorView (x, y) { return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS; } function neighborhoodCoords (centerX, centerY) { const coords = []; for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++) { for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++) { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); } } return coords; } function snapshotFromPayload (payload) { return { chunkX: payload.chunkX, chunkY: payload.chunkY, open: payload.data.open, closedEdges: payload.closedEdges, grounds: payload.data.grounds, blocks: payload.data.blocks, light: payload.data.light, entities: [] }; } function paintAt (localX, localY) { if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return; } const index = localY * CHUNK_SIZE + localX; const state = placeableToolState(); if (tool.kind === "ground") { draft.grounds[index] = { typeId: tool.typeId, state }; } else if (tool.kind === "erase") { draft.blocks[index] = null; } else { const existing = draft.blocks[index]; let config = null; if (tool.typeId === BlockType.spawner) { const spawnerId = existing?.typeId === BlockType.spawner && existing.config?.spawnerId ? existing.config.spawnerId : `${chunkX}:${chunkY}:${index}`; config = { spawnerId, mobTypeId: $("spawner-mob")?.value || "deer", maxAlive: Number($("spawner-max")?.value || 3), spawnRangeTiles: Number($("spawner-range")?.value || 4) }; } draft.blocks[index] = { typeId: tool.typeId, state, config }; } view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); } function updateRevisionUI () { const applyBtn = $("apply"); $("revision").textContent = `active ${activeRevisionId ?? "?"}` + (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision"); if (applyBtn) { applyBtn.disabled = !pendingRevisionId || applyInFlight; applyBtn.title = pendingRevisionId ? "Reload the live world with the pending map revision" : "Save a chunk first to create a pending revision"; } } function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending }) { if (active != null) { activeRevisionId = active; } pendingRevisionId = pending ?? null; updateRevisionUI(); } function showSelectedChunk (payload) { draft = { open: payload.data.open, grounds: payload.data.grounds.map((ground) => normalizeGround(ground)), blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)), light: payload.data.light.slice() }; $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; $("open").checked = draft.open; setRevisionState({ activeRevisionId: payload.activeRevisionId, pendingRevisionId: payload.pendingRevisionId }); $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)"; const log = $("changelog"); log.innerHTML = ""; for (const entry of payload.changelog ?? []) { const item = document.createElement("article"); item.innerHTML = `
${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}
`; const list = document.createElement("ul"); for (const bullet of entry.diffEntries) { const li = document.createElement("li"); li.textContent = bullet; list.append(li); } item.append(list); log.append(item); } view.applySnapshot(snapshotFromPayload(payload)); } function pruneView () { for (const key of [...view.chunks.keys()]) { const [x, y] = key.split(",").map(Number); if (!inEditorView(x, y)) { view.removeChunk(x, y); } } } function frameNeighborhood () { const size = view.tileSize(); view.followPlayer = false; const centerX = (chunkX + 0.5) * CHUNK_SIZE * size; const centerY = (chunkY + 0.5) * CHUNK_SIZE * size; view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX; view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY; updateSelectionBorder(); } function updateSelectionBorder () { const border = $("selection-border"); const canvas = scene?.canvas; if (!border || !canvas) { return; } const rect = canvas.getBoundingClientRect(); const size = view.tileSize(); const chunkPx = CHUNK_SIZE * size; const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x; const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y; border.style.left = `${rect.left + screenLeft}px`; border.style.top = `${rect.top + screenTop}px`; border.style.width = `${chunkPx}px`; border.style.height = `${chunkPx}px`; } function layoutScene () { const header = document.querySelector("body > header"); const aside = document.querySelector("body > aside"); const changelog = $("changelog-wrap"); const top = header.offsetHeight; aside.style.top = `${top}px`; changelog.style.top = `${top}px`; const left = aside.offsetWidth; const right = changelog.offsetWidth; const width = Math.max(64, window.innerWidth - left - right); const height = Math.max(64, window.innerHeight - top); scene.position.x = left; scene.position.y = top; scene.size.x = width; scene.size.y = height; scene.g_fixSize(); useNearestNeighbour(scene, game.images); const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX); if (editorZoom == null) { editorZoom = fit; } else { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); } view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); frameNeighborhood(); } function zoomEditor (direction) { if (!view) { return; } const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP; editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor)); view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); useNearestNeighbour(scene, game.images); frameNeighborhood(); } function requestChunks (coords) { for (const coord of coords) { socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY }); } } function loadNeighborhood (x, y) { chunkX = x; chunkY = y; $("coords").textContent = `${chunkX}, ${chunkY}`; requestChunks(neighborhoodCoords(x, y)); } function requestNeighbors () { requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); } async function main () { catalog = await loadSpriteCatalog(); await preloadCatalogImages(game, catalog); applySpriteSheets(game.images, catalog); scene = new Scene(250, 56, 64, 64); game.loadScene(scene); useNearestNeighbour(scene, game.images); view = new WorldView(game, scene, catalog); view.followPlayer = false; layoutScene(); selectTool(tool); $("tool").textContent = selectedToolLabel(); const ticker = new GameObject(0, 0, null, 10); ticker.update = (dt) => { hoverLocal = null; const canvas = scene.canvas; const rect = canvas.getBoundingClientRect(); const mouseX = GameInput.mousePosition.x - rect.left; const mouseY = GameInput.mousePosition.y - rect.top; const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height; if (overCanvas && draft && !settingsModal?.isOpen()) { const tile = view.screenToTile(mouseX, mouseY); const localX = tile.tileX - chunkX * CHUNK_SIZE; const localY = tile.tileY - chunkY * CHUNK_SIZE; if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE) { hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY }; view.setTilePreview(tile.tileX, tile.tileY, previewFromTool()); if (GameInput.mouseHeld(GameInput.MouseButtons.Left)) { paintAt(localX, localY); } } else { view.clearTilePreview(); } } else { view.clearTilePreview(); } view.update(dt); frameNeighborhood(); }; scene.addObject(ticker); window.addEventListener("resize", layoutScene); socket = new GameSocket(defaultSocketUrl(), (message) => { if (message.type === MessageType.session) { $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`; socket.send({ type: MessageType.editorLoadSettings }); loadNeighborhood(0, 0); } else if (message.type === MessageType.editorSettings) { settingsModal.handleMessage(message); } else if (message.type === MessageType.editorChunk) { if (message.settings) { view.setSettings(message.settings); } if (!inEditorView(message.chunkX, message.chunkY)) { return; } if (message.chunkX === chunkX && message.chunkY === chunkY) { showSelectedChunk(message); } else { view.applySnapshot(snapshotFromPayload(message)); } pruneView(); } else if (message.type === MessageType.editorRevisionApplied) { applyInFlight = false; setRevisionState({ activeRevisionId: message.activeRevisionId, pendingRevisionId: message.pendingRevisionId }); const status = $("apply-status"); status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`; status.className = "hint ok"; requestChunks(neighborhoodCoords(chunkX, chunkY)); } else if (message.type === MessageType.error) { $("error").textContent = message.message; if (applyInFlight) { applyInFlight = false; $("apply-status").textContent = ""; $("apply-status").className = "hint"; updateRevisionUI(); } } }); settingsModal = initSettingsModal({ socket, MessageType, onApplied (settings) { view.setSettings(settings); }, onPreviewNight (hour) { view.nightPreview = hour; $("night").value = String(hour); $("night-label").textContent = Number(hour).toFixed(1); } }); game.startGame(); await socket.connect(); } $("tool").textContent = selectedToolLabel(); document.querySelectorAll("[data-tool]").forEach((button) => { button.addEventListener("click", () => { selectTool(JSON.parse(button.dataset.tool)); $("tool").textContent = selectedToolLabel(); }); }); $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1)); $("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1)); $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY)); $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY)); $("open").addEventListener("change", () => { if (draft) { draft.open = $("open").checked; view.setChunkOpen(chunkX, chunkY, draft.open); } }); $("save").addEventListener("click", () => { $("error").textContent = ""; $("apply-status").textContent = ""; $("apply-status").className = "hint"; socket.send({ type: MessageType.editorSaveChunk, chunkX, chunkY, draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks } }); requestNeighbors(); }); $("apply").addEventListener("click", () => { if (!pendingRevisionId || applyInFlight) { return; } $("error").textContent = ""; const status = $("apply-status"); status.textContent = "Applying…"; status.className = "hint"; applyInFlight = true; updateRevisionUI(); socket.send({ type: MessageType.editorApplyRevision }); }); $("night").addEventListener("input", () => { view.nightPreview = Number($("night").value); $("night-label").textContent = view.nightPreview.toFixed(1); }); function cycleToolState (direction) { if (tool.kind === "erase") { return; } const layer = tool.kind === "ground" ? "ground" : "block"; const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; const states = statesForType(catalog, layer, def.key); if (states.length < 2) { return; } tool.state = cycleState(states, tool.state, direction); $("tool").textContent = selectedToolLabel(); if (!draft || !hoverLocal) { return; } const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x; if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId) { paintAt(hoverLocal.x, hoverLocal.y); } else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId) { paintAt(hoverLocal.x, hoverLocal.y); } } document.addEventListener("wheel", (event) => { if (!scene?.canvas || settingsModal?.isOpen()) { return; } const rect = scene.canvas.getBoundingClientRect(); if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) { return; } event.preventDefault(); if (event.shiftKey) { cycleToolState(event.deltaY < 0 ? 1 : -1); if (hoverLocal) { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); } return; } zoomEditor(event.deltaY < 0 ? 1 : -1); }, { passive: false }); main().catch((error) => { $("error").textContent = error.message; console.error(error); });