Files
systemrevivalserver/Services/Admin/Pages/Dungeons/View.cshtml
T
2026-01-31 11:19:38 -05:00

793 lines
42 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@page "/admin/dungeons/view"
@model Admin.Pages.Dungeons.ViewModel
@{
ViewData["Title"] = $"Dungeon View - Tier {Model.Dungeon?.Tier}";
}
<style>
.dungeon-map { background: #0a0a15; border: 2px solid #374151; border-radius: 8px; overflow: hidden; position: relative; }
.map-viewport { overflow: auto; height: calc(100vh - 350px); min-height: 400px; position: relative; }
.map-canvas { image-rendering: pixelated; cursor: crosshair; display: block; }
.map-canvas.edit-mode { cursor: cell; }
.entity-layer { position: absolute; top: 0; left: 0; pointer-events: none; }
.entity-dot { position: absolute; border-radius: 50%; transform: translate(-50%, -50%); cursor: pointer; pointer-events: auto; transition: transform 0.1s; }
.entity-dot:hover { transform: translate(-50%, -50%) scale(1.5); z-index: 100; }
.player-dot { background: #4ade80; width: 12px; height: 12px; box-shadow: 0 0 6px #4ade80; }
.player-dot.selected { outline: 2px solid #fff; outline-offset: 2px; }
.mob-dot { background: #f87171; width: 8px; height: 8px; }
.mob-dot:hover { box-shadow: 0 0 8px #f87171; }
.boss-dot { background: #fbbf24; width: 12px; height: 12px; box-shadow: 0 0 8px #fbbf24; }
.mob-dot.selected, .boss-dot.selected { outline: 2px solid white; outline-offset: 2px; }
.stat-card { background: rgba(30, 30, 50, 0.8); border: 1px solid #374151; border-radius: 8px; padding: 12px; }
.inspector { background: rgba(20, 20, 40, 0.95); border: 1px solid #4f46e5; border-radius: 8px; padding: 16px; }
.inspector-stat { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid rgba(255,255,255,0.1); }
.inspector, .inspector * { color: #e5e7eb; }
.inspector .text-gray-400 { color: #9ca3af !important; }
.inspector select, .inspector input, .inspector textarea { background: #111827; border-color: #374151; color: #e5e7eb; }
.inspector option { color: #e5e7eb; background: #111827; }
.tool-btn { padding: 6px 10px; border-radius: 6px; font-size: 12px; transition: all 0.15s; background: #374151; color: #ccc; border: none; cursor: pointer; }
.tool-btn:hover { background: #4b5563; }
.tool-btn.active { background: #4f46e5; color: white; }
.zoom-btn { width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; }
/* Tile Drawer */
.tile-drawer { position: fixed; top: 0; right: -320px; width: 320px; height: 100vh; background: #1a1a2e; border-left: 2px solid #4f46e5; z-index: 1000; transition: right 0.3s ease; display: flex; flex-direction: column; }
.tile-drawer.open { right: 0; }
.tile-drawer-header { padding: 16px; border-bottom: 1px solid #374151; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
.tile-drawer-body { flex: 1; overflow-y: auto; padding: 12px; }
.sheet-section { margin-bottom: 16px; }
.sheet-header { padding: 8px; background: #252540; border-radius: 6px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.sheet-header:hover { background: #303050; }
.sheet-header.expanded { background: #4f46e5; }
.tile-grid { display: grid; gap: 2px; padding: 4px; background: #0a0a15; border-radius: 4px; }
.tile-cell { border: 2px solid transparent; cursor: pointer; image-rendering: pixelated; background: #1a1a2e; }
.tile-cell:hover { border-color: #4f46e5; }
.tile-cell.selected { border-color: #22c55e; }
.tile-preview-box { display: flex; align-items: center; gap: 12px; padding: 12px; background: #252540; border-radius: 8px; margin-bottom: 12px; }
.tile-preview-canvas { width: 48px; height: 48px; border: 2px solid #374151; image-rendering: pixelated; background: #000; }
.drawer-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 999; display: none; }
.drawer-overlay.open { display: block; }
</style>
<div class="mb-4">
<a href="/admin/dungeons" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Dungeons</a>
</div>
@if (Model.Dungeon == null)
{
<div class="card p-8 text-center">
<div class="text-4xl mb-2">❌</div>
<h2 class="text-xl font-semibold text-white mb-2">Dungeon Not Found</h2>
<a href="/admin/dungeons" class="btn btn-primary mt-4">Back to Dungeons</a>
</div>
}
else
{
<div class="flex flex-col xl:flex-row gap-4">
<!-- Left: Map View (50% on large screens) -->
<div class="w-full xl:w-1/2">
<div class="card p-4">
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-white">Live Dungeon Map</h2>
<div class="flex items-center gap-4">
<div class="flex items-center gap-2">
<button onclick="zoomOut()" class="tool-btn zoom-btn">−</button>
<span id="zoomLevel" class="text-sm text-gray-400 w-12 text-center">100%</span>
<button onclick="zoomIn()" class="tool-btn zoom-btn">+</button>
<button onclick="zoomFit()" class="tool-btn">Fit</button>
</div>
<div class="flex items-center gap-2 text-sm text-gray-400">
<div class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="tool-btn">Auto: ON</button>
</div>
</div>
</div>
<!-- Edit Tools -->
<div class="flex flex-wrap items-center gap-2 mb-3 p-2 bg-gray-800 rounded">
<span class="text-xs text-gray-400 mr-2">Mode:</span>
<button onclick="setEditMode('none')" id="modeNone" class="tool-btn active">🔍 View</button>
<button onclick="setEditMode('floor')" id="modeFloor" class="tool-btn">🟦 Floor</button>
<button onclick="setEditMode('wall')" id="modeWall" class="tool-btn">⬛ Wall</button>
<button onclick="setEditMode('tile')" id="modeTile" class="tool-btn">🎨 Tile</button>
<button onclick="setEditMode('erase')" id="modeErase" class="tool-btn">🗑️ Erase</button>
<button onclick="toggleTileDrawer()" id="drawerToggle" class="tool-btn ml-auto">📋 Tile Picker</button>
</div>
<!-- Selected Tile Info (shown when in tile mode) -->
<div id="selectedTileInfo" class="hidden mb-3 p-2 bg-gray-800 rounded flex items-center gap-4">
<canvas id="previewCanvas" width="32" height="32" class="tile-preview-canvas"></canvas>
<div class="flex-1">
<div class="text-sm text-white" id="selectedTileName">No tile selected</div>
<div class="text-xs text-gray-400">Click "Tile Picker" to select</div>
</div>
<div class="flex items-center gap-2">
<select id="tileLayer" class="input text-xs w-24">
<option value="0">Ground</option>
<option value="1">Decor</option>
<option value="2">Walls</option>
<option value="3">Ceiling</option>
</select>
<label class="flex items-center gap-1 text-xs text-gray-400">
<input type="checkbox" id="tileWalkable" checked class="w-4 h-4"> Walk
</label>
</div>
</div>
<div class="dungeon-map" id="mapContainer">
<div class="map-viewport" id="mapViewport">
<canvas id="mapCanvas" class="map-canvas"></canvas>
<div id="entityLayer" class="entity-layer"></div>
</div>
</div>
<div class="flex items-center justify-center gap-6 mt-3 text-xs text-gray-400">
<div class="flex items-center gap-1"><div class="w-3 h-3 rounded-full bg-green-400"></div><span>Players</span></div>
<div class="flex items-center gap-1"><div class="w-2 h-2 rounded-full bg-red-400"></div><span>Mobs</span></div>
<div class="flex items-center gap-1"><div class="w-3 h-3 rounded-full bg-yellow-400"></div><span>Boss</span></div>
</div>
</div>
<!-- Inspectors -->
<div id="playerInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-green-400" id="playerInspectorName">Player</h3>
<button onclick="closePlayerInspector()" class="text-gray-400 hover:text-white">✕</button>
</div>
<div id="playerInspectorContent" class="space-y-1 text-sm"></div>
<div class="grid grid-cols-2 gap-2 mt-4">
<button onclick="healSelectedPlayer()" class="btn btn-success btn-sm">❤️ Heal</button>
<button onclick="teleportPlayerToClick()" id="teleportBtn" class="btn btn-secondary btn-sm">📍 Teleport</button>
<button onclick="toggleGodMode()" id="godModeBtn" class="btn btn-secondary btn-sm">🛡️ God</button>
<button onclick="killSelectedPlayer()" class="btn btn-danger btn-sm">💀 Kill</button>
</div>
</div>
<div id="mobInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-red-400" id="mobInspectorName">Mob</h3>
<button onclick="closeMobInspector()" class="text-gray-400 hover:text-white">✕</button>
</div>
<div id="mobInspectorContent" class="space-y-1 text-sm"></div>
<div class="grid grid-cols-2 gap-2 mt-4">
<button onclick="healSelectedMob()" class="btn btn-success btn-sm">❤️ Heal</button>
<button onclick="copyMobPosition()" class="btn btn-secondary btn-sm">📍 Copy</button>
<button onclick="killSelectedMob()" class="btn btn-danger btn-sm">🗡️ Kill</button>
</div>
<div class="mt-4 space-y-3">
<div>
<div class="text-xs text-gray-400 mb-1">Add Ability</div>
<div class="flex gap-2">
<select id="mobAbilitySelect" class="input text-xs w-full">
<option value="">Select ability...</option>
@foreach (var ability in Model.AbilityDefinitions)
{
<option value="@ability.Id">@ability.Name (@ability.Key)</option>
}
</select>
<button onclick="addMobAbility()" class="btn btn-secondary btn-sm">Add</button>
</div>
</div>
<div>
<div class="text-xs text-gray-400 mb-1">Resistances</div>
<div class="grid grid-cols-3 gap-2">
<select id="mobResistSelect" class="input text-xs col-span-2">
<option value="">Select type...</option>
@foreach (var res in Model.ResistanceTypes)
{
<option value="@res.Key">@res.DisplayName (@res.Key)</option>
}
</select>
<input type="number" id="mobResistValue" class="input text-xs" placeholder="0.25" step="0.05" />
</div>
<div class="flex gap-2 mt-2">
<button onclick="setMobResistance(false)" class="btn btn-secondary btn-sm">Add/Update</button>
<button onclick="setMobResistance(true)" class="btn btn-danger btn-sm">Remove</button>
</div>
</div>
<div>
<div class="text-xs text-gray-400 mb-1">Loot</div>
<div class="grid grid-cols-3 gap-2">
<input type="number" id="mobLootGold" class="input text-xs col-span-2" placeholder="Gold" />
<button onclick="setMobLootGold()" class="btn btn-secondary btn-sm">Set</button>
</div>
<div class="grid grid-cols-3 gap-2 mt-2">
<input type="number" id="mobLootItemId" class="input text-xs" placeholder="Item Id" />
<input type="number" id="mobLootItemQty" class="input text-xs" placeholder="Qty" value="1" />
<button onclick="addMobLootItem()" class="btn btn-secondary btn-sm">Add</button>
</div>
</div>
</div>
</div>
</div>
<!-- Right: Info Panel (50% on large screens) -->
<div class="w-full xl:w-1/2 space-y-4">
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Dungeon Info</h3>
<div class="space-y-2 text-sm">
<div class="flex justify-between"><span class="text-gray-400">Tier</span><span class="text-white">@Model.Dungeon.Tier</span></div>
<div class="flex justify-between"><span class="text-gray-400">Size</span><span class="text-white">@Model.MapWidth × @Model.MapHeight</span></div>
<div class="flex justify-between"><span class="text-gray-400">Tiles</span><span class="text-white">@Model.VisualTileCount</span></div>
<div class="flex justify-between"><span class="text-gray-400">Sheets</span><span class="text-white" id="sheetCount">0</span></div>
<div class="flex justify-between"><span class="text-gray-400">Duration</span><span class="text-white" id="duration">@Model.Duration</span></div>
</div>
</div>
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Live Stats</h3>
<div class="grid grid-cols-2 gap-3">
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-green-400" id="playerCount">@Model.Dungeon.Simulation.Players.Count</div>
<div class="text-xs text-gray-400">Players</div>
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-red-400" id="mobCount">@Model.Dungeon.Simulation.Mobs.Values.Count(m => m.IsAlive)</div>
<div class="text-xs text-gray-400">Mobs</div>
</div>
</div>
</div>
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Spawn Mob</h3>
<div class="space-y-2">
<input type="text" id="spawnMobFilter" class="input text-sm w-full" placeholder="Type to filter mobs..." />
<select id="spawnMobSelect" class="input text-sm w-full">
<option value="">Select mob...</option>
@foreach (var mob in Model.MobDefinitions)
{
<option value="@mob.Id">@mob.Name</option>
}
</select>
<div class="grid grid-cols-2 gap-2">
<input type="number" id="spawnX" class="input text-sm" placeholder="X" value="@(Model.MapWidth / 2 * 32)" />
<input type="number" id="spawnY" class="input text-sm" placeholder="Y" value="@(Model.MapHeight / 2 * 32)" />
</div>
<button onclick="spawnMob()" class="btn btn-success w-full text-sm">+ Spawn</button>
<p class="text-xs text-gray-500">Right-click map to set position</p>
</div>
</div>
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Actions</h3>
<div class="space-y-2">
<form method="post" asp-page-handler="KillAllMobs">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Kill all?')">Kill All Mobs</button>
</form>
<button onclick="broadcastTiles()" class="btn btn-primary w-full text-sm">📡 Broadcast Tiles</button>
</div>
</div>
</div>
</div>
<!-- Tile Picker Drawer -->
<div id="drawerOverlay" class="drawer-overlay" onclick="closeTileDrawer()"></div>
<div id="tileDrawer" class="tile-drawer">
<div class="tile-drawer-header">
<h3 class="text-lg font-semibold text-white">Tile Picker</h3>
<button onclick="closeTileDrawer()" class="text-gray-400 hover:text-white text-xl">✕</button>
</div>
<div class="tile-drawer-body">
<!-- Selected tile preview -->
<div class="tile-preview-box">
<canvas id="drawerPreview" width="48" height="48" class="tile-preview-canvas"></canvas>
<div>
<div class="text-sm text-white" id="drawerTileName">No tile selected</div>
<div class="text-xs text-gray-400" id="drawerTileInfo">Select from below</div>
</div>
</div>
<!-- Sheet list -->
<div id="sheetList">
<p class="text-gray-500 text-sm">Loading sheets...</p>
</div>
</div>
</div>
}
@section Scripts {
<script>
const dungeonId = '@Model.Dungeon?.Id';
const mapWidth = @(Model.MapWidth);
const mapHeight = @(Model.MapHeight);
const tileSize = 32;
let walkableData = @Html.Raw(Model.WalkableJson);
let visualTiles = @Html.Raw(Model.VisualTilesJson);
let tileSheets = @Html.Raw(Model.TileSheetsJson);
let autoRefresh = true, refreshInterval;
let zoom = 1.0;
const minZoom = 0.25, maxZoom = 4.0;
let selectedMobId = null, selectedPlayerId = null;
let currentMobs = [], currentPlayers = [];
let editMode = 'none', isDrawing = false;
let teleportMode = false, godModeEnabled = false;
let selectedSheetId = 0, selectedFrameIndex = 0;
let sheetTextures = {};
let expandedSheets = {};
// ==================== INIT ====================
async function init() {
console.log('[Admin] Init - tileSheets:', tileSheets.length);
document.getElementById('sheetCount').textContent = tileSheets.length;
await loadSheetTextures();
initMap();
buildSheetList();
updateEntities(@Html.Raw(Model.PlayersJson), @Html.Raw(Model.MobsJson));
refreshInterval = setInterval(fetchUpdate, 500);
const filterInput = document.getElementById('spawnMobFilter');
if (filterInput) {
filterInput.addEventListener('input', () => filterMobSelect(filterInput.value));
}
}
async function loadSheetTextures() {
const cdnBase = 'https://assets.aeternalisgames.com/downloads/';
const promises = tileSheets.map(sheet => new Promise(resolve => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => { sheetTextures[sheet.id] = img; console.log('[Admin] Loaded sheet', sheet.id, sheet.path); resolve(); };
img.onerror = () => { console.warn('[Admin] Failed to load', sheet.path); resolve(); };
img.src = cdnBase + sheet.path;
}));
await Promise.all(promises);
console.log('[Admin] Loaded', Object.keys(sheetTextures).length, 'textures');
}
function initMap() {
const canvas = document.getElementById('mapCanvas');
const entityLayer = document.getElementById('entityLayer');
canvas.width = mapWidth * tileSize;
canvas.height = mapHeight * tileSize;
entityLayer.style.width = canvas.width + 'px';
entityLayer.style.height = canvas.height + 'px';
applyZoom();
drawMap();
setupCanvasEvents(canvas);
}
function drawMap() {
const canvas = document.getElementById('mapCanvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
// Base walkability
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
ctx.fillStyle = walkableData[y * mapWidth + x] ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
}
}
// Visual tiles
for (const tile of visualTiles) {
const sheet = tileSheets.find(s => s.id === tile.sid);
const tex = sheetTextures[tile.sid];
if (!sheet || !tex) continue;
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const srcX = (tile.frame % cols) * sheet.tileW;
const srcY = Math.floor(tile.frame / cols) * sheet.tileH;
ctx.drawImage(tex, srcX, srcY, sheet.tileW, sheet.tileH, tile.x * tileSize, tile.y * tileSize, tileSize, tileSize);
}
// Grid
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
for (let i = 0; i <= mapWidth; i++) { ctx.beginPath(); ctx.moveTo(i * tileSize, 0); ctx.lineTo(i * tileSize, mapHeight * tileSize); ctx.stroke(); }
for (let i = 0; i <= mapHeight; i++) { ctx.beginPath(); ctx.moveTo(0, i * tileSize); ctx.lineTo(mapWidth * tileSize, i * tileSize); ctx.stroke(); }
}
// ==================== TILE DRAWER ====================
function toggleTileDrawer() {
const drawer = document.getElementById('tileDrawer');
const overlay = document.getElementById('drawerOverlay');
drawer.classList.toggle('open');
overlay.classList.toggle('open');
}
function closeTileDrawer() {
document.getElementById('tileDrawer').classList.remove('open');
document.getElementById('drawerOverlay').classList.remove('open');
}
function buildSheetList() {
const container = document.getElementById('sheetList');
if (tileSheets.length === 0) {
container.innerHTML = '<p class="text-gray-500 text-sm">No tile sheets in this dungeon</p>';
return;
}
let html = '';
for (const sheet of tileSheets) {
const name = sheet.name || sheet.path?.split('/').pop() || `Sheet ${sheet.id}`;
html += `
<div class="sheet-section" data-sheet-id="${sheet.id}">
<div class="sheet-header ${expandedSheets[sheet.id] ? 'expanded' : ''}" onclick="toggleSheet(${sheet.id})">
<span class="text-white text-sm">${name}</span>
<span class="text-gray-400 text-xs">${expandedSheets[sheet.id] ? '▼' : '▶'}</span>
</div>
<div class="sheet-tiles ${expandedSheets[sheet.id] ? '' : 'hidden'}" id="sheetTiles_${sheet.id}"></div>
</div>
`;
}
container.innerHTML = html;
// Render expanded sheets
for (const sheetId of Object.keys(expandedSheets)) {
if (expandedSheets[sheetId]) renderSheetTiles(parseInt(sheetId));
}
}
function toggleSheet(sheetId) {
expandedSheets[sheetId] = !expandedSheets[sheetId];
buildSheetList();
if (expandedSheets[sheetId]) renderSheetTiles(sheetId);
}
function renderSheetTiles(sheetId) {
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
const container = document.getElementById(`sheetTiles_${sheetId}`);
if (!sheet || !texture || !container) return;
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const rows = Math.floor(sheet.sheetH / sheet.tileH);
const totalTiles = cols * rows;
const cellSize = Math.min(32, Math.floor(280 / cols));
let html = `<div class="tile-grid" style="grid-template-columns: repeat(${cols}, ${cellSize}px);">`;
for (let i = 0; i < totalTiles; i++) {
const isSelected = sheetId === selectedSheetId && i === selectedFrameIndex;
html += `<canvas class="tile-cell ${isSelected ? 'selected' : ''}" width="${cellSize}" height="${cellSize}"
data-sheet="${sheetId}" data-frame="${i}" onclick="selectTile(${sheetId}, ${i})"></canvas>`;
}
html += '</div>';
container.innerHTML = html;
// Draw tiles
container.querySelectorAll('.tile-cell').forEach(canvas => {
const frame = parseInt(canvas.dataset.frame);
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
const srcX = (frame % cols) * sheet.tileW;
const srcY = Math.floor(frame / cols) * sheet.tileH;
ctx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, cellSize, cellSize);
});
}
function selectTile(sheetId, frameIndex) {
selectedSheetId = sheetId;
selectedFrameIndex = frameIndex;
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
// Update drawer preview
if (sheet && texture) {
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const srcX = (frameIndex % cols) * sheet.tileW;
const srcY = Math.floor(frameIndex / cols) * sheet.tileH;
const drawerCanvas = document.getElementById('drawerPreview');
const dCtx = drawerCanvas.getContext('2d');
dCtx.imageSmoothingEnabled = false;
dCtx.clearRect(0, 0, 48, 48);
dCtx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, 48, 48);
const mainCanvas = document.getElementById('previewCanvas');
const mCtx = mainCanvas.getContext('2d');
mCtx.imageSmoothingEnabled = false;
mCtx.clearRect(0, 0, 32, 32);
mCtx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, 32, 32);
const name = sheet.name || sheet.path?.split('/').pop() || `Sheet ${sheetId}`;
document.getElementById('drawerTileName').textContent = name;
document.getElementById('drawerTileInfo').textContent = `Frame ${frameIndex}`;
document.getElementById('selectedTileName').textContent = `${name} #${frameIndex}`;
}
// Update selection visuals
document.querySelectorAll('.tile-cell').forEach(el => el.classList.remove('selected'));
event?.target?.classList.add('selected');
// Auto-switch to tile mode
setEditMode('tile');
}
// ==================== ZOOM ====================
function applyZoom() {
const canvas = document.getElementById('mapCanvas');
const entityLayer = document.getElementById('entityLayer');
canvas.style.transform = `scale(${zoom})`;
canvas.style.transformOrigin = 'top left';
entityLayer.style.transform = `scale(${zoom})`;
entityLayer.style.transformOrigin = 'top left';
document.getElementById('zoomLevel').textContent = Math.round(zoom * 100) + '%';
}
function zoomIn() { zoom = Math.min(maxZoom, zoom * 1.25); applyZoom(); }
function zoomOut() { zoom = Math.max(minZoom, zoom / 1.25); applyZoom(); }
function zoomFit() {
const vp = document.getElementById('mapViewport');
zoom = Math.max(minZoom, Math.min(vp.clientWidth / (mapWidth * tileSize), vp.clientHeight / (mapHeight * tileSize), 1) * 0.95);
applyZoom();
}
// ==================== CANVAS EVENTS ====================
function setupCanvasEvents(canvas) {
canvas.oncontextmenu = e => {
e.preventDefault();
const pos = getTilePos(e);
document.getElementById('spawnX').value = pos.x * tileSize + tileSize/2;
document.getElementById('spawnY').value = pos.y * tileSize + tileSize/2;
};
canvas.onmousedown = e => {
if (e.button !== 0) return;
const pos = getTilePos(e);
if (teleportMode && selectedPlayerId) {
teleportPlayer(pos.x * tileSize + tileSize/2, pos.y * tileSize + tileSize/2);
teleportMode = false;
document.getElementById('teleportBtn').classList.remove('btn-primary');
return;
}
if (editMode === 'none') return;
isDrawing = true;
paintTile(pos.x, pos.y);
};
canvas.onmousemove = e => { if (isDrawing && editMode !== 'none') paintTile(getTilePos(e).x, getTilePos(e).y); };
canvas.onmouseup = () => isDrawing = false;
canvas.onmouseleave = () => isDrawing = false;
}
function getTilePos(e) {
const rect = document.getElementById('mapCanvas').getBoundingClientRect();
return { x: Math.floor((e.clientX - rect.left) / (tileSize * zoom)), y: Math.floor((e.clientY - rect.top) / (tileSize * zoom)) };
}
// ==================== EDIT MODE ====================
function setEditMode(mode) {
editMode = mode;
document.querySelectorAll('[id^="mode"]').forEach(b => b.classList.remove('active'));
document.getElementById('mode' + mode.charAt(0).toUpperCase() + mode.slice(1))?.classList.add('active');
document.getElementById('mapCanvas').classList.toggle('edit-mode', mode !== 'none');
document.getElementById('selectedTileInfo').classList.toggle('hidden', mode !== 'tile');
}
async function paintTile(x, y) {
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) return;
let handler = '', params = `id=${dungeonId}&x=${x}&y=${y}`;
if (editMode === 'floor') {
handler = 'SetTile'; params += '&walkable=true';
walkableData[y * mapWidth + x] = true;
} else if (editMode === 'wall') {
handler = 'SetTile'; params += '&walkable=false';
walkableData[y * mapWidth + x] = false;
} else if (editMode === 'tile' && selectedSheetId > 0) {
handler = 'PlaceVisualTile';
const layer = parseInt(document.getElementById('tileLayer').value);
const walkable = document.getElementById('tileWalkable').checked;
params += `&sheetId=${selectedSheetId}&frameIndex=${selectedFrameIndex}&layer=${layer}&walkable=${walkable}`;
walkableData[y * mapWidth + x] = walkable;
const idx = visualTiles.findIndex(t => t.x === x && t.y === y && t.l === layer);
const tile = { x, y, sid: selectedSheetId, frame: selectedFrameIndex, l: layer };
if (idx >= 0) visualTiles[idx] = tile; else visualTiles.push(tile);
} else if (editMode === 'erase') {
handler = 'RemoveTile';
visualTiles = visualTiles.filter(t => t.x !== x || t.y !== y);
walkableData[y * mapWidth + x] = false;
} else return;
drawMap();
await fetch(`/admin/dungeons/view?handler=${handler}&${params}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
// ==================== ENTITIES ====================
function updateEntities(players, mobs) {
currentPlayers = players; currentMobs = mobs;
const layer = document.getElementById('entityLayer');
layer.innerHTML = '';
players.forEach(p => {
const div = document.createElement('div');
div.className = 'entity-dot player-dot' + (p.id == selectedPlayerId ? ' selected' : '');
div.style.left = p.x + 'px'; div.style.top = p.y + 'px';
div.title = p.name; div.onclick = () => selectPlayer(p);
layer.appendChild(div);
});
mobs.filter(m => m.alive).forEach(m => {
const div = document.createElement('div');
div.className = 'entity-dot ' + (m.isBoss ? 'boss-dot' : 'mob-dot') + (m.id == selectedMobId ? ' selected' : '');
div.style.left = m.x + 'px'; div.style.top = m.y + 'px';
div.title = m.name; div.onclick = () => selectMob(m);
layer.appendChild(div);
});
}
function selectPlayer(p) {
selectedPlayerId = p.id; selectedMobId = null; closeMobInspector();
document.getElementById('playerInspector').classList.remove('hidden');
document.getElementById('playerInspectorName').textContent = p.name;
document.getElementById('playerInspectorContent').innerHTML = `
<div class="inspector-stat"><span class="text-gray-400">Health</span><span>${Math.round(p.health)}/${Math.round(p.maxHealth)}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Position</span><span>${Math.round(p.x)}, ${Math.round(p.y)}</span></div>`;
updateEntities(currentPlayers, currentMobs);
}
function closePlayerInspector() { selectedPlayerId = null; document.getElementById('playerInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
function selectMob(m) {
selectedMobId = m.id; selectedPlayerId = null; closePlayerInspector();
document.getElementById('mobInspector').classList.remove('hidden');
document.getElementById('mobInspectorName').textContent = m.name;
const abilities = (m.abilities || []).map(a => `${a.name} (${a.key})`).join(', ') || 'None';
const resEntries = m.resistances ? Object.entries(m.resistances) : [];
const resText = resEntries.length ? resEntries.map(([k, v]) => `${k}: ${v}`).join(', ') : 'None';
const lootItems = (m.lootItems || []).map(i => `${i.name} x${i.qty}`).join(', ') || 'None';
document.getElementById('mobInspectorContent').innerHTML = `
<div class="inspector-stat"><span class="text-gray-400">Health</span><span>${m.health}/${m.maxHealth}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Position</span><span>${Math.round(m.x)}, ${Math.round(m.y)}</span></div>
<div class="inspector-stat"><span class="text-gray-400">State</span><span>${m.state}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Abilities</span><span>${abilities}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Resistances</span><span>${resText}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Loot</span><span>${lootItems} (Gold: ${m.lootGold ?? 0})</span></div>`;
const lootGoldInput = document.getElementById('mobLootGold');
if (lootGoldInput) lootGoldInput.value = m.lootGold ?? 0;
updateEntities(currentPlayers, currentMobs);
}
function closeMobInspector() { selectedMobId = null; document.getElementById('mobInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
// ==================== ACTIONS ====================
async function healSelectedPlayer() {
if (!selectedPlayerId) return;
await fetch(`/admin/dungeons/view?handler=HealPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
function teleportPlayerToClick() { teleportMode = true; document.getElementById('teleportBtn').classList.add('btn-primary'); }
async function teleportPlayer(x, y) {
await fetch(`/admin/dungeons/view?handler=TeleportPlayer&id=${dungeonId}&playerId=${selectedPlayerId}&x=${x}&y=${y}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function toggleGodMode() {
godModeEnabled = !godModeEnabled;
await fetch(`/admin/dungeons/view?handler=SetGodMode&id=${dungeonId}&playerId=${selectedPlayerId}&enabled=${godModeEnabled}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
document.getElementById('godModeBtn').textContent = godModeEnabled ? '🛡️ ON' : '🛡️ God';
}
async function killSelectedPlayer() {
if (!confirm('Kill?')) return;
await fetch(`/admin/dungeons/view?handler=KillPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
closePlayerInspector();
}
async function killSelectedMob() {
await fetch(`/admin/dungeons/view?handler=KillMob&id=${dungeonId}&mobId=${selectedMobId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
closeMobInspector();
}
async function healSelectedMob() {
if (!selectedMobId) return;
await fetch(`/admin/dungeons/view?handler=HealMob&id=${dungeonId}&mobId=${selectedMobId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function addMobAbility() {
const abilityId = document.getElementById('mobAbilitySelect').value;
if (!selectedMobId || !abilityId) return;
await fetch(`/admin/dungeons/view?handler=AddMobAbility&id=${dungeonId}&mobId=${selectedMobId}&abilityId=${abilityId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function setMobResistance(remove) {
const key = document.getElementById('mobResistSelect').value;
if (!selectedMobId || !key) return;
const value = parseFloat(document.getElementById('mobResistValue').value || '0');
await fetch(`/admin/dungeons/view?handler=SetMobResistance&id=${dungeonId}&mobId=${selectedMobId}&key=${encodeURIComponent(key)}&value=${value}&remove=${remove}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function setMobLootGold() {
const gold = parseInt(document.getElementById('mobLootGold').value || '0', 10);
if (!selectedMobId) return;
await fetch(`/admin/dungeons/view?handler=SetMobLootGold&id=${dungeonId}&mobId=${selectedMobId}&gold=${gold}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function addMobLootItem() {
const itemId = parseInt(document.getElementById('mobLootItemId').value || '0', 10);
const qty = parseInt(document.getElementById('mobLootItemQty').value || '0', 10);
if (!selectedMobId || itemId <= 0 || qty <= 0) return;
await fetch(`/admin/dungeons/view?handler=AddMobLootItem&id=${dungeonId}&mobId=${selectedMobId}&itemId=${itemId}&quantity=${qty}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
function copyMobPosition() {
const m = currentMobs.find(m => m.id == selectedMobId);
if (m) navigator.clipboard.writeText(`${Math.round(m.x)}, ${Math.round(m.y)}`);
}
async function spawnMob() {
const mobDefId = document.getElementById('spawnMobSelect').value;
if (!mobDefId) return alert('Select a mob');
const x = document.getElementById('spawnX').value, y = document.getElementById('spawnY').value;
await fetch(`/admin/dungeons/view?handler=SpawnMob&id=${dungeonId}&mobDefId=${mobDefId}&x=${x}&y=${y}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
function filterMobSelect(query) {
const select = document.getElementById('spawnMobSelect');
if (!select) return;
const q = (query || '').toLowerCase();
Array.from(select.options).forEach(opt => {
if (!opt.value) return;
opt.hidden = q.length > 0 && !opt.text.toLowerCase().includes(q);
});
}
async function broadcastTiles() {
await fetch(`/admin/dungeons/view?handler=BroadcastTiles&id=${dungeonId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
alert('Tile update queued for broadcast!');
}
async function fetchUpdate() {
try {
const resp = await fetch(`/admin/dungeons/view?handler=Status&id=${dungeonId}`);
if (resp.ok) {
const data = await resp.json();
document.getElementById('playerCount').textContent = data.playerCount;
document.getElementById('mobCount').textContent = data.mobsAlive;
document.getElementById('duration').textContent = data.duration;
updateEntities(data.players, data.mobs);
}
} catch (e) { console.error('Update failed:', e); }
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
document.getElementById('autoRefreshBtn').textContent = 'Auto: ' + (autoRefresh ? 'ON' : 'OFF');
if (autoRefresh) refreshInterval = setInterval(fetchUpdate, 500);
else clearInterval(refreshInterval);
}
document.addEventListener('DOMContentLoaded', init);
</script>
}