import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, BlockType, normalizeGround, normalizeBlock, listPlaceableBlockPaletteEntries } from "/shared/definitions/tiles.js"; import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js"; import { SeasonId, seasonIdAt, seasonalCycleStates, seasonIdFromVisualState, placeableStatesForType } from "/shared/world/season.js"; import { loadGraphicsSettings } from "/shared/graphics/settings.js"; import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js"; import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js"; import { computeNeighborConnectMask, composeNeighborConnectState, definitionUsesNeighborConnect, neighborConnectBlocksMatch } from "/shared/world/neighborConnect.js"; import { GameSocket, defaultSocketUrl } from "../net/socket.js"; import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js"; import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; import { WorldView } from "../render/worldView.js"; import { initSettingsModal, initDimensionSettings } from "./settingsModal.js"; import { initPaletteModal } from "./paletteModal.js"; import { initTileConfigModal } from "./tileConfigModal.js"; import { initQuestsModal } from "./questsModal.js"; import { initDialoguesModal } from "./dialoguesModal.js"; import { createDimensionCombobox } from "./dimensionCombobox.js"; import { OVERWORLD_ID, normalizeDimensionId, isOverworld } from "/shared/world/dimensions.js"; const game = new Game(); let socket; let scene; let view; let draft = null; /** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */ let draftBaseline = null; /** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */ let pendingNavigate = null; /** When true, next matching editorChunk after save should navigate to pendingNavigate. */ let navigateAfterSave = false; let chunkX = 0; let chunkY = 0; let selectedDimensionId = OVERWORLD_ID; /** @type {string|null} */ let pendingCreatedDimensionId = null; /** @type {Map} */ let dimensionsById = new Map(); let dimensionCombo = null; let dimensionSettings = null; let tool = { kind: "ground", typeId: GroundType.grass, state: null }; let settingsModal; let paletteModal; let tileConfigModal; let questsModal; let dialoguesModal; let catalog = { grounds: {}, blocks: {}, images: [] }; let imageUrlByName = new Map(); let hoverLocal = null; let editorZoom = null; let activeRevisionId = null; let pendingRevisionId = null; let applyInFlight = false; /** @type {string|null} */ let sessionAuthSubject = null; const EDITOR_ZOOM_MIN = 0.25; const EDITOR_ZOOM_MAX = 8; const EDITOR_ZOOM_STEP = 1.12; const CONSOLE_MAX_LINES = 2000; function $ (id) { return document.getElementById(id); } function formatConsoleTime (t) { try { return new Date(t).toLocaleTimeString(); } catch { return ""; } } function appendConsoleLine (entry, { scroll = true } = {}) { const pre = $("editor-console"); if (!pre || !entry) { return; } const line = document.createElement("div"); const level = entry.level || "info"; line.className = `console-${level}`; line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`; pre.append(line); while (pre.childElementCount > CONSOLE_MAX_LINES) { pre.firstChild?.remove(); } if (scroll) { pre.scrollTop = pre.scrollHeight; } } function applyConsoleSnapshot (lines) { const pre = $("editor-console"); if (!pre) { return; } pre.replaceChildren(); for (const entry of lines ?? []) { appendConsoleLine(entry, { scroll: false }); } pre.scrollTop = pre.scrollHeight; } function initSidePanelTabs () { const tabs = document.querySelectorAll(".side-panel-tab"); const bodies = document.querySelectorAll("[data-side-panel-body]"); function activate (name) { for (const tab of tabs) { const on = tab.dataset.sidePanel === name; tab.classList.toggle("active", on); tab.setAttribute("aria-selected", on ? "true" : "false"); } for (const body of bodies) { body.hidden = body.dataset.sidePanelBody !== name; } if (name === "console") { const pre = $("editor-console"); if (pre) { pre.scrollTop = pre.scrollHeight; } } } for (const tab of tabs) { tab.addEventListener("click", () => activate(tab.dataset.sidePanel)); } $("console-clear")?.addEventListener("click", () => { const pre = $("editor-console"); if (pre) { pre.replaceChildren(); } }); activate("changelog"); } function selectedToolLabel () { if (tool.kind === "erase") { return "Erase block"; } if (tool.kind === "spawner") { const def = mobDefinition(tool.mobTypeId); return `Spawner · ${def?.displayName ?? tool.mobTypeId}`; } 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 (tool.kind === "block" && def.id === BlockType.flower) { return "Flower"; } if (tool.kind === "block" && def.id === BlockType.boulder) { const entry = listPlaceableBlockPaletteEntries(catalog) .find((row) => row.typeId === def.id && row.state === state); if (entry) { return entry.displayName; } } if (states.length > 1) { return `${def.displayName} (${state})`; } return def.displayName; } function selectTool (next) { if (next.kind === "erase") { tool = { kind: "erase" }; return; } if (next.kind === "spawner") { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; 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: next.state ?? defaultStateForType(catalog, layer, def.key) }; } function placeableToolState () { if (tool.kind === "erase" || tool.kind === "spawner") { 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 }; } if (tool.kind === "spawner") { return {}; } 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 syncSpawnersOverlay (cx, cy, spawners) { view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId)); } function spawnerAt (localX, localY) { return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null; } function draftPersistable () { if (!draft) { return null; } return { open: !!draft.open, grounds: draft.grounds, blocks: draft.blocks, spawners: draft.spawners ?? [] }; } function captureDraftBaseline () { const payload = draftPersistable(); draftBaseline = payload ? JSON.stringify(payload) : null; syncSaveButton(); } function isDraftDirty () { if (!draft || draftBaseline == null) { return false; } return JSON.stringify(draftPersistable()) !== draftBaseline; } function syncSaveButton () { const btn = $("save"); if (!btn) { return; } const softDeleted = isSelectedDimensionSoftDeleted(); const dirty = isDraftDirty(); btn.disabled = !dirty || softDeleted; btn.classList.toggle("save-dirty", dirty && !softDeleted); btn.title = softDeleted ? "Cannot save while this dimension is soft-deleted" : dirty ? "Save unsaved chunk changes" : "No unsaved changes"; } function afterDraftMutation () { syncSaveButton(); } function showUnsavedModal (target) { pendingNavigate = target; $("unsaved-chunk-backdrop").hidden = false; $("unsaved-chunk-modal").hidden = false; } function hideUnsavedModal () { $("unsaved-chunk-backdrop").hidden = true; $("unsaved-chunk-modal").hidden = true; } function saveSelectedChunk () { if (!draft || !isDraftDirty()) { return false; } if (isSelectedDimensionSoftDeleted()) { $("error").textContent = "Cannot save while this dimension is soft-deleted."; return false; } $("error").textContent = ""; $("apply-status").textContent = ""; $("apply-status").className = "hint"; socket.send({ type: MessageType.editorSaveChunk, chunkX, chunkY, dimensionId: selectedDimensionId, draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks, spawners: draft.spawners ?? [] } }); requestNeighbors(); return true; } function isSelectedDimensionSoftDeleted () { const record = dimensionsById.get(selectedDimensionId); return record?.deletedAt != null; } function formatPurgeHint (record) { if (!record?.purgeAfter) { return "Soft-deleted — painting disabled."; } const when = new Date(record.purgeAfter); return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`; } function syncDimensionUi () { const record = dimensionsById.get(selectedDimensionId); const softDeleted = record?.deletedAt != null; const hint = $("dimension-purge-hint"); if (hint) { hint.hidden = !softDeleted; hint.textContent = softDeleted ? formatPurgeHint(record) : ""; } const openToggle = $("open"); if (openToggle) { openToggle.disabled = softDeleted; } dimensionCombo?.setValue(selectedDimensionId); dimensionSettings?.refresh(); syncSaveButton(); } function applyDimensionsList (payload) { const list = Array.isArray(payload?.dimensions) ? payload.dimensions : []; dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim])); if (!dimensionsById.has(OVERWORLD_ID)) { dimensionsById.set(OVERWORLD_ID, { dimensionId: OVERWORLD_ID, displayName: "Overworld", lightingMode: "dayNight", seasonMode: "auto", defaultGroundTypeId: 1, deletedAt: null, purgeAfter: null }); } const options = [...dimensionsById.values()].map((dim) => ({ id: dim.dimensionId, label: dim.displayName || dim.dimensionId, disabled: dim.deletedAt != null, hint: dim.deletedAt != null ? formatPurgeHint(dim) : null })); dimensionCombo?.setOptions(options); const createdId = pendingCreatedDimensionId; pendingCreatedDimensionId = null; if (createdId && dimensionsById.has(createdId)) { setRevisionState({ activeRevisionId: payload.activeRevisionId, pendingRevisionId: payload.pendingRevisionId }); selectDimension(createdId, { force: true }); return; } if (!dimensionsById.has(selectedDimensionId)) { selectedDimensionId = OVERWORLD_ID; } setRevisionState({ activeRevisionId: payload.activeRevisionId, pendingRevisionId: payload.pendingRevisionId }); syncDimensionUi(); if (!isDraftDirty()) { requestChunks(neighborhoodCoords(chunkX, chunkY)); } } function requestDimensions () { socket.send({ type: MessageType.editorListDimensions }); } function selectDimension (dimensionId, { force = false } = {}) { const nextId = normalizeDimensionId(dimensionId); if (!force && nextId === selectedDimensionId) { return; } if (!force && isDraftDirty()) { showUnsavedModal({ chunkX, chunkY, dimensionId: nextId }); dimensionCombo?.setValue(selectedDimensionId); return; } selectedDimensionId = nextId; syncDimensionUi(); clearNeighborhoodView(); doLoadNeighborhood(chunkX, chunkY); } function clearNeighborhoodView () { draft = null; draftBaseline = null; if (!view) { return; } for (const key of [...view.chunks.keys()]) { const [x, y] = key.split(",").map(Number); view.removeChunk(x, y); } view.clearEditorSpawners?.(); syncSaveButton(); } function paintAt (localX, localY) { if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return; } if (isSelectedDimensionSoftDeleted()) { 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") { const removed = draft.blocks[index]; draft.blocks[index] = null; view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId])) { refreshNeighborConnect(localX, localY, removed.typeId); } afterDraftMutation(); return; } else if (tool.kind === "spawner") { const existing = spawnerAt(localX, localY); const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`; const entry = { localX, localY, config: normalizeSpawnerConfig({ ...defaultSpawnerConfig(spawnerId, tool.mobTypeId), ...(existing?.config ?? {}), spawnerId, mobTypeId: tool.mobTypeId }, spawnerId) }; draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY); draft.spawners.push(entry); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); afterDraftMutation(); return; } else { const def = BLOCK_DEFINITIONS[tool.typeId]; if (def?.id === BlockType.fishingSpot) { const groundType = draft.grounds[index]?.typeId; if (groundType !== GroundType.water && groundType !== GroundType.deepWater) { return; } } let nextState = definitionUsesNeighborConnect(def) ? composeNeighborConnectState(def, state, 0) : state; if (def?.id === BlockType.flower) { nextState = flowerBlockState(randomFlowerColorId()); } if (def?.id === BlockType.fishingSpot && !nextState) { nextState = "fishing-spot"; } const config = def?.id === BlockType.doorway ? { targetDimensionId: selectedDimensionId, tileX: chunkX * CHUNK_SIZE + localX, tileY: chunkY * CHUNK_SIZE + localY } : (def?.id === BlockType.fishingSpot ? { fishes: [] } : null); if (def?.id === BlockType.doorway && !nextState) { nextState = "door"; } draft.blocks[index] = { typeId: tool.typeId, state: nextState, config }; view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); if (definitionUsesNeighborConnect(def)) { refreshNeighborConnect(localX, localY, tool.typeId); } afterDraftMutation(); return; } view.updateAuthoredTile(chunkX, chunkY, localX, localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); } /** Recompute neighbor-connect masks for a type around a local tile (same chunk). */ function refreshNeighborConnect (localX, localY, typeId) { const def = BLOCK_DEFINITIONS[typeId]; if (!draft || !definitionUsesNeighborConnect(def)) { return; } const cells = [[localX, localY]]; for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) { cells.push([localX + dx, localY + dy]); } for (const [lx, ly] of cells) { if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE) { continue; } const index = ly * CHUNK_SIZE + lx; const block = draft.blocks[index]; if (!block || block.typeId !== typeId) { continue; } const mask = computeNeighborConnectMask((dx, dy) => { const nx = lx + dx; const ny = ly + dy; if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE) { return false; } const neighbor = draft.blocks[ny * CHUNK_SIZE + nx]; return neighborConnectBlocksMatch(block, neighbor, def); }); block.state = composeNeighborConnectState(def, block.state, mask); view.updateAuthoredTile(chunkX, chunkY, lx, ly, { 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, config: block.config ?? null } : null)), light: payload.data.light.slice(), spawners: (payload.data.spawners ?? []).map((entry) => ({ localX: entry.localX, localY: entry.localY, config: { ...entry.config } })) }; $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; $("open").checked = draft.open; setRevisionState({ activeRevisionId: payload.activeRevisionId, pendingRevisionId: payload.pendingRevisionId }); $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)"; 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)); syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners); captureDraftBaseline(); if (navigateAfterSave && pendingNavigate) { const next = pendingNavigate; navigateAfterSave = false; pendingNavigate = null; const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; if (nextDim !== selectedDimensionId) { selectedDimensionId = nextDim; syncDimensionUi(); clearNeighborhoodView(); } doLoadNeighborhood(next.chunkX, next.chunkY); } } 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 sidePanels = $("side-panels") || $("changelog-wrap"); const top = header.offsetHeight; aside.style.top = `${top}px`; sidePanels.style.top = `${top}px`; const left = aside.offsetWidth; const right = sidePanels.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)); scheduleEditorZoom(); } let editorZoomRaf = 0; function scheduleEditorZoom () { if (editorZoomRaf) { return; } editorZoomRaf = requestAnimationFrame(() => { editorZoomRaf = 0; if (!view) { return; } view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); frameNeighborhood(); }); } function requestChunks (coords) { if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN) { return; } for (const coord of coords) { try { socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY, dimensionId: selectedDimensionId }); } catch (_) { break; } } } function doLoadNeighborhood (x, y) { chunkX = x; chunkY = y; $("coords").textContent = `${chunkX}, ${chunkY}`; requestChunks(neighborhoodCoords(x, y)); } function loadNeighborhood (x, y) { if ((x !== chunkX || y !== chunkY) && isDraftDirty()) { showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId }); return; } doLoadNeighborhood(x, y); } function requestNeighbors () { requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); } function anyModalOpen () { return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen() || questsModal?.isOpen() || dialoguesModal?.isOpen() || !$("unsaved-chunk-modal")?.hidden; } function updateHoverStatus (local) { const el = $("hover-status-text"); if (!el) { return; } if (!local) { el.textContent = "Hover a tile for coordinates"; return; } const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE); const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE); el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`; } function updateTooltip (local, options = {}) { if (!options.keepStatus) { updateHoverStatus(local); } const tip = $("tile-tooltip"); if (!tip || !local || !draft) { if (tip) { tip.hidden = true; } view?.clearSpawnRangeHighlight(); return; } const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]); const spawner = spawnerAt(local.x, local.y); const lines = []; if (block) { const def = BLOCK_DEFINITIONS[block.typeId]; lines.push(def?.displayName ?? `Block ${block.typeId}`); if (block.config && Object.keys(block.config).length) { for (const [key, value] of Object.entries(block.config)) { lines.push(`${key}: ${value}`); } } } if (spawner) { const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId); const mob = mobDefinition(config.mobTypeId); lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`); lines.push(`maxAlive: ${config.maxAlive}`); lines.push(`spawnRange: ${config.spawnRangeTiles}`); lines.push(`wanderRange: ${config.maxWanderRangeTiles}`); lines.push(`id: ${config.spawnerId}`); view.setSpawnRangeHighlight( local.tileX, local.tileY, config.spawnRangeTiles, config.maxWanderRangeTiles ); } else { view.clearSpawnRangeHighlight(); } if (!lines.length) { tip.hidden = true; return; } tip.hidden = false; tip.textContent = lines.join("\n"); const canvas = scene.canvas; const rect = canvas.getBoundingClientRect(); const size = view.tileSize(); const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size; const screenY = local.tileY * size + scene.cameraPosition.y + rect.top; tip.style.left = `${screenX}px`; tip.style.top = `${screenY}px`; } async function main () { const authStatus = await fetchAuthStatus(); const signIn = document.getElementById("auth-sign-in"); const signOut = document.getElementById("auth-sign-out"); if (signIn) { signIn.hidden = !!authStatus?.authenticated; signIn.href = loginUrl("/editor"); } if (signOut) { signOut.hidden = !authStatus?.authenticated; signOut.href = logoutUrl("/editor"); } if (!authStatus.authenticated) { $("who").textContent = "Sign in required"; $("error").textContent = "Sign in with your Tim Falken account to use the world editor."; return; } const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in"; $("who").textContent = `${accountLabel} · loading sprites…`; catalog = await loadSpriteCatalog(); imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url])); await preloadCatalogImages(game, catalog, { onProgress ({ loaded, total }) { $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`; } }); applySpriteSheets(game.images, catalog); scene = new Scene(250, 56, 64, 64); game.loadScene(scene); view = new WorldView(game, scene, catalog); view.followPlayer = false; view.setGraphicsPrefs(loadGraphicsSettings()); syncSeasonControls(view.worldSeason ?? seasonIdAt()); layoutScene(); selectTool(tool); $("tool").textContent = selectedToolLabel(); paletteModal = initPaletteModal({ catalog, imageUrlFor (name) { const sprite = game.images[name]; const html = sprite?.g_image; if (html && typeof html.toDataURL === "function") { try { return html.toDataURL("image/png"); } catch (_) { /* fall through */ } } return imageUrlByName.get(name) ?? null; }, onSelect (next) { selectTool(next); $("tool").textContent = selectedToolLabel(); } }); tileConfigModal = initTileConfigModal({ socket: { send (payload) { socket?.send(payload); } }, MessageType, getDialogues: () => dialoguesModal?.getDialogues?.() ?? [], getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({ id: dim.dimensionId, label: dim.displayName || dim.dimensionId, disabled: !!dim.deletedAt, hint: dim.deletedAt ? "soft-deleted" : undefined })), onSave (ctx, config) { if (!draft) { return; } if (ctx.kind === "doorway") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; draft.blocks[index] = { typeId: BlockType.doorway, state: config.state || "door", config: { targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID), tileX: Number(config.tileX) || 0, tileY: Number(config.tileY) || 0 } }; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } if (ctx.kind === "fishing-spot") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; const existing = draft.blocks[index]; draft.blocks[index] = { typeId: BlockType.fishingSpot, state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot", config: { fishes: [...(config.fishes ?? [])] } }; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config }); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); afterDraftMutation(); }, onRemove (ctx) { if (!draft) { return; } if (ctx.kind === "doorway") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; draft.blocks[index] = null; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } if (ctx.kind === "fishing-spot") { const index = ctx.localY * CHUNK_SIZE + ctx.localX; draft.blocks[index] = null; view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { ground: draft.grounds[index], block: draft.blocks[index], light: draft.light[index] }); afterDraftMutation(); return; } draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); syncSpawnersOverlay(chunkX, chunkY, draft.spawners); afterDraftMutation(); } }); 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 && !anyModalOpen()) { const tile = view.screenToTile(mouseX, mouseY); const localX = tile.tileX - chunkX * CHUNK_SIZE; const localY = tile.tileY - chunkY * CHUNK_SIZE; const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE); const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE); updateHoverStatus({ tileX: tile.tileX, tileY: tile.tileY, x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE, y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE, chunkX: hoverChunkX, chunkY: hoverChunkY }); 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()); updateTooltip(hoverLocal); if (GameInput.mouseHeld(GameInput.MouseButtons.Left)) { paintAt(localX, localY); } } else { hoverLocal = null; view.clearTilePreview(); updateTooltip(null, { keepStatus: true }); } } else { view.clearTilePreview(); updateTooltip(null); } view.update(dt); frameNeighborhood(); }; scene.addObject(ticker); window.addEventListener("resize", layoutScene); $("who").textContent = `${accountLabel} · connecting…`; socket = new GameSocket(defaultSocketUrl(), (message) => { if (message.type === MessageType.session) { sessionAuthSubject = message.authSubject ?? null; const label = message.username ?? message.authSubject ?? "Unknown"; $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`; if (!message.isAdmin) { $("error").textContent = "Admin access required."; return; } $("error").textContent = ""; const restartBtn = document.getElementById("editor-restart-now"); if (restartBtn) { restartBtn.hidden = false; restartBtn.disabled = false; } socket.send({ type: MessageType.editorLoadSettings }); socket.send({ type: MessageType.editorLoadGameAdmins }); socket.send({ type: MessageType.editorConsoleSubscribe }); requestDimensions(); loadNeighborhood(0, 0); } else if (message.type === MessageType.editorSettings || message.type === MessageType.editorGameAdmins) { settingsModal.handleMessage(message); } else if (message.type === MessageType.editorConsoleSnapshot) { applyConsoleSnapshot(message.lines); } else if (message.type === MessageType.editorConsoleLine) { appendConsoleLine(message.line); } else if (message.type === MessageType.editorDimensions) { applyDimensionsList(message); } else if (message.type === MessageType.editorQuests) { questsModal?.handleMessage(message); } else if (message.type === MessageType.editorDialogues) { dialoguesModal?.handleMessage(message); tileConfigModal?.handleMessage(message); } else if (message.type === MessageType.editorChunk) { const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); if (msgDim !== selectedDimensionId) { return; } 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)); syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners); } 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"; requestDimensions(); requestChunks(neighborhoodCoords(chunkX, chunkY)); } else if (message.type === MessageType.forceLogout) { $("who").textContent = "Server restarting…"; $("error").textContent = message.reason || "Server shutting down."; } else if (message.type === MessageType.error) { $("error").textContent = message.message; pendingCreatedDimensionId = null; navigateAfterSave = false; dimensionCombo?.setValue(selectedDimensionId); if (applyInFlight) { applyInFlight = false; $("apply-status").textContent = ""; $("apply-status").className = "hint"; updateRevisionUI(); } } }, { onClose (event) { if (event.code === 1000) { return; } const reasons = { 4401: "Sign in expired or missing. Use Sign out, then sign in again.", 1011: "Server could not verify your account with auth.timfalken.com.", 1006: "Connection dropped before the editor session started.", 1001: "Server is restarting. Reload this page in a moment." }; const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`; $("who").textContent = "Connection failed"; $("error").textContent = detail; }, onError () { $("who").textContent = "Connection failed"; $("error").textContent = "Could not open a live connection to the server."; } }); settingsModal = initSettingsModal({ socket, MessageType, getAuthSubject: () => sessionAuthSubject, onApplied (settings) { view.setSettings(settings); }, onPreviewNight (hour) { view.nightPreview = hour; $("night").value = String(hour); $("night-label").textContent = Number(hour).toFixed(1); } }); dimensionCombo = createDimensionCombobox({ root: $("dimension-combo"), allowCreate: true, placeholder: "Search or create dimension…", onSelect (id) { selectDimension(id); }, onCreate (rawId) { const id = normalizeDimensionId(rawId); $("error").textContent = ""; pendingCreatedDimensionId = id; socket.send({ type: MessageType.editorCreateDimension, dimensionId: id, displayName: rawId.trim() }); } }); dimensionCombo.setOptions([{ id: OVERWORLD_ID, label: "Overworld" }]); dimensionCombo.setValue(OVERWORLD_ID); dimensionSettings = initDimensionSettings({ socket, MessageType, GROUND_DEFINITIONS, OVERWORLD_ID, getSelectedDimensionId: () => selectedDimensionId, getDimensionRecord: (id) => dimensionsById.get(id) ?? null, isOverworld }); questsModal = initQuestsModal({ socket, MessageType }); dialoguesModal = initDialoguesModal({ socket, MessageType }); initSidePanelTabs(); game.startGame(); useNearestNeighbour(scene, game.images); await socket.connect(); } $("tool").textContent = selectedToolLabel(); $("tool-erase").addEventListener("click", () => { selectTool({ kind: "erase" }); $("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 (isSelectedDimensionSoftDeleted()) { $("open").checked = !!draft?.open; return; } if (draft) { draft.open = $("open").checked; view.setChunkOpen(chunkX, chunkY, draft.open); afterDraftMutation(); } }); $("save").addEventListener("click", () => { saveSelectedChunk(); }); $("unsaved-chunk-cancel")?.addEventListener("click", () => { pendingNavigate = null; navigateAfterSave = false; hideUnsavedModal(); }); $("unsaved-chunk-backdrop")?.addEventListener("click", () => { pendingNavigate = null; navigateAfterSave = false; hideUnsavedModal(); }); $("unsaved-chunk-discard")?.addEventListener("click", () => { const next = pendingNavigate; hideUnsavedModal(); pendingNavigate = null; navigateAfterSave = false; if (!next) { return; } const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; if (nextDim !== selectedDimensionId) { selectedDimensionId = nextDim; syncDimensionUi(); clearNeighborhoodView(); } doLoadNeighborhood(next.chunkX, next.chunkY); }); $("unsaved-chunk-save")?.addEventListener("click", () => { hideUnsavedModal(); if (!pendingNavigate) { return; } navigateAfterSave = true; if (!saveSelectedChunk()) { navigateAfterSave = false; const next = pendingNavigate; pendingNavigate = null; if (next) { const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; if (nextDim !== selectedDimensionId) { selectedDimensionId = nextDim; syncDimensionUi(); clearNeighborhoodView(); } doLoadNeighborhood(next.chunkX, next.chunkY); } } }); $("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 }); }); document.getElementById("editor-restart-now")?.addEventListener("click", () => { if (!socket) { return; } const ok = window.confirm( "Restart the server now?\n\nAll players and editor sessions will disconnect. " + "systemd will start a fresh process and pull the latest code from git." ); if (!ok) { return; } const restartBtn = document.getElementById("editor-restart-now"); if (restartBtn) { restartBtn.disabled = true; } $("who").textContent = "Restarting server…"; $("error").textContent = ""; socket.send({ type: MessageType.editorRestartNow }); }); $("night").addEventListener("input", () => { view.nightPreview = Number($("night").value); $("night-label").textContent = view.nightPreview.toFixed(1); }); $("season").addEventListener("change", () => { applySeasonPreview($("season").value); }); function syncSeasonControls (season) { const next = season === SeasonId.spring || season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer ? season : seasonIdAt(); $("season").value = next; view?.setWorldSeason(next); } function applySeasonPreview (season) { syncSeasonControls(season); } function cycleToolState (direction) { if (tool.kind === "erase" || tool.kind === "spawner") { return; } const layer = tool.kind === "ground" ? "ground" : "block"; const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; if (definitionUsesNeighborConnect(def)) { return; } if (tool.kind === "block" && def?.id === BlockType.flower) { return; } const allStates = statesForType(catalog, layer, def.key); const seasonal = seasonalCycleStates(allStates); const states = seasonal ?? placeableStatesForType(catalog, layer, def.key); if (states.length < 2) { return; } tool.state = cycleState(states, tool.state, direction); $("tool").textContent = selectedToolLabel(); const season = seasonIdFromVisualState(tool.state); if (season) { applySeasonPreview(season); } 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 || anyModalOpen()) { 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 }); document.addEventListener("contextmenu", (event) => { if (!scene?.canvas || anyModalOpen() || !draft) { 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(); const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top); 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) { return; } const spawner = spawnerAt(localX, localY); if (spawner) { tileConfigModal.openSpawner({ localX, localY, tileX: tile.tileX, tileY: tile.tileY, config: { ...spawner.config } }); return; } const index = localY * CHUNK_SIZE + localX; const block = draft.blocks[index]; if (block?.typeId === BlockType.doorway) { tileConfigModal.openDoorway({ localX, localY, tileX: tile.tileX, tileY: tile.tileY, state: block.state ?? "door", config: block.config ? { ...block.config } : {} }); return; } if (block?.typeId === BlockType.fishingSpot) { tileConfigModal.openFishingSpot({ localX, localY, tileX: tile.tileX, tileY: tile.tileY, config: block.config ? { ...block.config } : { fishes: [] } }); } }); main().catch((error) => { $("error").textContent = error.message; console.error(error); });