| 1 | import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; |
| 2 | import { |
| 3 | GROUND_DEFINITIONS, |
| 4 | BLOCK_DEFINITIONS, |
| 5 | GroundType, |
| 6 | BlockType, |
| 7 | normalizeGround, |
| 8 | normalizeBlock, |
| 9 | listPlaceableBlockPaletteEntries |
| 10 | } from "/shared/definitions/tiles.js"; |
| 11 | import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js"; |
| 12 | import { |
| 13 | SeasonId, |
| 14 | seasonIdAt, |
| 15 | seasonalCycleStates, |
| 16 | seasonIdFromVisualState, |
| 17 | placeableStatesForType |
| 18 | } from "/shared/world/season.js"; |
| 19 | import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js"; |
| 20 | import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js"; |
| 21 | import { |
| 22 | computeNeighborConnectMask, |
| 23 | composeNeighborConnectState, |
| 24 | definitionUsesNeighborConnect, |
| 25 | neighborConnectBlocksMatch |
| 26 | } from "/shared/world/neighborConnect.js"; |
| 27 | import { GameSocket, defaultSocketUrl } from "../net/socket.js"; |
| 28 | import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; |
| 29 | import { WorldView } from "../render/worldView.js"; |
| 30 | import { initSettingsModal, initDimensionSettings } from "./settingsModal.js"; |
| 31 | import { initPaletteModal } from "./paletteModal.js"; |
| 32 | import { initTileConfigModal } from "./tileConfigModal.js"; |
| 33 | import { initQuestsModal } from "./questsModal.js"; |
| 34 | import { initDialoguesModal } from "./dialoguesModal.js"; |
| 35 | import { createDimensionCombobox } from "./dimensionCombobox.js"; |
| 36 | import { |
| 37 | OVERWORLD_ID, |
| 38 | normalizeDimensionId, |
| 39 | isOverworld |
| 40 | } from "/shared/world/dimensions.js"; |
| 41 | |
| 42 | const game = new Game(); |
| 43 | let socket; |
| 44 | let scene; |
| 45 | let view; |
| 46 | let draft = null; |
| 47 | /** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */ |
| 48 | let draftBaseline = null; |
| 49 | /** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */ |
| 50 | let pendingNavigate = null; |
| 51 | /** When true, next matching editorChunk after save should navigate to pendingNavigate. */ |
| 52 | let navigateAfterSave = false; |
| 53 | let chunkX = 0; |
| 54 | let chunkY = 0; |
| 55 | let selectedDimensionId = OVERWORLD_ID; |
| 56 | /** @type {string|null} */ |
| 57 | let pendingCreatedDimensionId = null; |
| 58 | /** @type {Map<string, object>} */ |
| 59 | let dimensionsById = new Map(); |
| 60 | let dimensionCombo = null; |
| 61 | let dimensionSettings = null; |
| 62 | let tool = { kind: "ground", typeId: GroundType.grass, state: null }; |
| 63 | let settingsModal; |
| 64 | let paletteModal; |
| 65 | let tileConfigModal; |
| 66 | let questsModal; |
| 67 | let dialoguesModal; |
| 68 | let catalog = { grounds: {}, blocks: {}, images: [] }; |
| 69 | let imageUrlByName = new Map(); |
| 70 | let hoverLocal = null; |
| 71 | let editorZoom = null; |
| 72 | let activeRevisionId = null; |
| 73 | let pendingRevisionId = null; |
| 74 | let applyInFlight = false; |
| 75 | const EDITOR_ZOOM_MIN = 0.25; |
| 76 | const EDITOR_ZOOM_MAX = 8; |
| 77 | const EDITOR_ZOOM_STEP = 1.12; |
| 78 | |
| 79 | function $ (id) |
| 80 | { |
| 81 | return document.getElementById(id); |
| 82 | } |
| 83 | |
| 84 | function selectedToolLabel () |
| 85 | { |
| 86 | if (tool.kind === "erase") |
| 87 | { return "Erase block"; } |
| 88 | if (tool.kind === "spawner") |
| 89 | { |
| 90 | const def = mobDefinition(tool.mobTypeId); |
| 91 | return `Spawner · ${def?.displayName ?? tool.mobTypeId}`; |
| 92 | } |
| 93 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 94 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 95 | const states = statesForType(catalog, layer, def.key); |
| 96 | const state = resolveState(states, tool.state); |
| 97 | if (tool.kind === "block" && def.id === BlockType.flower) |
| 98 | { return "Flower"; } |
| 99 | if (tool.kind === "block" && def.id === BlockType.boulder) |
| 100 | { |
| 101 | const entry = listPlaceableBlockPaletteEntries(catalog) |
| 102 | .find((row) => row.typeId === def.id && row.state === state); |
| 103 | if (entry) |
| 104 | { return entry.displayName; } |
| 105 | } |
| 106 | if (states.length > 1) |
| 107 | { return `${def.displayName} (${state})`; } |
| 108 | return def.displayName; |
| 109 | } |
| 110 | |
| 111 | function selectTool (next) |
| 112 | { |
| 113 | if (next.kind === "erase") |
| 114 | { |
| 115 | tool = { kind: "erase" }; |
| 116 | return; |
| 117 | } |
| 118 | if (next.kind === "spawner") |
| 119 | { |
| 120 | tool = { kind: "spawner", mobTypeId: next.mobTypeId }; |
| 121 | return; |
| 122 | } |
| 123 | const layer = next.kind === "ground" ? "ground" : "block"; |
| 124 | const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId]; |
| 125 | tool = { |
| 126 | kind: next.kind, |
| 127 | typeId: next.typeId, |
| 128 | state: next.state ?? defaultStateForType(catalog, layer, def.key) |
| 129 | }; |
| 130 | } |
| 131 | |
| 132 | function placeableToolState () |
| 133 | { |
| 134 | if (tool.kind === "erase" || tool.kind === "spawner") |
| 135 | { return null; } |
| 136 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 137 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 138 | return resolveState(statesForType(catalog, layer, def.key), tool.state); |
| 139 | } |
| 140 | |
| 141 | function previewFromTool () |
| 142 | { |
| 143 | if (tool.kind === "erase") |
| 144 | { return { block: null }; } |
| 145 | if (tool.kind === "spawner") |
| 146 | { return {}; } |
| 147 | const state = placeableToolState(); |
| 148 | if (tool.kind === "ground") |
| 149 | { return { ground: { typeId: tool.typeId, state } }; } |
| 150 | return { block: { typeId: tool.typeId, state, config: null } }; |
| 151 | } |
| 152 | |
| 153 | function inEditorView (x, y) |
| 154 | { |
| 155 | return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS; |
| 156 | } |
| 157 | |
| 158 | function neighborhoodCoords (centerX, centerY) |
| 159 | { |
| 160 | const coords = []; |
| 161 | for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++) |
| 162 | { |
| 163 | for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++) |
| 164 | { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); } |
| 165 | } |
| 166 | return coords; |
| 167 | } |
| 168 | |
| 169 | function snapshotFromPayload (payload) |
| 170 | { |
| 171 | return { |
| 172 | chunkX: payload.chunkX, |
| 173 | chunkY: payload.chunkY, |
| 174 | open: payload.data.open, |
| 175 | closedEdges: payload.closedEdges, |
| 176 | grounds: payload.data.grounds, |
| 177 | blocks: payload.data.blocks, |
| 178 | light: payload.data.light, |
| 179 | entities: [] |
| 180 | }; |
| 181 | } |
| 182 | |
| 183 | function syncSpawnersOverlay (cx, cy, spawners) |
| 184 | { |
| 185 | view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId)); |
| 186 | } |
| 187 | |
| 188 | function spawnerAt (localX, localY) |
| 189 | { |
| 190 | return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null; |
| 191 | } |
| 192 | |
| 193 | function draftPersistable () |
| 194 | { |
| 195 | if (!draft) |
| 196 | { return null; } |
| 197 | return { |
| 198 | open: !!draft.open, |
| 199 | grounds: draft.grounds, |
| 200 | blocks: draft.blocks, |
| 201 | spawners: draft.spawners ?? [] |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | function captureDraftBaseline () |
| 206 | { |
| 207 | const payload = draftPersistable(); |
| 208 | draftBaseline = payload ? JSON.stringify(payload) : null; |
| 209 | syncSaveButton(); |
| 210 | } |
| 211 | |
| 212 | function isDraftDirty () |
| 213 | { |
| 214 | if (!draft || draftBaseline == null) |
| 215 | { return false; } |
| 216 | return JSON.stringify(draftPersistable()) !== draftBaseline; |
| 217 | } |
| 218 | |
| 219 | function syncSaveButton () |
| 220 | { |
| 221 | const btn = $("save"); |
| 222 | if (!btn) |
| 223 | { return; } |
| 224 | const softDeleted = isSelectedDimensionSoftDeleted(); |
| 225 | const dirty = isDraftDirty(); |
| 226 | btn.disabled = !dirty || softDeleted; |
| 227 | btn.classList.toggle("save-dirty", dirty && !softDeleted); |
| 228 | btn.title = softDeleted |
| 229 | ? "Cannot save while this dimension is soft-deleted" |
| 230 | : dirty |
| 231 | ? "Save unsaved chunk changes" |
| 232 | : "No unsaved changes"; |
| 233 | } |
| 234 | |
| 235 | function afterDraftMutation () |
| 236 | { |
| 237 | syncSaveButton(); |
| 238 | } |
| 239 | |
| 240 | function showUnsavedModal (target) |
| 241 | { |
| 242 | pendingNavigate = target; |
| 243 | $("unsaved-chunk-backdrop").hidden = false; |
| 244 | $("unsaved-chunk-modal").hidden = false; |
| 245 | } |
| 246 | |
| 247 | function hideUnsavedModal () |
| 248 | { |
| 249 | $("unsaved-chunk-backdrop").hidden = true; |
| 250 | $("unsaved-chunk-modal").hidden = true; |
| 251 | } |
| 252 | |
| 253 | function saveSelectedChunk () |
| 254 | { |
| 255 | if (!draft || !isDraftDirty()) |
| 256 | { return false; } |
| 257 | if (isSelectedDimensionSoftDeleted()) |
| 258 | { |
| 259 | $("error").textContent = "Cannot save while this dimension is soft-deleted."; |
| 260 | return false; |
| 261 | } |
| 262 | $("error").textContent = ""; |
| 263 | $("apply-status").textContent = ""; |
| 264 | $("apply-status").className = "hint"; |
| 265 | socket.send({ |
| 266 | type: MessageType.editorSaveChunk, |
| 267 | chunkX, |
| 268 | chunkY, |
| 269 | dimensionId: selectedDimensionId, |
| 270 | draft: { |
| 271 | open: $("open").checked, |
| 272 | grounds: draft.grounds, |
| 273 | blocks: draft.blocks, |
| 274 | spawners: draft.spawners ?? [] |
| 275 | } |
| 276 | }); |
| 277 | requestNeighbors(); |
| 278 | return true; |
| 279 | } |
| 280 | |
| 281 | function isSelectedDimensionSoftDeleted () |
| 282 | { |
| 283 | const record = dimensionsById.get(selectedDimensionId); |
| 284 | return record?.deletedAt != null; |
| 285 | } |
| 286 | |
| 287 | function formatPurgeHint (record) |
| 288 | { |
| 289 | if (!record?.purgeAfter) |
| 290 | { return "Soft-deleted — painting disabled."; } |
| 291 | const when = new Date(record.purgeAfter); |
| 292 | return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`; |
| 293 | } |
| 294 | |
| 295 | function syncDimensionUi () |
| 296 | { |
| 297 | const record = dimensionsById.get(selectedDimensionId); |
| 298 | const softDeleted = record?.deletedAt != null; |
| 299 | const hint = $("dimension-purge-hint"); |
| 300 | if (hint) |
| 301 | { |
| 302 | hint.hidden = !softDeleted; |
| 303 | hint.textContent = softDeleted ? formatPurgeHint(record) : ""; |
| 304 | } |
| 305 | const openToggle = $("open"); |
| 306 | if (openToggle) |
| 307 | { openToggle.disabled = softDeleted; } |
| 308 | dimensionCombo?.setValue(selectedDimensionId); |
| 309 | dimensionSettings?.refresh(); |
| 310 | syncSaveButton(); |
| 311 | } |
| 312 | |
| 313 | function applyDimensionsList (payload) |
| 314 | { |
| 315 | const list = Array.isArray(payload?.dimensions) ? payload.dimensions : []; |
| 316 | dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim])); |
| 317 | if (!dimensionsById.has(OVERWORLD_ID)) |
| 318 | { |
| 319 | dimensionsById.set(OVERWORLD_ID, { |
| 320 | dimensionId: OVERWORLD_ID, |
| 321 | displayName: "Overworld", |
| 322 | lightingMode: "dayNight", |
| 323 | seasonMode: "auto", |
| 324 | defaultGroundTypeId: 1, |
| 325 | deletedAt: null, |
| 326 | purgeAfter: null |
| 327 | }); |
| 328 | } |
| 329 | const options = [...dimensionsById.values()].map((dim) => ({ |
| 330 | id: dim.dimensionId, |
| 331 | label: dim.displayName || dim.dimensionId, |
| 332 | disabled: dim.deletedAt != null, |
| 333 | hint: dim.deletedAt != null ? formatPurgeHint(dim) : null |
| 334 | })); |
| 335 | dimensionCombo?.setOptions(options); |
| 336 | const createdId = pendingCreatedDimensionId; |
| 337 | pendingCreatedDimensionId = null; |
| 338 | if (createdId && dimensionsById.has(createdId)) |
| 339 | { |
| 340 | setRevisionState({ |
| 341 | activeRevisionId: payload.activeRevisionId, |
| 342 | pendingRevisionId: payload.pendingRevisionId |
| 343 | }); |
| 344 | selectDimension(createdId, { force: true }); |
| 345 | return; |
| 346 | } |
| 347 | if (!dimensionsById.has(selectedDimensionId)) |
| 348 | { selectedDimensionId = OVERWORLD_ID; } |
| 349 | setRevisionState({ |
| 350 | activeRevisionId: payload.activeRevisionId, |
| 351 | pendingRevisionId: payload.pendingRevisionId |
| 352 | }); |
| 353 | syncDimensionUi(); |
| 354 | if (!isDraftDirty()) |
| 355 | { requestChunks(neighborhoodCoords(chunkX, chunkY)); } |
| 356 | } |
| 357 | |
| 358 | function requestDimensions () |
| 359 | { |
| 360 | socket.send({ type: MessageType.editorListDimensions }); |
| 361 | } |
| 362 | |
| 363 | function selectDimension (dimensionId, { force = false } = {}) |
| 364 | { |
| 365 | const nextId = normalizeDimensionId(dimensionId); |
| 366 | if (!force && nextId === selectedDimensionId) |
| 367 | { return; } |
| 368 | if (!force && isDraftDirty()) |
| 369 | { |
| 370 | showUnsavedModal({ chunkX, chunkY, dimensionId: nextId }); |
| 371 | dimensionCombo?.setValue(selectedDimensionId); |
| 372 | return; |
| 373 | } |
| 374 | selectedDimensionId = nextId; |
| 375 | syncDimensionUi(); |
| 376 | clearNeighborhoodView(); |
| 377 | doLoadNeighborhood(chunkX, chunkY); |
| 378 | } |
| 379 | |
| 380 | function clearNeighborhoodView () |
| 381 | { |
| 382 | draft = null; |
| 383 | draftBaseline = null; |
| 384 | if (!view) |
| 385 | { return; } |
| 386 | for (const key of [...view.chunks.keys()]) |
| 387 | { |
| 388 | const [x, y] = key.split(",").map(Number); |
| 389 | view.removeChunk(x, y); |
| 390 | } |
| 391 | view.clearEditorSpawners?.(); |
| 392 | syncSaveButton(); |
| 393 | } |
| 394 | |
| 395 | function paintAt (localX, localY) |
| 396 | { |
| 397 | if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 398 | { return; } |
| 399 | if (isSelectedDimensionSoftDeleted()) |
| 400 | { return; } |
| 401 | const index = localY * CHUNK_SIZE + localX; |
| 402 | const state = placeableToolState(); |
| 403 | if (tool.kind === "ground") |
| 404 | { draft.grounds[index] = { typeId: tool.typeId, state }; } |
| 405 | else if (tool.kind === "erase") |
| 406 | { |
| 407 | const removed = draft.blocks[index]; |
| 408 | draft.blocks[index] = null; |
| 409 | view.updateAuthoredTile(chunkX, chunkY, localX, localY, { |
| 410 | ground: draft.grounds[index], |
| 411 | block: draft.blocks[index], |
| 412 | light: draft.light[index] |
| 413 | }); |
| 414 | if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId])) |
| 415 | { refreshNeighborConnect(localX, localY, removed.typeId); } |
| 416 | afterDraftMutation(); |
| 417 | return; |
| 418 | } |
| 419 | else if (tool.kind === "spawner") |
| 420 | { |
| 421 | const existing = spawnerAt(localX, localY); |
| 422 | const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`; |
| 423 | const entry = { |
| 424 | localX, |
| 425 | localY, |
| 426 | config: normalizeSpawnerConfig({ |
| 427 | ...defaultSpawnerConfig(spawnerId, tool.mobTypeId), |
| 428 | ...(existing?.config ?? {}), |
| 429 | spawnerId, |
| 430 | mobTypeId: tool.mobTypeId |
| 431 | }, spawnerId) |
| 432 | }; |
| 433 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY); |
| 434 | draft.spawners.push(entry); |
| 435 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 436 | afterDraftMutation(); |
| 437 | return; |
| 438 | } |
| 439 | else |
| 440 | { |
| 441 | const def = BLOCK_DEFINITIONS[tool.typeId]; |
| 442 | let nextState = definitionUsesNeighborConnect(def) |
| 443 | ? composeNeighborConnectState(def, state, 0) |
| 444 | : state; |
| 445 | if (def?.id === BlockType.flower) |
| 446 | { nextState = flowerBlockState(randomFlowerColorId()); } |
| 447 | const config = def?.id === BlockType.doorway |
| 448 | ? { |
| 449 | targetDimensionId: selectedDimensionId, |
| 450 | tileX: chunkX * CHUNK_SIZE + localX, |
| 451 | tileY: chunkY * CHUNK_SIZE + localY |
| 452 | } |
| 453 | : null; |
| 454 | if (def?.id === BlockType.doorway && !nextState) |
| 455 | { nextState = "door"; } |
| 456 | draft.blocks[index] = { typeId: tool.typeId, state: nextState, config }; |
| 457 | view.updateAuthoredTile(chunkX, chunkY, localX, localY, { |
| 458 | ground: draft.grounds[index], |
| 459 | block: draft.blocks[index], |
| 460 | light: draft.light[index] |
| 461 | }); |
| 462 | if (definitionUsesNeighborConnect(def)) |
| 463 | { refreshNeighborConnect(localX, localY, tool.typeId); } |
| 464 | afterDraftMutation(); |
| 465 | return; |
| 466 | } |
| 467 | view.updateAuthoredTile(chunkX, chunkY, localX, localY, { |
| 468 | ground: draft.grounds[index], |
| 469 | block: draft.blocks[index], |
| 470 | light: draft.light[index] |
| 471 | }); |
| 472 | afterDraftMutation(); |
| 473 | } |
| 474 | |
| 475 | /** Recompute neighbor-connect masks for a type around a local tile (same chunk). */ |
| 476 | function refreshNeighborConnect (localX, localY, typeId) |
| 477 | { |
| 478 | const def = BLOCK_DEFINITIONS[typeId]; |
| 479 | if (!draft || !definitionUsesNeighborConnect(def)) |
| 480 | { return; } |
| 481 | const cells = [[localX, localY]]; |
| 482 | for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]]) |
| 483 | { cells.push([localX + dx, localY + dy]); } |
| 484 | for (const [lx, ly] of cells) |
| 485 | { |
| 486 | if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE) |
| 487 | { continue; } |
| 488 | const index = ly * CHUNK_SIZE + lx; |
| 489 | const block = draft.blocks[index]; |
| 490 | if (!block || block.typeId !== typeId) |
| 491 | { continue; } |
| 492 | const mask = computeNeighborConnectMask((dx, dy) => |
| 493 | { |
| 494 | const nx = lx + dx; |
| 495 | const ny = ly + dy; |
| 496 | if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE) |
| 497 | { return false; } |
| 498 | const neighbor = draft.blocks[ny * CHUNK_SIZE + nx]; |
| 499 | return neighborConnectBlocksMatch(block, neighbor, def); |
| 500 | }); |
| 501 | block.state = composeNeighborConnectState(def, block.state, mask); |
| 502 | view.updateAuthoredTile(chunkX, chunkY, lx, ly, { |
| 503 | ground: draft.grounds[index], |
| 504 | block: draft.blocks[index], |
| 505 | light: draft.light[index] |
| 506 | }); |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | function updateRevisionUI () |
| 511 | { |
| 512 | const applyBtn = $("apply"); |
| 513 | $("revision").textContent = `active ${activeRevisionId ?? "?"}` + |
| 514 | (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision"); |
| 515 | if (applyBtn) |
| 516 | { |
| 517 | applyBtn.disabled = !pendingRevisionId || applyInFlight; |
| 518 | applyBtn.title = pendingRevisionId |
| 519 | ? "Reload the live world with the pending map revision" |
| 520 | : "Save a chunk first to create a pending revision"; |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending }) |
| 525 | { |
| 526 | if (active != null) |
| 527 | { activeRevisionId = active; } |
| 528 | pendingRevisionId = pending ?? null; |
| 529 | updateRevisionUI(); |
| 530 | } |
| 531 | |
| 532 | function showSelectedChunk (payload) |
| 533 | { |
| 534 | draft = { |
| 535 | open: payload.data.open, |
| 536 | grounds: payload.data.grounds.map((ground) => normalizeGround(ground)), |
| 537 | blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)), |
| 538 | light: payload.data.light.slice(), |
| 539 | spawners: (payload.data.spawners ?? []).map((entry) => ({ |
| 540 | localX: entry.localX, |
| 541 | localY: entry.localY, |
| 542 | config: { ...entry.config } |
| 543 | })) |
| 544 | }; |
| 545 | $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; |
| 546 | $("open").checked = draft.open; |
| 547 | setRevisionState({ |
| 548 | activeRevisionId: payload.activeRevisionId, |
| 549 | pendingRevisionId: payload.pendingRevisionId |
| 550 | }); |
| 551 | $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)"; |
| 552 | const log = $("changelog"); |
| 553 | log.innerHTML = ""; |
| 554 | for (const entry of payload.changelog ?? []) |
| 555 | { |
| 556 | const item = document.createElement("article"); |
| 557 | item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`; |
| 558 | const list = document.createElement("ul"); |
| 559 | for (const bullet of entry.diffEntries) |
| 560 | { |
| 561 | const li = document.createElement("li"); |
| 562 | li.textContent = bullet; |
| 563 | list.append(li); |
| 564 | } |
| 565 | item.append(list); |
| 566 | log.append(item); |
| 567 | } |
| 568 | view.applySnapshot(snapshotFromPayload(payload)); |
| 569 | syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners); |
| 570 | captureDraftBaseline(); |
| 571 | if (navigateAfterSave && pendingNavigate) |
| 572 | { |
| 573 | const next = pendingNavigate; |
| 574 | navigateAfterSave = false; |
| 575 | pendingNavigate = null; |
| 576 | const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; |
| 577 | if (nextDim !== selectedDimensionId) |
| 578 | { |
| 579 | selectedDimensionId = nextDim; |
| 580 | syncDimensionUi(); |
| 581 | clearNeighborhoodView(); |
| 582 | } |
| 583 | doLoadNeighborhood(next.chunkX, next.chunkY); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | function pruneView () |
| 588 | { |
| 589 | for (const key of [...view.chunks.keys()]) |
| 590 | { |
| 591 | const [x, y] = key.split(",").map(Number); |
| 592 | if (!inEditorView(x, y)) |
| 593 | { view.removeChunk(x, y); } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | function frameNeighborhood () |
| 598 | { |
| 599 | const size = view.tileSize(); |
| 600 | view.followPlayer = false; |
| 601 | const centerX = (chunkX + 0.5) * CHUNK_SIZE * size; |
| 602 | const centerY = (chunkY + 0.5) * CHUNK_SIZE * size; |
| 603 | view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX; |
| 604 | view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY; |
| 605 | updateSelectionBorder(); |
| 606 | } |
| 607 | |
| 608 | function updateSelectionBorder () |
| 609 | { |
| 610 | const border = $("selection-border"); |
| 611 | const canvas = scene?.canvas; |
| 612 | if (!border || !canvas) |
| 613 | { return; } |
| 614 | |
| 615 | const rect = canvas.getBoundingClientRect(); |
| 616 | const size = view.tileSize(); |
| 617 | const chunkPx = CHUNK_SIZE * size; |
| 618 | const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x; |
| 619 | const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y; |
| 620 | border.style.left = `${rect.left + screenLeft}px`; |
| 621 | border.style.top = `${rect.top + screenTop}px`; |
| 622 | border.style.width = `${chunkPx}px`; |
| 623 | border.style.height = `${chunkPx}px`; |
| 624 | } |
| 625 | |
| 626 | function layoutScene () |
| 627 | { |
| 628 | const header = document.querySelector("body > header"); |
| 629 | const aside = document.querySelector("body > aside"); |
| 630 | const changelog = $("changelog-wrap"); |
| 631 | const top = header.offsetHeight; |
| 632 | aside.style.top = `${top}px`; |
| 633 | changelog.style.top = `${top}px`; |
| 634 | const left = aside.offsetWidth; |
| 635 | const right = changelog.offsetWidth; |
| 636 | const width = Math.max(64, window.innerWidth - left - right); |
| 637 | const height = Math.max(64, window.innerHeight - top); |
| 638 | scene.position.x = left; |
| 639 | scene.position.y = top; |
| 640 | scene.size.x = width; |
| 641 | scene.size.y = height; |
| 642 | scene.g_fixSize(); |
| 643 | useNearestNeighbour(scene, game.images); |
| 644 | const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX); |
| 645 | if (editorZoom == null) |
| 646 | { editorZoom = fit; } |
| 647 | else |
| 648 | { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); } |
| 649 | view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); |
| 650 | frameNeighborhood(); |
| 651 | } |
| 652 | |
| 653 | function zoomEditor (direction) |
| 654 | { |
| 655 | if (!view) |
| 656 | { return; } |
| 657 | const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP; |
| 658 | editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor)); |
| 659 | view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); |
| 660 | useNearestNeighbour(scene, game.images); |
| 661 | frameNeighborhood(); |
| 662 | } |
| 663 | |
| 664 | function requestChunks (coords) |
| 665 | { |
| 666 | for (const coord of coords) |
| 667 | { |
| 668 | socket.send({ |
| 669 | type: MessageType.editorLoadChunk, |
| 670 | chunkX: coord.chunkX, |
| 671 | chunkY: coord.chunkY, |
| 672 | dimensionId: selectedDimensionId |
| 673 | }); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | function doLoadNeighborhood (x, y) |
| 678 | { |
| 679 | chunkX = x; |
| 680 | chunkY = y; |
| 681 | $("coords").textContent = `${chunkX}, ${chunkY}`; |
| 682 | requestChunks(neighborhoodCoords(x, y)); |
| 683 | } |
| 684 | |
| 685 | function loadNeighborhood (x, y) |
| 686 | { |
| 687 | if ((x !== chunkX || y !== chunkY) && isDraftDirty()) |
| 688 | { |
| 689 | showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId }); |
| 690 | return; |
| 691 | } |
| 692 | doLoadNeighborhood(x, y); |
| 693 | } |
| 694 | |
| 695 | function requestNeighbors () |
| 696 | { |
| 697 | requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); |
| 698 | } |
| 699 | |
| 700 | function anyModalOpen () |
| 701 | { |
| 702 | return settingsModal?.isOpen() |
| 703 | || paletteModal?.isOpen() |
| 704 | || tileConfigModal?.isOpen() |
| 705 | || questsModal?.isOpen() |
| 706 | || dialoguesModal?.isOpen() |
| 707 | || !$("unsaved-chunk-modal")?.hidden; |
| 708 | } |
| 709 | |
| 710 | function updateHoverStatus (local) |
| 711 | { |
| 712 | const el = $("hover-status-text"); |
| 713 | if (!el) |
| 714 | { return; } |
| 715 | if (!local) |
| 716 | { |
| 717 | el.textContent = "Hover a tile for coordinates"; |
| 718 | return; |
| 719 | } |
| 720 | const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE); |
| 721 | const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE); |
| 722 | el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`; |
| 723 | } |
| 724 | |
| 725 | function updateTooltip (local, options = {}) |
| 726 | { |
| 727 | if (!options.keepStatus) |
| 728 | { updateHoverStatus(local); } |
| 729 | const tip = $("tile-tooltip"); |
| 730 | if (!tip || !local || !draft) |
| 731 | { |
| 732 | if (tip) |
| 733 | { tip.hidden = true; } |
| 734 | view?.clearSpawnRangeHighlight(); |
| 735 | return; |
| 736 | } |
| 737 | const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]); |
| 738 | const spawner = spawnerAt(local.x, local.y); |
| 739 | const lines = []; |
| 740 | if (block) |
| 741 | { |
| 742 | const def = BLOCK_DEFINITIONS[block.typeId]; |
| 743 | lines.push(def?.displayName ?? `Block ${block.typeId}`); |
| 744 | if (block.config && Object.keys(block.config).length) |
| 745 | { |
| 746 | for (const [key, value] of Object.entries(block.config)) |
| 747 | { lines.push(`${key}: ${value}`); } |
| 748 | } |
| 749 | } |
| 750 | if (spawner) |
| 751 | { |
| 752 | const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId); |
| 753 | const mob = mobDefinition(config.mobTypeId); |
| 754 | lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`); |
| 755 | lines.push(`maxAlive: ${config.maxAlive}`); |
| 756 | lines.push(`spawnRange: ${config.spawnRangeTiles}`); |
| 757 | lines.push(`wanderRange: ${config.maxWanderRangeTiles}`); |
| 758 | lines.push(`id: ${config.spawnerId}`); |
| 759 | view.setSpawnRangeHighlight( |
| 760 | local.tileX, |
| 761 | local.tileY, |
| 762 | config.spawnRangeTiles, |
| 763 | config.maxWanderRangeTiles |
| 764 | ); |
| 765 | } |
| 766 | else |
| 767 | { view.clearSpawnRangeHighlight(); } |
| 768 | if (!lines.length) |
| 769 | { |
| 770 | tip.hidden = true; |
| 771 | return; |
| 772 | } |
| 773 | tip.hidden = false; |
| 774 | tip.textContent = lines.join("\n"); |
| 775 | const canvas = scene.canvas; |
| 776 | const rect = canvas.getBoundingClientRect(); |
| 777 | const size = view.tileSize(); |
| 778 | const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size; |
| 779 | const screenY = local.tileY * size + scene.cameraPosition.y + rect.top; |
| 780 | tip.style.left = `${screenX}px`; |
| 781 | tip.style.top = `${screenY}px`; |
| 782 | } |
| 783 | |
| 784 | async function main () |
| 785 | { |
| 786 | catalog = await loadSpriteCatalog(); |
| 787 | imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url])); |
| 788 | await preloadCatalogImages(game, catalog); |
| 789 | applySpriteSheets(game.images, catalog); |
| 790 | scene = new Scene(250, 56, 64, 64); |
| 791 | game.loadScene(scene); |
| 792 | useNearestNeighbour(scene, game.images); |
| 793 | view = new WorldView(game, scene, catalog); |
| 794 | view.followPlayer = false; |
| 795 | syncSeasonControls(view.worldSeason ?? seasonIdAt()); |
| 796 | layoutScene(); |
| 797 | selectTool(tool); |
| 798 | $("tool").textContent = selectedToolLabel(); |
| 799 | |
| 800 | paletteModal = initPaletteModal({ |
| 801 | catalog, |
| 802 | imageUrlFor (name) |
| 803 | { |
| 804 | const sprite = game.images[name]; |
| 805 | const html = sprite?.g_image; |
| 806 | if (html && typeof html.toDataURL === "function") |
| 807 | { |
| 808 | try |
| 809 | { return html.toDataURL("image/png"); } |
| 810 | catch (_) |
| 811 | { /* fall through */ } |
| 812 | } |
| 813 | return imageUrlByName.get(name) ?? null; |
| 814 | }, |
| 815 | onSelect (next) |
| 816 | { |
| 817 | selectTool(next); |
| 818 | $("tool").textContent = selectedToolLabel(); |
| 819 | } |
| 820 | }); |
| 821 | |
| 822 | tileConfigModal = initTileConfigModal({ |
| 823 | socket: { |
| 824 | send (payload) |
| 825 | { |
| 826 | socket?.send(payload); |
| 827 | } |
| 828 | }, |
| 829 | MessageType, |
| 830 | getDialogues: () => dialoguesModal?.getDialogues?.() ?? [], |
| 831 | getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({ |
| 832 | id: dim.dimensionId, |
| 833 | label: dim.displayName || dim.dimensionId, |
| 834 | disabled: !!dim.deletedAt, |
| 835 | hint: dim.deletedAt ? "soft-deleted" : undefined |
| 836 | })), |
| 837 | onSave (ctx, config) |
| 838 | { |
| 839 | if (!draft) |
| 840 | { return; } |
| 841 | if (ctx.kind === "doorway") |
| 842 | { |
| 843 | const index = ctx.localY * CHUNK_SIZE + ctx.localX; |
| 844 | draft.blocks[index] = { |
| 845 | typeId: BlockType.doorway, |
| 846 | state: config.state || "door", |
| 847 | config: { |
| 848 | targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID), |
| 849 | tileX: Number(config.tileX) || 0, |
| 850 | tileY: Number(config.tileY) || 0 |
| 851 | } |
| 852 | }; |
| 853 | view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { |
| 854 | ground: draft.grounds[index], |
| 855 | block: draft.blocks[index], |
| 856 | light: draft.light[index] |
| 857 | }); |
| 858 | afterDraftMutation(); |
| 859 | return; |
| 860 | } |
| 861 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); |
| 862 | draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config }); |
| 863 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 864 | afterDraftMutation(); |
| 865 | }, |
| 866 | onRemove (ctx) |
| 867 | { |
| 868 | if (!draft) |
| 869 | { return; } |
| 870 | if (ctx.kind === "doorway") |
| 871 | { |
| 872 | const index = ctx.localY * CHUNK_SIZE + ctx.localX; |
| 873 | draft.blocks[index] = null; |
| 874 | view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, { |
| 875 | ground: draft.grounds[index], |
| 876 | block: draft.blocks[index], |
| 877 | light: draft.light[index] |
| 878 | }); |
| 879 | afterDraftMutation(); |
| 880 | return; |
| 881 | } |
| 882 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); |
| 883 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 884 | afterDraftMutation(); |
| 885 | } |
| 886 | }); |
| 887 | |
| 888 | const ticker = new GameObject(0, 0, null, 10); |
| 889 | ticker.update = (dt) => |
| 890 | { |
| 891 | hoverLocal = null; |
| 892 | const canvas = scene.canvas; |
| 893 | const rect = canvas.getBoundingClientRect(); |
| 894 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 895 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 896 | const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height; |
| 897 | if (overCanvas && draft && !anyModalOpen()) |
| 898 | { |
| 899 | const tile = view.screenToTile(mouseX, mouseY); |
| 900 | const localX = tile.tileX - chunkX * CHUNK_SIZE; |
| 901 | const localY = tile.tileY - chunkY * CHUNK_SIZE; |
| 902 | const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE); |
| 903 | const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE); |
| 904 | updateHoverStatus({ |
| 905 | tileX: tile.tileX, |
| 906 | tileY: tile.tileY, |
| 907 | x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE, |
| 908 | y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE, |
| 909 | chunkX: hoverChunkX, |
| 910 | chunkY: hoverChunkY |
| 911 | }); |
| 912 | if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE) |
| 913 | { |
| 914 | hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY }; |
| 915 | view.setTilePreview(tile.tileX, tile.tileY, previewFromTool()); |
| 916 | updateTooltip(hoverLocal); |
| 917 | if (GameInput.mouseHeld(GameInput.MouseButtons.Left)) |
| 918 | { paintAt(localX, localY); } |
| 919 | } |
| 920 | else |
| 921 | { |
| 922 | hoverLocal = null; |
| 923 | view.clearTilePreview(); |
| 924 | updateTooltip(null, { keepStatus: true }); |
| 925 | } |
| 926 | } |
| 927 | else |
| 928 | { |
| 929 | view.clearTilePreview(); |
| 930 | updateTooltip(null); |
| 931 | } |
| 932 | view.update(dt); |
| 933 | frameNeighborhood(); |
| 934 | }; |
| 935 | scene.addObject(ticker); |
| 936 | window.addEventListener("resize", layoutScene); |
| 937 | |
| 938 | socket = new GameSocket(defaultSocketUrl(), (message) => |
| 939 | { |
| 940 | if (message.type === MessageType.session) |
| 941 | { |
| 942 | $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`; |
| 943 | socket.send({ type: MessageType.editorLoadSettings }); |
| 944 | requestDimensions(); |
| 945 | loadNeighborhood(0, 0); |
| 946 | } |
| 947 | else if (message.type === MessageType.editorSettings) |
| 948 | { settingsModal.handleMessage(message); } |
| 949 | else if (message.type === MessageType.editorDimensions) |
| 950 | { |
| 951 | applyDimensionsList(message); |
| 952 | } |
| 953 | else if (message.type === MessageType.editorQuests) |
| 954 | { questsModal?.handleMessage(message); } |
| 955 | else if (message.type === MessageType.editorDialogues) |
| 956 | { |
| 957 | dialoguesModal?.handleMessage(message); |
| 958 | tileConfigModal?.handleMessage(message); |
| 959 | } |
| 960 | else if (message.type === MessageType.editorChunk) |
| 961 | { |
| 962 | const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID); |
| 963 | if (msgDim !== selectedDimensionId) |
| 964 | { return; } |
| 965 | if (message.settings) |
| 966 | { view.setSettings(message.settings); } |
| 967 | if (!inEditorView(message.chunkX, message.chunkY)) |
| 968 | { return; } |
| 969 | if (message.chunkX === chunkX && message.chunkY === chunkY) |
| 970 | { showSelectedChunk(message); } |
| 971 | else |
| 972 | { |
| 973 | view.applySnapshot(snapshotFromPayload(message)); |
| 974 | syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners); |
| 975 | } |
| 976 | pruneView(); |
| 977 | } |
| 978 | else if (message.type === MessageType.editorRevisionApplied) |
| 979 | { |
| 980 | applyInFlight = false; |
| 981 | setRevisionState({ |
| 982 | activeRevisionId: message.activeRevisionId, |
| 983 | pendingRevisionId: message.pendingRevisionId |
| 984 | }); |
| 985 | const status = $("apply-status"); |
| 986 | status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`; |
| 987 | status.className = "hint ok"; |
| 988 | requestDimensions(); |
| 989 | requestChunks(neighborhoodCoords(chunkX, chunkY)); |
| 990 | } |
| 991 | else if (message.type === MessageType.error) |
| 992 | { |
| 993 | $("error").textContent = message.message; |
| 994 | pendingCreatedDimensionId = null; |
| 995 | navigateAfterSave = false; |
| 996 | dimensionCombo?.setValue(selectedDimensionId); |
| 997 | if (applyInFlight) |
| 998 | { |
| 999 | applyInFlight = false; |
| 1000 | $("apply-status").textContent = ""; |
| 1001 | $("apply-status").className = "hint"; |
| 1002 | updateRevisionUI(); |
| 1003 | } |
| 1004 | } |
| 1005 | }); |
| 1006 | settingsModal = initSettingsModal({ |
| 1007 | socket, |
| 1008 | MessageType, |
| 1009 | onApplied (settings) |
| 1010 | { |
| 1011 | view.setSettings(settings); |
| 1012 | }, |
| 1013 | onPreviewNight (hour) |
| 1014 | { |
| 1015 | view.nightPreview = hour; |
| 1016 | $("night").value = String(hour); |
| 1017 | $("night-label").textContent = Number(hour).toFixed(1); |
| 1018 | } |
| 1019 | }); |
| 1020 | dimensionCombo = createDimensionCombobox({ |
| 1021 | root: $("dimension-combo"), |
| 1022 | allowCreate: true, |
| 1023 | placeholder: "Search or create dimension…", |
| 1024 | onSelect (id) |
| 1025 | { |
| 1026 | selectDimension(id); |
| 1027 | }, |
| 1028 | onCreate (rawId) |
| 1029 | { |
| 1030 | const id = normalizeDimensionId(rawId); |
| 1031 | $("error").textContent = ""; |
| 1032 | pendingCreatedDimensionId = id; |
| 1033 | socket.send({ |
| 1034 | type: MessageType.editorCreateDimension, |
| 1035 | dimensionId: id, |
| 1036 | displayName: rawId.trim() |
| 1037 | }); |
| 1038 | } |
| 1039 | }); |
| 1040 | dimensionCombo.setOptions([{ |
| 1041 | id: OVERWORLD_ID, |
| 1042 | label: "Overworld" |
| 1043 | }]); |
| 1044 | dimensionCombo.setValue(OVERWORLD_ID); |
| 1045 | dimensionSettings = initDimensionSettings({ |
| 1046 | socket, |
| 1047 | MessageType, |
| 1048 | GROUND_DEFINITIONS, |
| 1049 | OVERWORLD_ID, |
| 1050 | getSelectedDimensionId: () => selectedDimensionId, |
| 1051 | getDimensionRecord: (id) => dimensionsById.get(id) ?? null, |
| 1052 | isOverworld |
| 1053 | }); |
| 1054 | questsModal = initQuestsModal({ socket, MessageType }); |
| 1055 | dialoguesModal = initDialoguesModal({ socket, MessageType }); |
| 1056 | game.startGame(); |
| 1057 | await socket.connect(); |
| 1058 | } |
| 1059 | |
| 1060 | $("tool").textContent = selectedToolLabel(); |
| 1061 | $("tool-erase").addEventListener("click", () => |
| 1062 | { |
| 1063 | selectTool({ kind: "erase" }); |
| 1064 | $("tool").textContent = selectedToolLabel(); |
| 1065 | }); |
| 1066 | |
| 1067 | $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1)); |
| 1068 | $("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1)); |
| 1069 | $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY)); |
| 1070 | $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY)); |
| 1071 | $("open").addEventListener("change", () => |
| 1072 | { |
| 1073 | if (isSelectedDimensionSoftDeleted()) |
| 1074 | { |
| 1075 | $("open").checked = !!draft?.open; |
| 1076 | return; |
| 1077 | } |
| 1078 | if (draft) |
| 1079 | { |
| 1080 | draft.open = $("open").checked; |
| 1081 | view.setChunkOpen(chunkX, chunkY, draft.open); |
| 1082 | afterDraftMutation(); |
| 1083 | } |
| 1084 | }); |
| 1085 | $("save").addEventListener("click", () => |
| 1086 | { |
| 1087 | saveSelectedChunk(); |
| 1088 | }); |
| 1089 | $("unsaved-chunk-cancel")?.addEventListener("click", () => |
| 1090 | { |
| 1091 | pendingNavigate = null; |
| 1092 | navigateAfterSave = false; |
| 1093 | hideUnsavedModal(); |
| 1094 | }); |
| 1095 | $("unsaved-chunk-backdrop")?.addEventListener("click", () => |
| 1096 | { |
| 1097 | pendingNavigate = null; |
| 1098 | navigateAfterSave = false; |
| 1099 | hideUnsavedModal(); |
| 1100 | }); |
| 1101 | $("unsaved-chunk-discard")?.addEventListener("click", () => |
| 1102 | { |
| 1103 | const next = pendingNavigate; |
| 1104 | hideUnsavedModal(); |
| 1105 | pendingNavigate = null; |
| 1106 | navigateAfterSave = false; |
| 1107 | if (!next) |
| 1108 | { return; } |
| 1109 | const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; |
| 1110 | if (nextDim !== selectedDimensionId) |
| 1111 | { |
| 1112 | selectedDimensionId = nextDim; |
| 1113 | syncDimensionUi(); |
| 1114 | clearNeighborhoodView(); |
| 1115 | } |
| 1116 | doLoadNeighborhood(next.chunkX, next.chunkY); |
| 1117 | }); |
| 1118 | $("unsaved-chunk-save")?.addEventListener("click", () => |
| 1119 | { |
| 1120 | hideUnsavedModal(); |
| 1121 | if (!pendingNavigate) |
| 1122 | { return; } |
| 1123 | navigateAfterSave = true; |
| 1124 | if (!saveSelectedChunk()) |
| 1125 | { |
| 1126 | navigateAfterSave = false; |
| 1127 | const next = pendingNavigate; |
| 1128 | pendingNavigate = null; |
| 1129 | if (next) |
| 1130 | { |
| 1131 | const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId; |
| 1132 | if (nextDim !== selectedDimensionId) |
| 1133 | { |
| 1134 | selectedDimensionId = nextDim; |
| 1135 | syncDimensionUi(); |
| 1136 | clearNeighborhoodView(); |
| 1137 | } |
| 1138 | doLoadNeighborhood(next.chunkX, next.chunkY); |
| 1139 | } |
| 1140 | } |
| 1141 | }); |
| 1142 | $("apply").addEventListener("click", () => |
| 1143 | { |
| 1144 | if (!pendingRevisionId || applyInFlight) |
| 1145 | { return; } |
| 1146 | $("error").textContent = ""; |
| 1147 | const status = $("apply-status"); |
| 1148 | status.textContent = "Applying…"; |
| 1149 | status.className = "hint"; |
| 1150 | applyInFlight = true; |
| 1151 | updateRevisionUI(); |
| 1152 | socket.send({ type: MessageType.editorApplyRevision }); |
| 1153 | }); |
| 1154 | $("night").addEventListener("input", () => |
| 1155 | { |
| 1156 | view.nightPreview = Number($("night").value); |
| 1157 | $("night-label").textContent = view.nightPreview.toFixed(1); |
| 1158 | }); |
| 1159 | $("season").addEventListener("change", () => |
| 1160 | { |
| 1161 | applySeasonPreview($("season").value); |
| 1162 | }); |
| 1163 | |
| 1164 | function syncSeasonControls (season) |
| 1165 | { |
| 1166 | const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer |
| 1167 | ? season |
| 1168 | : seasonIdAt(); |
| 1169 | $("season").value = next; |
| 1170 | view?.setWorldSeason(next); |
| 1171 | } |
| 1172 | |
| 1173 | function applySeasonPreview (season) |
| 1174 | { |
| 1175 | syncSeasonControls(season); |
| 1176 | } |
| 1177 | |
| 1178 | function cycleToolState (direction) |
| 1179 | { |
| 1180 | if (tool.kind === "erase" || tool.kind === "spawner") |
| 1181 | { return; } |
| 1182 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 1183 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 1184 | if (definitionUsesNeighborConnect(def)) |
| 1185 | { return; } |
| 1186 | if (tool.kind === "block" && def?.id === BlockType.flower) |
| 1187 | { return; } |
| 1188 | const allStates = statesForType(catalog, layer, def.key); |
| 1189 | const seasonal = seasonalCycleStates(allStates); |
| 1190 | const states = seasonal ?? placeableStatesForType(catalog, layer, def.key); |
| 1191 | if (states.length < 2) |
| 1192 | { return; } |
| 1193 | tool.state = cycleState(states, tool.state, direction); |
| 1194 | $("tool").textContent = selectedToolLabel(); |
| 1195 | const season = seasonIdFromVisualState(tool.state); |
| 1196 | if (season) |
| 1197 | { applySeasonPreview(season); } |
| 1198 | if (!draft || !hoverLocal) |
| 1199 | { return; } |
| 1200 | const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x; |
| 1201 | if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId) |
| 1202 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 1203 | else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId) |
| 1204 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 1205 | } |
| 1206 | |
| 1207 | document.addEventListener("wheel", (event) => |
| 1208 | { |
| 1209 | if (!scene?.canvas || anyModalOpen()) |
| 1210 | { return; } |
| 1211 | const rect = scene.canvas.getBoundingClientRect(); |
| 1212 | if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) |
| 1213 | { return; } |
| 1214 | event.preventDefault(); |
| 1215 | if (event.shiftKey) |
| 1216 | { |
| 1217 | cycleToolState(event.deltaY < 0 ? 1 : -1); |
| 1218 | if (hoverLocal) |
| 1219 | { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); } |
| 1220 | return; |
| 1221 | } |
| 1222 | zoomEditor(event.deltaY < 0 ? 1 : -1); |
| 1223 | }, { passive: false }); |
| 1224 | |
| 1225 | document.addEventListener("contextmenu", (event) => |
| 1226 | { |
| 1227 | if (!scene?.canvas || anyModalOpen() || !draft) |
| 1228 | { return; } |
| 1229 | const rect = scene.canvas.getBoundingClientRect(); |
| 1230 | if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) |
| 1231 | { return; } |
| 1232 | event.preventDefault(); |
| 1233 | const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top); |
| 1234 | const localX = tile.tileX - chunkX * CHUNK_SIZE; |
| 1235 | const localY = tile.tileY - chunkY * CHUNK_SIZE; |
| 1236 | if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 1237 | { return; } |
| 1238 | const spawner = spawnerAt(localX, localY); |
| 1239 | if (spawner) |
| 1240 | { |
| 1241 | tileConfigModal.openSpawner({ |
| 1242 | localX, |
| 1243 | localY, |
| 1244 | tileX: tile.tileX, |
| 1245 | tileY: tile.tileY, |
| 1246 | config: { ...spawner.config } |
| 1247 | }); |
| 1248 | return; |
| 1249 | } |
| 1250 | const index = localY * CHUNK_SIZE + localX; |
| 1251 | const block = draft.blocks[index]; |
| 1252 | if (block?.typeId === BlockType.doorway) |
| 1253 | { |
| 1254 | tileConfigModal.openDoorway({ |
| 1255 | localX, |
| 1256 | localY, |
| 1257 | tileX: tile.tileX, |
| 1258 | tileY: tile.tileY, |
| 1259 | state: block.state ?? "door", |
| 1260 | config: block.config ? { ...block.config } : {} |
| 1261 | }); |
| 1262 | } |
| 1263 | }); |
| 1264 | |
| 1265 | main().catch((error) => |
| 1266 | { |
| 1267 | $("error").textContent = error.message; |
| 1268 | console.error(error); |
| 1269 | }); |