Add overworld region-zone-chunk data model and admin live world editor

This commit is contained in:
dingo
2026-02-14 13:52:36 -05:00
parent 189e5fcff4
commit 18d6fe683b
9 changed files with 6017 additions and 22 deletions
@@ -160,6 +160,10 @@
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
<span>Dungeons</span>
</a>
<a href="/admin/worldeditor" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/WorldEditor") == true ? "active" : "")" data-tooltip="World Editor">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a2 2 0 01-2.828 0L6.343 16.657m11.314 0A8 8 0 005.03 7.343m12.627 9.314A8 8 0 1112 4a8 8 0 015.657 12.657z"/></svg>
<span>World Editor</span>
</a>
<a href="/admin/players" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/Players") == true ? "active" : "")" data-tooltip="Players">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
<span>Players</span>
@@ -0,0 +1,532 @@
@page "/admin/worldeditor"
@model GameServices.Admin.Pages.WorldEditor.IndexModel
@using System.Text.Json
@{
ViewData["Title"] = "World Editor";
var regionsJson = JsonSerializer.Serialize(Model.Regions.Select(r => new
{
id = r.Id,
name = r.Name,
zonesX = r.ZonesPerRegionX,
zonesY = r.ZonesPerRegionY,
chunksPerZoneX = r.ChunksPerZoneX,
chunksPerZoneY = r.ChunksPerZoneY,
chunkWidthTiles = r.ChunkWidthTiles,
chunkHeightTiles = r.ChunkHeightTiles
}));
var sheetsJson = JsonSerializer.Serialize(Model.TileSheets.Select(s => new
{
id = s.Id,
name = s.Name,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
cols = s.Columns,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight
}));
var objectsJson = JsonSerializer.Serialize(Model.ObjectDefinitions.Select(o => new { id = o.Id, name = o.Name }));
var npcsJson = JsonSerializer.Serialize(Model.NpcDefinitions.Select(n => new { id = n.Id, name = n.Name }));
}
<div class="space-y-6">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold text-white">World Editor</h1>
<p class="text-gray-400 mt-1">Live chunk editing for tiles, objects, and NPC spawns</p>
</div>
</div>
<form id="af-form" method="post" class="hidden">
@Html.AntiForgeryToken()
</form>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
<div class="xl:col-span-3 space-y-4">
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Selection</h2>
<div>
<label class="label">Region</label>
<select id="regionId" class="input"></select>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="label">Zone X</label>
<input id="zoneX" type="number" class="input" min="0" value="@Model.SelectedZoneX" />
</div>
<div>
<label class="label">Zone Y</label>
<input id="zoneY" type="number" class="input" min="0" value="@Model.SelectedZoneY" />
</div>
<div>
<label class="label">Chunk X</label>
<input id="chunkX" type="number" class="input" min="0" value="@Model.SelectedChunkX" />
</div>
<div>
<label class="label">Chunk Y</label>
<input id="chunkY" type="number" class="input" min="0" value="@Model.SelectedChunkY" />
</div>
</div>
<div class="flex gap-2">
<button type="button" class="btn btn-primary" onclick="loadChunk()">Load Chunk</button>
<button type="button" class="btn btn-secondary" onclick="loadZone()">Load Zone</button>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Paint Mode</h2>
<div>
<label class="label">Mode</label>
<select id="paintMode" class="input" onchange="renderChunk()">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
<option value="erase">Erase</option>
</select>
</div>
<div id="eraseTargetWrap" class="hidden">
<label class="label">Erase Target</label>
<select id="eraseTarget" class="input">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
</select>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Tile Tool</h2>
<div>
<label class="label">Sprite Sheet</label>
<select id="sheetId" class="input" onchange="onSheetChanged()"></select>
</div>
<div>
<label class="label">Frame Index</label>
<input id="frameIndex" type="number" class="input" min="0" value="0" />
</div>
<div class="grid grid-cols-1 gap-2">
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isWalkable" type="checkbox" checked class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Walkable
</label>
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isInvisiblePaywall" type="checkbox" class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Invisible Paywall
</label>
</div>
<a id="tileDefLink" href="/admin/tilemaps/tiles/edit" class="text-sm text-indigo-400 hover:underline">Edit Tile Definition</a>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Object Tool</h2>
<label class="label">Object</label>
<select id="objectDefinitionId" class="input"></select>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">NPC Tool</h2>
<label class="label">NPC</label>
<select id="npcDefinitionId" class="input"></select>
</div>
</div>
<div class="xl:col-span-9 space-y-4">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Region Minimap</h2>
<canvas id="regionCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Zone Chunk Map</h2>
<canvas id="zoneCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
</div>
<div class="card p-4">
<div class="flex items-center justify-between mb-2">
<h2 class="text-lg font-semibold text-white">Chunk Canvas</h2>
<div id="chunkMeta" class="text-sm text-gray-400">No chunk loaded</div>
</div>
<canvas id="chunkCanvas" width="768" height="768" class="w-full rounded border border-gray-700 bg-gray-900 cursor-crosshair"></canvas>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
const regions = @Html.Raw(regionsJson);
const sheets = @Html.Raw(sheetsJson);
const objectDefs = @Html.Raw(objectsJson);
const npcDefs = @Html.Raw(npcsJson);
let currentRegion = null;
let currentZoneChunks = [];
let currentChunk = null;
let currentTiles = new Map();
let currentObjects = [];
let currentNpcs = [];
let pollTimer = null;
const regionCanvas = document.getElementById('regionCanvas');
const regionCtx = regionCanvas.getContext('2d');
const zoneCanvas = document.getElementById('zoneCanvas');
const zoneCtx = zoneCanvas.getContext('2d');
const chunkCanvas = document.getElementById('chunkCanvas');
const chunkCtx = chunkCanvas.getContext('2d');
function token() {
return document.querySelector('#af-form input[name="__RequestVerificationToken"]').value;
}
function key(x, y) { return `${x},${y}`; }
function initSelectors() {
const regionSel = document.getElementById('regionId');
regionSel.innerHTML = regions.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
regionSel.value = '@Model.SelectedRegionId';
regionSel.addEventListener('change', () => {
loadRegion();
});
const sheetSel = document.getElementById('sheetId');
sheetSel.innerHTML = sheets.map(s => `<option value="${s.id}">${s.name}</option>`).join('');
if (sheets.length) sheetSel.value = sheets[0].id;
onSheetChanged();
document.getElementById('objectDefinitionId').innerHTML = objectDefs.map(o => `<option value="${o.id}">${o.name}</option>`).join('');
document.getElementById('npcDefinitionId').innerHTML = npcDefs.map(n => `<option value="${n.id}">${n.name}</option>`).join('');
}
async function getJson(url) {
const res = await fetch(url);
return await res.json();
}
async function postJson(url, body) {
const params = new URLSearchParams();
for (const k of Object.keys(body)) {
const v = body[k];
if (v === undefined || v === null) continue;
params.set(k, String(v));
}
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'RequestVerificationToken': token()
},
body: params.toString()
});
return await res.json();
}
function selection() {
return {
regionId: parseInt(document.getElementById('regionId').value, 10) || 0,
zoneX: parseInt(document.getElementById('zoneX').value, 10) || 0,
zoneY: parseInt(document.getElementById('zoneY').value, 10) || 0,
chunkX: parseInt(document.getElementById('chunkX').value, 10) || 0,
chunkY: parseInt(document.getElementById('chunkY').value, 10) || 0
};
}
async function loadRegion() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Region&regionId=${s.regionId}`);
if (!data.success) return;
currentRegion = data.region;
renderRegionMap();
await loadZone();
}
async function loadZone() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Zone&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}`);
if (!data.success) return;
currentZoneChunks = data.chunks || [];
renderZoneMap();
}
async function loadChunk() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(checkChunkVersion, 2000);
}
async function checkChunkVersion() {
if (!currentChunk) return;
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
if (data.chunk.version !== currentChunk.version) {
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
loadZone();
}
}
function renderRegionMap() {
regionCtx.clearRect(0, 0, regionCanvas.width, regionCanvas.height);
if (!currentRegion) return;
const cellW = regionCanvas.width / currentRegion.zonesX;
const cellH = regionCanvas.height / currentRegion.zonesY;
const sx = parseInt(document.getElementById('zoneX').value, 10) || 0;
const sy = parseInt(document.getElementById('zoneY').value, 10) || 0;
for (let y = 0; y < currentRegion.zonesY; y++) {
for (let x = 0; x < currentRegion.zonesX; x++) {
const px = x * cellW;
const py = y * cellH;
regionCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : '#1f2937';
regionCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.strokeStyle = '#374151';
regionCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.fillStyle = '#9ca3af';
regionCtx.font = '12px monospace';
regionCtx.fillText(`${x},${y}`, px + 6, py + 16);
}
}
}
function renderZoneMap() {
zoneCtx.clearRect(0, 0, zoneCanvas.width, zoneCanvas.height);
if (!currentRegion) return;
const w = currentRegion.chunksPerZoneX;
const h = currentRegion.chunksPerZoneY;
const cellW = zoneCanvas.width / w;
const cellH = zoneCanvas.height / h;
const sx = parseInt(document.getElementById('chunkX').value, 10) || 0;
const sy = parseInt(document.getElementById('chunkY').value, 10) || 0;
const versionByPos = new Map();
for (const c of currentZoneChunks) versionByPos.set(key(c.chunkX, c.chunkY), c.version);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const px = x * cellW;
const py = y * cellH;
const v = versionByPos.get(key(x, y));
zoneCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : (v ? '#14532d' : '#1f2937');
zoneCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
zoneCtx.strokeStyle = '#374151';
zoneCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
}
}
}
function renderChunk() {
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
if (!currentChunk) return;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const drawW = currentChunk.width * tileSize;
const drawH = currentChunk.height * tileSize;
chunkCtx.fillStyle = '#111827';
chunkCtx.fillRect(0, 0, drawW, drawH);
for (const t of currentTiles.values()) {
const px = t.x * tileSize;
const py = t.y * tileSize;
if (t.isInvisiblePaywall) {
chunkCtx.fillStyle = '#7c2d12';
} else if (t.isWalkable) {
chunkCtx.fillStyle = '#1d4ed8';
} else {
chunkCtx.fillStyle = '#334155';
}
chunkCtx.fillRect(px, py, tileSize, tileSize);
}
chunkCtx.strokeStyle = 'rgba(148,163,184,0.16)';
chunkCtx.lineWidth = 1;
for (let x = 0; x <= currentChunk.width; x++) {
chunkCtx.beginPath();
chunkCtx.moveTo(x * tileSize + 0.5, 0);
chunkCtx.lineTo(x * tileSize + 0.5, drawH);
chunkCtx.stroke();
}
for (let y = 0; y <= currentChunk.height; y++) {
chunkCtx.beginPath();
chunkCtx.moveTo(0, y * tileSize + 0.5);
chunkCtx.lineTo(drawW, y * tileSize + 0.5);
chunkCtx.stroke();
}
for (const o of currentObjects) {
const px = o.x * tileSize + tileSize / 2;
const py = o.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#f59e0b';
chunkCtx.beginPath();
chunkCtx.arc(px, py, Math.max(2, tileSize * 0.25), 0, Math.PI * 2);
chunkCtx.fill();
}
for (const n of currentNpcs) {
const px = n.x * tileSize + tileSize / 2;
const py = n.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#22c55e';
chunkCtx.beginPath();
chunkCtx.rect(px - Math.max(2, tileSize * 0.2), py - Math.max(2, tileSize * 0.2), Math.max(4, tileSize * 0.4), Math.max(4, tileSize * 0.4));
chunkCtx.fill();
}
const mode = document.getElementById('paintMode').value;
document.getElementById('eraseTargetWrap').classList.toggle('hidden', mode !== 'erase');
}
function canvasTile(e) {
if (!currentChunk) return null;
const rect = chunkCanvas.getBoundingClientRect();
const scaleX = chunkCanvas.width / rect.width;
const scaleY = chunkCanvas.height / rect.height;
const cx = (e.clientX - rect.left) * scaleX;
const cy = (e.clientY - rect.top) * scaleY;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const x = Math.floor(cx / tileSize);
const y = Math.floor(cy / tileSize);
if (x < 0 || y < 0 || x >= currentChunk.width || y >= currentChunk.height) return null;
return { x, y };
}
async function handleChunkPaint(e) {
const pos = canvasTile(e);
if (!pos) return;
const s = selection();
const mode = document.getElementById('paintMode').value;
if (mode === 'tile') {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const isWalkable = document.getElementById('isWalkable').checked;
const isInvisiblePaywall = document.getElementById('isInvisiblePaywall').checked;
const data = await postJson('/admin/worldeditor?handler=UpsertTile', {
...s,
x: pos.x,
y: pos.y,
sheetId,
frameIndex,
isWalkable,
isInvisiblePaywall
});
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.set(key(pos.x, pos.y), {
x: pos.x, y: pos.y, sheetId, frameIndex, isWalkable, isInvisiblePaywall
});
}
} else if (mode === 'object') {
const objectDefinitionId = parseInt(document.getElementById('objectDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertObject', {
...s,
objectDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentObjects.findIndex(o => o.id === data.op.id);
if (idx >= 0) currentObjects[idx] = { ...currentObjects[idx], ...data.op };
else currentObjects.push(data.op);
}
} else if (mode === 'npc') {
const npcDefinitionId = parseInt(document.getElementById('npcDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertNpc', {
...s,
npcDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentNpcs.findIndex(n => n.id === data.op.id);
if (idx >= 0) currentNpcs[idx] = { ...currentNpcs[idx], ...data.op };
else currentNpcs.push(data.op);
}
} else if (mode === 'erase') {
const eraseTarget = document.getElementById('eraseTarget').value;
if (eraseTarget === 'tile') {
const data = await postJson('/admin/worldeditor?handler=RemoveTile', { ...s, x: pos.x, y: pos.y });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.delete(key(pos.x, pos.y));
}
} else if (eraseTarget === 'object') {
const hit = currentObjects.find(o => o.x === pos.x && o.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveObject', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentObjects = currentObjects.filter(o => o.id !== hit.id);
}
}
} else if (eraseTarget === 'npc') {
const hit = currentNpcs.find(n => n.x === pos.x && n.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveNpc', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentNpcs = currentNpcs.filter(n => n.id !== hit.id);
}
}
}
}
renderChunk();
loadZone();
}
function onSheetChanged() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
document.getElementById('tileDefLink').href = `/admin/tilemaps/tiles/edit?sheetId=${sheetId}&frameIndex=${frameIndex}`;
}
document.getElementById('frameIndex').addEventListener('input', onSheetChanged);
chunkCanvas.addEventListener('click', handleChunkPaint);
zoneCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = zoneCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.chunksPerZoneX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.chunksPerZoneY));
document.getElementById('chunkX').value = x;
document.getElementById('chunkY').value = y;
renderZoneMap();
});
regionCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = regionCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.zonesX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.zonesY));
document.getElementById('zoneX').value = x;
document.getElementById('zoneY').value = y;
renderRegionMap();
loadZone();
});
initSelectors();
loadRegion().then(loadChunk);
</script>
}
@@ -0,0 +1,624 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.WorldEditor;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<WorldRegion> Regions { get; set; } = new();
public List<TileMapSheet> TileSheets { get; set; } = new();
public List<DungeonObjectDefinition> ObjectDefinitions { get; set; } = new();
public List<DungeonNpcDefinition> NpcDefinitions { get; set; } = new();
public int SelectedRegionId { get; set; }
public int SelectedZoneX { get; set; }
public int SelectedZoneY { get; set; }
public int SelectedChunkX { get; set; }
public int SelectedChunkY { get; set; }
public async Task OnGetAsync(int? regionId, int zoneX = 0, int zoneY = 0, int chunkX = 0, int chunkY = 0)
{
await EnsureDefaultRegionAsync();
Regions = await _db.WorldRegions
.Where(r => r.IsEnabled)
.OrderBy(r => r.Id)
.ToListAsync();
var selected = Regions.FirstOrDefault(r => r.Id == regionId) ?? Regions.First();
SelectedRegionId = selected.Id;
SelectedZoneX = Math.Clamp(zoneX, 0, Math.Max(0, selected.ZonesPerRegionX - 1));
SelectedZoneY = Math.Clamp(zoneY, 0, Math.Max(0, selected.ZonesPerRegionY - 1));
SelectedChunkX = Math.Clamp(chunkX, 0, Math.Max(0, selected.ChunksPerZoneX - 1));
SelectedChunkY = Math.Clamp(chunkY, 0, Math.Max(0, selected.ChunksPerZoneY - 1));
await EnsureZonesAsync(selected);
TileSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
ObjectDefinitions = await _db.DungeonObjects
.Where(o => o.IsEnabled)
.OrderBy(o => o.Name)
.ToListAsync();
NpcDefinitions = await _db.DungeonNpcDefinitions
.Where(n => n.IsEnabled)
.OrderBy(n => n.Name)
.ToListAsync();
}
public async Task<IActionResult> OnGetRegionAsync(int regionId)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
{
return new JsonResult(new { success = false, error = "region_not_found" }) { StatusCode = 404 };
}
await EnsureZonesAsync(region);
var zones = await _db.WorldZones
.Where(z => z.RegionId == region.Id && z.IsEnabled)
.OrderBy(z => z.ZoneY).ThenBy(z => z.ZoneX)
.ToListAsync();
var zoneIds = zones.Select(z => z.Id).ToList();
var chunkCounts = await _db.WorldChunks
.Where(c => zoneIds.Contains(c.WorldZoneId))
.GroupBy(c => c.WorldZoneId)
.Select(g => new { ZoneId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.ZoneId, x => x.Count);
return new JsonResult(new
{
success = true,
region = new
{
id = region.Id,
name = region.Name,
zonesX = region.ZonesPerRegionX,
zonesY = region.ZonesPerRegionY,
chunksPerZoneX = region.ChunksPerZoneX,
chunksPerZoneY = region.ChunksPerZoneY,
chunkWidthTiles = region.ChunkWidthTiles,
chunkHeightTiles = region.ChunkHeightTiles
},
zones = zones.Select(z => new
{
id = z.Id,
zoneX = z.ZoneX,
zoneY = z.ZoneY,
name = z.Name,
editedChunkCount = chunkCounts.GetValueOrDefault(z.Id)
})
});
}
public async Task<IActionResult> OnGetZoneAsync(int regionId, int zoneX, int zoneY)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
{
return new JsonResult(new { success = false, error = "region_not_found" }) { StatusCode = 404 };
}
if (!IsInside(region.ZonesPerRegionX, region.ZonesPerRegionY, zoneX, zoneY))
{
return new JsonResult(new { success = false, error = "zone_out_of_bounds" }) { StatusCode = 400 };
}
await EnsureZonesAsync(region);
var zone = await _db.WorldZones.FirstAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY);
var chunks = await _db.WorldChunks
.Where(c => c.WorldZoneId == zone.Id)
.Select(c => new { c.ChunkX, c.ChunkY, c.Version })
.ToListAsync();
return new JsonResult(new
{
success = true,
zone = new
{
id = zone.Id,
regionId,
zoneX,
zoneY,
chunksPerZoneX = region.ChunksPerZoneX,
chunksPerZoneY = region.ChunksPerZoneY
},
chunks
});
}
public async Task<IActionResult> OnGetChunkAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Zone == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var chunk = locate.Chunk;
var region = locate.Region;
var tiles = await _db.WorldChunkTiles
.Where(t => t.WorldChunkId == chunk.Id)
.OrderBy(t => t.TileY).ThenBy(t => t.TileX)
.Select(t => new
{
id = t.Id,
x = t.TileX,
y = t.TileY,
sheetId = t.SheetId,
frameIndex = t.FrameIndex,
isWalkable = t.IsWalkable,
isInvisiblePaywall = t.IsInvisiblePaywall
})
.ToListAsync();
var objects = await _db.WorldChunkObjects
.Include(o => o.ObjectDefinition)
.Where(o => o.WorldChunkId == chunk.Id)
.OrderBy(o => o.TileY).ThenBy(o => o.TileX)
.Select(o => new
{
id = o.Id,
x = o.TileX,
y = o.TileY,
objectDefinitionId = o.ObjectDefinitionId,
objectName = o.ObjectDefinition != null ? o.ObjectDefinition.Name : $"Object {o.ObjectDefinitionId}",
rotation = o.Rotation,
metadataJson = o.MetadataJson
})
.ToListAsync();
var npcs = await _db.WorldChunkNpcSpawns
.Include(n => n.NpcDefinition)
.Where(n => n.WorldChunkId == chunk.Id)
.OrderBy(n => n.TileY).ThenBy(n => n.TileX)
.Select(n => new
{
id = n.Id,
x = n.TileX,
y = n.TileY,
npcDefinitionId = n.NpcDefinitionId,
npcName = n.NpcDefinition != null ? n.NpcDefinition.Name : $"NPC {n.NpcDefinitionId}",
rotation = n.Rotation,
metadataJson = n.MetadataJson
})
.ToListAsync();
return new JsonResult(new
{
success = true,
chunk = new
{
id = chunk.Id,
regionId,
zoneX,
zoneY,
chunkX,
chunkY,
version = chunk.Version,
width = region.ChunkWidthTiles,
height = region.ChunkHeightTiles
},
tiles,
objects,
npcs
});
}
public async Task<IActionResult> OnPostUpsertTileAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
int x,
int y,
int sheetId,
int frameIndex,
bool isWalkable,
bool isInvisiblePaywall)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var sheetExists = await _db.TileMapSheets.AnyAsync(s => s.Id == sheetId && s.IsEnabled);
if (!sheetExists)
{
return new JsonResult(new { success = false, error = "sheet_not_found" }) { StatusCode = 404 };
}
var tile = await _db.WorldChunkTiles
.FirstOrDefaultAsync(t => t.WorldChunkId == locate.Chunk.Id && t.TileX == x && t.TileY == y);
if (tile == null)
{
tile = new WorldChunkTile
{
WorldChunkId = locate.Chunk.Id,
TileX = x,
TileY = y
};
_db.WorldChunkTiles.Add(tile);
}
tile.SheetId = sheetId;
tile.FrameIndex = frameIndex;
tile.IsWalkable = isWalkable;
tile.IsInvisiblePaywall = isInvisiblePaywall;
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "tile_upsert",
x,
y,
sheetId,
frameIndex,
isWalkable,
isInvisiblePaywall
}
});
}
public async Task<IActionResult> OnPostRemoveTileAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, int x, int y)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var tile = await _db.WorldChunkTiles
.FirstOrDefaultAsync(t => t.WorldChunkId == locate.Chunk.Id && t.TileX == x && t.TileY == y);
if (tile != null)
{
_db.WorldChunkTiles.Remove(tile);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "tile_remove", x, y }
});
}
public async Task<IActionResult> OnPostUpsertObjectAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
long? id,
int objectDefinitionId,
int x,
int y,
int rotation = 0,
string? metadataJson = null)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var objectExists = await _db.DungeonObjects.AnyAsync(o => o.Id == objectDefinitionId && o.IsEnabled);
if (!objectExists)
{
return new JsonResult(new { success = false, error = "object_definition_not_found" }) { StatusCode = 404 };
}
WorldChunkObject obj;
if (id.HasValue)
{
obj = await _db.WorldChunkObjects.FirstOrDefaultAsync(o => o.Id == id.Value && o.WorldChunkId == locate.Chunk.Id)
?? new WorldChunkObject { WorldChunkId = locate.Chunk.Id };
if (obj.Id == 0)
{
_db.WorldChunkObjects.Add(obj);
}
}
else
{
obj = new WorldChunkObject { WorldChunkId = locate.Chunk.Id };
_db.WorldChunkObjects.Add(obj);
}
obj.ObjectDefinitionId = objectDefinitionId;
obj.TileX = x;
obj.TileY = y;
obj.Rotation = rotation;
obj.MetadataJson = string.IsNullOrWhiteSpace(metadataJson) ? null : metadataJson.Trim();
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "object_upsert",
id = obj.Id,
x = obj.TileX,
y = obj.TileY,
objectDefinitionId = obj.ObjectDefinitionId,
rotation = obj.Rotation,
metadataJson = obj.MetadataJson
}
});
}
public async Task<IActionResult> OnPostRemoveObjectAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long id)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var obj = await _db.WorldChunkObjects.FirstOrDefaultAsync(o => o.Id == id && o.WorldChunkId == locate.Chunk.Id);
if (obj != null)
{
_db.WorldChunkObjects.Remove(obj);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "object_remove", id }
});
}
public async Task<IActionResult> OnPostUpsertNpcAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY,
long? id,
int npcDefinitionId,
int x,
int y,
int rotation = 0,
string? metadataJson = null)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Region == null || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
if (!IsInside(locate.Region.ChunkWidthTiles, locate.Region.ChunkHeightTiles, x, y))
{
return new JsonResult(new { success = false, error = "tile_out_of_bounds" }) { StatusCode = 400 };
}
var npcExists = await _db.DungeonNpcDefinitions.AnyAsync(n => n.Id == npcDefinitionId && n.IsEnabled);
if (!npcExists)
{
return new JsonResult(new { success = false, error = "npc_definition_not_found" }) { StatusCode = 404 };
}
WorldChunkNpcSpawn npc;
if (id.HasValue)
{
npc = await _db.WorldChunkNpcSpawns.FirstOrDefaultAsync(n => n.Id == id.Value && n.WorldChunkId == locate.Chunk.Id)
?? new WorldChunkNpcSpawn { WorldChunkId = locate.Chunk.Id };
if (npc.Id == 0)
{
_db.WorldChunkNpcSpawns.Add(npc);
}
}
else
{
npc = new WorldChunkNpcSpawn { WorldChunkId = locate.Chunk.Id };
_db.WorldChunkNpcSpawns.Add(npc);
}
npc.NpcDefinitionId = npcDefinitionId;
npc.TileX = x;
npc.TileY = y;
npc.Rotation = rotation;
npc.MetadataJson = string.IsNullOrWhiteSpace(metadataJson) ? null : metadataJson.Trim();
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new
{
type = "npc_upsert",
id = npc.Id,
x = npc.TileX,
y = npc.TileY,
npcDefinitionId = npc.NpcDefinitionId,
rotation = npc.Rotation,
metadataJson = npc.MetadataJson
}
});
}
public async Task<IActionResult> OnPostRemoveNpcAsync(int regionId, int zoneX, int zoneY, int chunkX, int chunkY, long id)
{
var locate = await GetOrCreateChunkAsync(regionId, zoneX, zoneY, chunkX, chunkY);
if (!locate.Success || locate.Chunk == null)
{
return new JsonResult(new { success = false, error = locate.Error }) { StatusCode = 400 };
}
var npc = await _db.WorldChunkNpcSpawns.FirstOrDefaultAsync(n => n.Id == id && n.WorldChunkId == locate.Chunk.Id);
if (npc != null)
{
_db.WorldChunkNpcSpawns.Remove(npc);
locate.Chunk.Version++;
locate.Chunk.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
}
return new JsonResult(new
{
success = true,
chunkVersion = locate.Chunk.Version,
op = new { type = "npc_remove", id }
});
}
private async Task EnsureDefaultRegionAsync()
{
if (await _db.WorldRegions.AnyAsync())
return;
_db.WorldRegions.Add(new WorldRegion
{
Name = "Default Region",
ZonesPerRegionX = 4,
ZonesPerRegionY = 4,
ChunksPerZoneX = 8,
ChunksPerZoneY = 8,
ChunkWidthTiles = 64,
ChunkHeightTiles = 64,
IsEnabled = true,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
});
await _db.SaveChangesAsync();
}
private async Task EnsureZonesAsync(WorldRegion region)
{
var existing = await _db.WorldZones
.Where(z => z.RegionId == region.Id)
.Select(z => new { z.ZoneX, z.ZoneY })
.ToListAsync();
var existingSet = existing.Select(z => $"{z.ZoneX}:{z.ZoneY}").ToHashSet();
var now = DateTime.UtcNow;
var added = false;
for (var y = 0; y < region.ZonesPerRegionY; y++)
{
for (var x = 0; x < region.ZonesPerRegionX; x++)
{
if (existingSet.Contains($"{x}:{y}"))
continue;
_db.WorldZones.Add(new WorldZone
{
RegionId = region.Id,
ZoneX = x,
ZoneY = y,
Name = $"Zone {x},{y}",
IsEnabled = true,
CreatedAt = now,
UpdatedAt = now
});
added = true;
}
}
if (added)
{
await _db.SaveChangesAsync();
}
}
private async Task<(bool Success, string? Error, WorldRegion? Region, WorldZone? Zone, WorldChunk? Chunk)> GetOrCreateChunkAsync(
int regionId,
int zoneX,
int zoneY,
int chunkX,
int chunkY)
{
var region = await _db.WorldRegions.FirstOrDefaultAsync(r => r.Id == regionId && r.IsEnabled);
if (region == null)
return (false, "region_not_found", null, null, null);
if (!IsInside(region.ZonesPerRegionX, region.ZonesPerRegionY, zoneX, zoneY))
return (false, "zone_out_of_bounds", region, null, null);
if (!IsInside(region.ChunksPerZoneX, region.ChunksPerZoneY, chunkX, chunkY))
return (false, "chunk_out_of_bounds", region, null, null);
await EnsureZonesAsync(region);
var zone = await _db.WorldZones
.FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.IsEnabled);
if (zone == null)
return (false, "zone_not_found", region, null, null);
var chunk = await _db.WorldChunks
.FirstOrDefaultAsync(c => c.WorldZoneId == zone.Id && c.ChunkX == chunkX && c.ChunkY == chunkY);
if (chunk == null)
{
chunk = new WorldChunk
{
WorldZoneId = zone.Id,
ChunkX = chunkX,
ChunkY = chunkY,
Version = 1,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
_db.WorldChunks.Add(chunk);
await _db.SaveChangesAsync();
}
return (true, null, region, zone, chunk);
}
private static bool IsInside(int width, int height, int x, int y)
{
return x >= 0 && y >= 0 && x < width && y < height;
}
}