Admin updates, dungeon viewer

This commit is contained in:
dingo
2026-01-10 13:43:59 -05:00
parent c43a334d8b
commit ff7357c557
15 changed files with 1033 additions and 1403 deletions
+82
View File
@@ -0,0 +1,82 @@
using System.Collections.Concurrent;
namespace Server.Game.Dungeon;
/// <summary>
/// Admin/management extensions for DungeonHandler
/// </summary>
public partial class DungeonHandler
{
/// <summary>
/// Get all active dungeon instances (for admin viewing)
/// </summary>
public IReadOnlyCollection<DungeonInstance> GetActiveDungeons()
{
return _dungeons.Values.ToList().AsReadOnly();
}
/// <summary>
/// Get a specific dungeon by ID (for admin viewing)
/// </summary>
public DungeonInstance? GetDungeon(Guid id)
{
_dungeons.TryGetValue(id, out var dungeon);
return dungeon;
}
/// <summary>
/// Force close a dungeon (admin action)
/// Removes all players and destroys the instance
/// </summary>
public bool ForceCloseDungeon(Guid dungeonId)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
// Remove all players from the dungeon
foreach (var player in dungeon.Simulation.Players.Values.ToList())
{
try
{
// Send them back to town
// Note: This is a simplified version - in production you'd want to
// properly handle player state transitions
//dungeon.Simulation.RemovePlayer(player.CharacterId);
Console.WriteLine("Force Close Dungeon -- Needs Implemented");
}
catch { /* Ignore errors during cleanup */ }
}
// Remove the dungeon
return _dungeons.TryRemove(dungeonId, out _);
}
/// <summary>
/// Get summary statistics for admin dashboard
/// </summary>
public DungeonStats GetStats()
{
var dungeons = _dungeons.Values.ToList();
return new DungeonStats
{
ActiveCount = dungeons.Count,
TotalPlayers = dungeons.Sum(d => d.Simulation.Players.Count),
TotalMobsAlive = dungeons.Sum(d => d.Simulation.Mobs.Values.Count(m => m.IsAlive)),
CompletedCount = dungeons.Count(d => d.Simulation.Phase == DungeonPhase.Cleared),
BossesKilled = dungeons.Count(d => d.BossKilled)
};
}
}
/// <summary>
/// Statistics for admin dashboard
/// </summary>
public class DungeonStats
{
public int ActiveCount { get; set; }
public int TotalPlayers { get; set; }
public int TotalMobsAlive { get; set; }
public int CompletedCount { get; set; }
public int BossesKilled { get; set; }
}
+7
View File
@@ -0,0 +1,7 @@
public enum DungeonPhase
{
Active,
Cleared,
Abandoned
}
+2 -7
View File
@@ -7,7 +7,7 @@ namespace Server.Game.Dungeon;
/// <summary>
/// Runtime simulation for an active dungeon instance
/// </summary>
public class DungeonSimulation
public partial class DungeonSimulation
{
public DungeonLayout Layout { get; }
public int Tier { get; }
@@ -1052,9 +1052,4 @@ public class DungeonSimulation
}
}
public enum DungeonPhase
{
Active,
Cleared,
Abandoned
}
+23
View File
@@ -0,0 +1,23 @@
namespace Server.Game.Dungeon;
/// <summary>
/// Admin extensions for DungeonSimulation
/// </summary>
public partial class DungeonSimulation
{
/// <summary>
/// Force the dungeon to complete (admin action)
/// </summary>
public void ForceComplete()
{
Phase = DungeonPhase.Cleared;
}
/// <summary>
/// Force the dungeon phase (admin action)
/// </summary>
public void SetPhase(DungeonPhase phase)
{
Phase = phase;
}
}
+237
View File
@@ -0,0 +1,237 @@
@page "/admin/dungeons"
@model Admin.Pages.Dungeons.IndexModel
@{
ViewData["Title"] = "Dungeon Management";
}
<style>
.dungeon-card {
transition: all 0.2s ease;
}
.dungeon-card:hover {
border-color: rgba(99, 102, 241, 0.5);
}
.phase-active { color: #4ade80; }
.phase-completed { color: #60a5fa; }
.phase-failed { color: #f87171; }
.stat-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
}
.live-indicator {
width: 8px;
height: 8px;
background: #4ade80;
border-radius: 50%;
animation: pulse 2s infinite;
}
@@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
</style>
<div class="space-y-6">
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 class="text-3xl font-bold text-white">Dungeon Management</h1>
<p class="text-gray-400 mt-1">View and manage active dungeon instances</p>
</div>
<div class="flex gap-2">
<button onclick="refreshDungeons()" class="btn btn-secondary">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
</svg>
Refresh
</button>
</div>
</div>
@if (TempData["Message"] != null)
{
<div class="p-4 rounded-lg bg-green-900/50 border border-green-700 text-green-300">
@TempData["Message"]
</div>
}
@if (TempData["Error"] != null)
{
<div class="p-4 rounded-lg bg-red-900/50 border border-red-700 text-red-300">
@TempData["Error"]
</div>
}
<!-- Stats Overview -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div class="card p-4">
<div class="text-2xl font-bold text-white">@Model.ActiveCount</div>
<div class="text-gray-400 text-sm">Active Dungeons</div>
</div>
<div class="card p-4">
<div class="text-2xl font-bold text-green-400">@Model.TotalPlayers</div>
<div class="text-gray-400 text-sm">Players In Dungeons</div>
</div>
<div class="card p-4">
<div class="text-2xl font-bold text-blue-400">@Model.CompletedToday</div>
<div class="text-gray-400 text-sm">Completed Today</div>
</div>
<div class="card p-4">
<div class="text-2xl font-bold text-yellow-400">@Model.AverageDuration</div>
<div class="text-gray-400 text-sm">Avg Duration (min)</div>
</div>
</div>
<!-- Filters -->
<div class="card p-4">
<form method="get" class="flex flex-wrap gap-3 items-end">
<div>
<label class="text-xs text-gray-400 mb-1 block">Status</label>
<select name="status" class="input text-sm">
<option value="">All Status</option>
<option value="active" selected="@(Model.StatusFilter == "active")">Active</option>
<option value="completed" selected="@(Model.StatusFilter == "completed")">Completed</option>
</select>
</div>
<div>
<label class="text-xs text-gray-400 mb-1 block">Tier</label>
<select name="tier" class="input text-sm">
<option value="">All Tiers</option>
@for (int i = 1; i <= 10; i++)
{
<option value="@i" selected="@(Model.TierFilter == i)">Tier @i</option>
}
</select>
</div>
<div>
<label class="text-xs text-gray-400 mb-1 block">Level Bracket</label>
<select name="bracket" class="input text-sm">
<option value="">All Brackets</option>
<option value="1" selected="@(Model.BracketFilter == 1)">1-10</option>
<option value="2" selected="@(Model.BracketFilter == 2)">11-20</option>
<option value="3" selected="@(Model.BracketFilter == 3)">21-30</option>
<option value="4" selected="@(Model.BracketFilter == 4)">31-40</option>
<option value="5" selected="@(Model.BracketFilter == 5)">41-50</option>
</select>
</div>
<button type="submit" class="btn btn-secondary text-sm">Filter</button>
<a href="/admin/dungeons" class="btn btn-ghost text-sm">Clear</a>
</form>
</div>
<!-- Active Dungeons -->
<div class="space-y-4">
<h2 class="text-xl font-semibold text-white flex items-center gap-2">
<div class="live-indicator"></div>
Active Dungeons (@Model.Dungeons.Count)
</h2>
@if (Model.Dungeons.Count > 0)
{
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
@foreach (var dungeon in Model.Dungeons)
{
<div class="dungeon-card card p-4">
<div class="flex items-start justify-between mb-3">
<div>
<div class="flex items-center gap-2">
<span class="text-lg font-semibold text-white">Tier @dungeon.Tier</span>
<span class="stat-badge bg-indigo-500/20 text-indigo-300">Lvl @dungeon.LevelBracketMin-@dungeon.LevelBracketMax</span>
@if (dungeon.BossKilled)
{
<span class="stat-badge bg-green-500/20 text-green-300">Boss Killed</span>
}
</div>
<div class="text-xs text-gray-500 mt-1 font-mono">@dungeon.Id.ToString()[..8]...</div>
</div>
<div class="text-right">
<span class="@GetPhaseClass(dungeon.Phase)">@dungeon.Phase</span>
<div class="text-xs text-gray-500">@dungeon.Duration</div>
</div>
</div>
<div class="grid grid-cols-3 gap-2 text-sm mb-3">
<div class="bg-gray-800/50 rounded p-2 text-center">
<div class="text-white font-semibold">@dungeon.PlayerCount</div>
<div class="text-xs text-gray-400">Players</div>
</div>
<div class="bg-gray-800/50 rounded p-2 text-center">
<div class="text-white font-semibold">@dungeon.MobsAlive / @dungeon.TotalMobs</div>
<div class="text-xs text-gray-400">Mobs</div>
</div>
<div class="bg-gray-800/50 rounded p-2 text-center">
<div class="text-white font-semibold">@dungeon.RoomCount</div>
<div class="text-xs text-gray-400">Rooms</div>
</div>
</div>
<div class="text-xs text-gray-400 mb-3">
<span>Created by: <span class="text-white">@dungeon.CreatorName</span></span>
<span class="mx-2">•</span>
<span>Seed: <span class="font-mono text-gray-300">@dungeon.Seed</span></span>
</div>
<div class="flex gap-2">
<a href="/admin/dungeons/view?id=@dungeon.Id" class="btn btn-sm btn-secondary flex-1">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
</svg>
View
</a>
<form method="post" asp-page-handler="Delete" onsubmit="return confirm('Delete this dungeon? All players will be removed.')">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@dungeon.Id" />
<button type="submit" class="btn btn-sm btn-danger">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
</svg>
</button>
</form>
</div>
</div>
}
</div>
}
else
{
<div class="card p-8 text-center text-gray-500">
<div class="text-4xl mb-2">🏰</div>
<p>No active dungeons at the moment.</p>
<p class="text-sm mt-1">Dungeons are created when players enter them.</p>
</div>
}
</div>
</div>
@section Scripts {
<script>
function refreshDungeons() {
window.location.reload();
}
// Auto-refresh every 30 seconds
setInterval(() => {
// Only refresh if page is visible
if (!document.hidden) {
refreshDungeons();
}
}, 30000);
</script>
}
@functions {
string GetPhaseClass(string phase)
{
return phase.ToLower() switch
{
"active" => "phase-active",
"completed" => "phase-completed",
"failed" => "phase-failed",
_ => "text-gray-400"
};
}
}
@@ -0,0 +1,133 @@
using Microsoft.AspNetCore.Mvc;
using Server.Game.Dungeon;
namespace Server.Services.Admin.Pages.Dungeons;
public class IndexModel : AdminPageModel
{
private readonly DungeonHandler _dungeonHandler;
public IndexModel(DungeonHandler dungeonHandler)
{
_dungeonHandler = dungeonHandler;
}
public List<DungeonSummary> Dungeons { get; set; } = new();
// Stats
public int ActiveCount { get; set; }
public int TotalPlayers { get; set; }
public int CompletedToday { get; set; }
public string AverageDuration { get; set; } = "0";
// Filters
public string? StatusFilter { get; set; }
public int? TierFilter { get; set; }
public int? BracketFilter { get; set; }
public void OnGet(string? status, int? tier, int? bracket)
{
StatusFilter = status;
TierFilter = tier;
BracketFilter = bracket;
// Get all active dungeons from the handler
var allDungeons = _dungeonHandler.GetActiveDungeons();
// Apply filters
var filtered = allDungeons.AsEnumerable();
if (!string.IsNullOrEmpty(status))
{
if (status == "active")
filtered = filtered.Where(d => d.Simulation.Phase == DungeonPhase.Active);
else if (status == "completed")
filtered = filtered.Where(d => d.Simulation.Phase == DungeonPhase.Cleared);
}
if (tier.HasValue)
{
filtered = filtered.Where(d => d.Tier == tier.Value);
}
if (bracket.HasValue)
{
int minLevel = (bracket.Value - 1) * 10 + 1;
int maxLevel = bracket.Value * 10;
filtered = filtered.Where(d => d.LevelBracketMin >= minLevel && d.LevelBracketMax <= maxLevel);
}
// Transform to summary
Dungeons = filtered.Select(d => new DungeonSummary
{
Id = d.Id,
Tier = d.Tier,
Seed = d.Seed,
LevelBracketMin = d.LevelBracketMin,
LevelBracketMax = d.LevelBracketMax,
CreatorName = d.CreatorName,
CreatedAt = d.CreatedAt,
Phase = d.Simulation.Phase.ToString(),
PlayerCount = d.Simulation.Players.Count,
MobsAlive = d.Simulation.Mobs.Values.Count(m => m.IsAlive),
TotalMobs = d.Simulation.Mobs.Count,
RoomCount = d.LayoutV2?.Rooms?.Count ?? d.Simulation.Layout.Rooms.Count,
BossKilled = d.BossKilled,
Duration = FormatDuration(DateTime.UtcNow - d.CreatedAt)
}).OrderByDescending(d => d.CreatedAt).ToList();
// Calculate stats
ActiveCount = allDungeons.Count;
TotalPlayers = allDungeons.Sum(d => d.Simulation.Players.Count);
// Average duration of completed dungeons (simplified)
var completedDungeons = allDungeons.Where(d => d.Simulation.Phase == DungeonPhase.Cleared).ToList();
if (completedDungeons.Any())
{
var avgMinutes = completedDungeons.Average(d => (DateTime.UtcNow - d.CreatedAt).TotalMinutes);
AverageDuration = avgMinutes.ToString("F1");
}
}
public IActionResult OnPostDelete(Guid id)
{
var result = _dungeonHandler.ForceCloseDungeon(id);
if (result)
{
TempData["Message"] = "Dungeon deleted successfully.";
}
else
{
TempData["Error"] = "Failed to delete dungeon. It may have already been closed.";
}
return RedirectToPage();
}
private static string FormatDuration(TimeSpan duration)
{
if (duration.TotalHours >= 1)
return $"{(int)duration.TotalHours}h {duration.Minutes}m";
if (duration.TotalMinutes >= 1)
return $"{(int)duration.TotalMinutes}m";
return $"{(int)duration.TotalSeconds}s";
}
}
public class DungeonSummary
{
public Guid Id { get; set; }
public int Tier { get; set; }
public int Seed { get; set; }
public int LevelBracketMin { get; set; }
public int LevelBracketMax { get; set; }
public string CreatorName { get; set; } = "";
public DateTime CreatedAt { get; set; }
public string Phase { get; set; } = "";
public int PlayerCount { get; set; }
public int MobsAlive { get; set; }
public int TotalMobs { get; set; }
public int RoomCount { get; set; }
public bool BossKilled { get; set; }
public string Duration { get; set; } = "";
}
+373
View File
@@ -0,0 +1,373 @@
@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-canvas {
image-rendering: pixelated;
}
.entity-dot {
position: absolute;
border-radius: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
.player-dot {
background: #4ade80;
width: 10px;
height: 10px;
box-shadow: 0 0 6px #4ade80;
}
.mob-dot {
background: #f87171;
width: 6px;
height: 6px;
}
.boss-dot {
background: #fbbf24;
width: 12px;
height: 12px;
box-shadow: 0 0 8px #fbbf24;
}
.stat-card {
background: rgba(30, 30, 50, 0.8);
border: 1px solid #374151;
border-radius: 8px;
padding: 12px;
}
.player-list-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
background: rgba(30, 30, 50, 0.5);
border-radius: 6px;
margin-bottom: 4px;
}
.health-bar {
height: 4px;
background: #374151;
border-radius: 2px;
overflow: hidden;
}
.health-bar-fill {
height: 100%;
background: linear-gradient(90deg, #ef4444, #22c55e);
transition: width 0.3s ease;
}
</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>
<p class="text-gray-400">This dungeon may have been closed or doesn't exist.</p>
<a href="/admin/dungeons" class="btn btn-primary mt-4">Back to Dungeons</a>
</div>
}
else
{
<div class="flex flex-col lg:flex-row gap-6">
<!-- Left: Map View -->
<div class="flex-1">
<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-2 text-sm text-gray-400">
<div class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<span>Live</span>
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="btn btn-sm btn-ghost ml-2">
Auto: ON
</button>
</div>
</div>
<div class="dungeon-map" id="mapContainer" style="height: 500px;">
<canvas id="mapCanvas" class="map-canvas"></canvas>
<div id="entityOverlay"></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 class="flex items-center gap-1">
<div class="w-3 h-3 bg-blue-400"></div>
<span>Floor</span>
</div>
<div class="flex items-center gap-1">
<div class="w-3 h-3 bg-gray-700"></div>
<span>Wall</span>
</div>
</div>
</div>
</div>
<!-- Right: Info Panel -->
<div class="w-full lg:w-80 space-y-4">
<!-- Dungeon Info -->
<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">ID</span>
<span class="text-white font-mono text-xs">@Model.Dungeon.Id.ToString()[..12]...</span>
</div>
<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">Level Bracket</span>
<span class="text-white">@Model.Dungeon.LevelBracketMin - @Model.Dungeon.LevelBracketMax</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Seed</span>
<span class="text-white font-mono">@Model.Dungeon.Seed</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Phase</span>
<span class="@(Model.Dungeon.Simulation.Phase == DungeonPhase.Active ? "text-green-400" : "text-blue-400")">
@Model.Dungeon.Simulation.Phase
</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Creator</span>
<span class="text-white">@Model.Dungeon.CreatorName</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Created</span>
<span class="text-white">@Model.Dungeon.CreatedAt.ToString("HH:mm:ss")</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>
<!-- Stats -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">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 Alive</div>
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-blue-400">@Model.RoomCount</div>
<div class="text-xs text-gray-400">Rooms</div>
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold @(Model.Dungeon.BossKilled ? "text-yellow-400" : "text-gray-500")">
@(Model.Dungeon.BossKilled ? "✓" : "✗")
</div>
<div class="text-xs text-gray-400">Boss Killed</div>
</div>
</div>
</div>
<!-- Players -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Players (@Model.Dungeon.Simulation.Players.Count)</h3>
<div id="playerList" class="space-y-1 max-h-48 overflow-y-auto">
@foreach (var player in Model.Dungeon.Simulation.Players.Values)
{
var healthPct = player.MaxHealth > 0 ? (player.Health * 100 / player.MaxHealth) : 0;
<div class="player-list-item">
<div class="w-2 h-2 rounded-full bg-green-400"></div>
<div class="flex-1 min-w-0">
<div class="text-white text-sm truncate">@player.CharacterName</div>
<div class="health-bar mt-1">
<div class="health-bar-fill" style="width: @healthPct%"></div>
</div>
</div>
<div class="text-xs text-gray-400">@player.Health/@player.MaxHealth</div>
</div>
}
@if (Model.Dungeon.Simulation.Players.Count == 0)
{
<div class="text-gray-500 text-sm text-center py-2">No players</div>
}
</div>
</div>
<!-- Actions -->
<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 mobs in this dungeon?')">
Kill All Mobs
</button>
</form>
<form method="post" asp-page-handler="CompleteDungeon">
@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('Force complete this dungeon?')">
Force Complete
</button>
</form>
<form method="post" asp-page-handler="Delete">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-danger w-full text-sm" onclick="return confirm('Delete this dungeon? All players will be removed.')">
Delete Dungeon
</button>
</form>
</div>
</div>
</div>
</div>
}
@section Scripts {
<script>
const dungeonId = '@Model.Dungeon?.Id';
const mapWidth = @(Model.MapWidth);
const mapHeight = @(Model.MapHeight);
const walkableData = @Html.Raw(Model.WalkableJson);
let autoRefresh = true;
let refreshInterval;
function initMap() {
const canvas = document.getElementById('mapCanvas');
const container = document.getElementById('mapContainer');
if (!canvas || !container) return;
const ctx = canvas.getContext('2d');
const scale = Math.min(
(container.clientWidth - 20) / mapWidth,
(container.clientHeight - 20) / mapHeight,
8 // Max scale
);
canvas.width = mapWidth * scale;
canvas.height = mapHeight * scale;
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
// Draw tiles
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
const idx = y * mapWidth + x;
const walkable = walkableData[idx];
ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * scale, y * scale, scale, scale);
// Grid lines
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.strokeRect(x * scale, y * scale, scale, scale);
}
}
// Store scale for entity positioning
canvas.dataset.scale = scale;
}
function updateEntities(players, mobs) {
const canvas = document.getElementById('mapCanvas');
const overlay = document.getElementById('entityOverlay');
if (!canvas || !overlay) return;
const scale = parseFloat(canvas.dataset.scale) || 4;
const tileSize = 32; // Game tile size
overlay.innerHTML = '';
// Draw players
players.forEach(p => {
const div = document.createElement('div');
div.className = 'entity-dot player-dot';
div.style.left = (p.x / tileSize * scale) + 'px';
div.style.top = (p.y / tileSize * scale) + 'px';
div.title = p.name;
overlay.appendChild(div);
});
// Draw mobs
mobs.forEach(m => {
if (!m.alive) return;
const div = document.createElement('div');
div.className = 'entity-dot ' + (m.isBoss ? 'boss-dot' : 'mob-dot');
div.style.left = (m.x / tileSize * scale) + 'px';
div.style.top = (m.y / tileSize * scale) + 'px';
div.title = m.name;
overlay.appendChild(div);
});
}
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('Failed to fetch update:', e);
}
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
document.getElementById('autoRefreshBtn').textContent = 'Auto: ' + (autoRefresh ? 'ON' : 'OFF');
if (autoRefresh) {
refreshInterval = setInterval(fetchUpdate, 2000);
} else {
clearInterval(refreshInterval);
}
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
initMap();
// Initial entity positions
const initialPlayers = @Html.Raw(Model.PlayersJson);
const initialMobs = @Html.Raw(Model.MobsJson);
updateEntities(initialPlayers, initialMobs);
// Start auto-refresh
refreshInterval = setInterval(fetchUpdate, 2000);
});
// Handle resize
window.addEventListener('resize', initMap);
</script>
}
@@ -0,0 +1,163 @@
using Microsoft.AspNetCore.Mvc;
using Server.Game.Dungeon;
using System.Text.Json;
namespace Server.Services.Admin.Pages.Dungeons;
public class ViewModel : AdminPageModel
{
private readonly DungeonHandler _dungeonHandler;
public ViewModel(DungeonHandler dungeonHandler)
{
_dungeonHandler = dungeonHandler;
}
public DungeonInstance? Dungeon { get; set; }
public string Duration { get; set; } = "";
public int RoomCount { get; set; }
public int MapWidth { get; set; }
public int MapHeight { get; set; }
public string WalkableJson { get; set; } = "[]";
public string PlayersJson { get; set; } = "[]";
public string MobsJson { get; set; } = "[]";
public void OnGet(Guid id)
{
Dungeon = _dungeonHandler.GetDungeon(id);
if (Dungeon == null) return;
Duration = FormatDuration(DateTime.UtcNow - Dungeon.CreatedAt);
RoomCount = Dungeon.LayoutV2?.Rooms?.Count ?? Dungeon.Simulation.Layout.Rooms.Count;
// Get map dimensions
var layout = Dungeon.LayoutV2 ?? (DungeonLayoutV2?)null;
if (layout != null)
{
MapWidth = layout.Width;
MapHeight = layout.Height;
// Flatten walkable array
var walkable = new List<bool>();
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
walkable.Add(layout.Walkable[x, y]);
}
}
WalkableJson = JsonSerializer.Serialize(walkable);
}
else
{
// Fallback for V1 layouts
MapWidth = 100;
MapHeight = 100;
WalkableJson = "[]";
}
// Serialize entity positions
PlayersJson = JsonSerializer.Serialize(
Dungeon.Simulation.Players.Values.Select(p => new
{
name = p.CharacterName,
x = p.X,
y = p.Y,
health = p.Health,
maxHealth = p.MaxHealth
})
);
MobsJson = JsonSerializer.Serialize(
Dungeon.Simulation.Mobs.Values.Select(m => new
{
name = m.Name,
x = m.X,
y = m.Y,
alive = m.IsAlive,
isBoss = m.Type == DataServer.Data.Enums.MobType.Boss
})
);
}
public IActionResult OnGetStatus(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
if (dungeon == null)
return new JsonResult(new { error = "Not found" }) { StatusCode = 404 };
return new JsonResult(new
{
playerCount = dungeon.Simulation.Players.Count,
mobsAlive = dungeon.Simulation.Mobs.Values.Count(m => m.IsAlive),
duration = FormatDuration(DateTime.UtcNow - dungeon.CreatedAt),
players = dungeon.Simulation.Players.Values.Select(p => new
{
name = p.CharacterName,
x = p.X,
y = p.Y
}),
mobs = dungeon.Simulation.Mobs.Values.Where(m => m.IsAlive).Select(m => new
{
name = m.Name,
x = m.X,
y = m.Y,
alive = m.IsAlive,
isBoss = m.Type == DataServer.Data.Enums.MobType.Boss
})
});
}
public IActionResult OnPostKillAllMobs(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
if (dungeon != null)
{
foreach (var mob in dungeon.Simulation.Mobs.Values)
{
mob.Health = 0;
mob.IsAlive = false;
}
TempData["Message"] = "All mobs killed.";
}
return RedirectToPage(new { id });
}
public IActionResult OnPostCompleteDungeon(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
if (dungeon != null)
{
dungeon.Simulation.ForceComplete();
TempData["Message"] = "Dungeon marked as completed.";
}
return RedirectToPage(new { id });
}
public IActionResult OnPostDelete(Guid id)
{
var result = _dungeonHandler.ForceCloseDungeon(id);
if (result)
{
TempData["Message"] = "Dungeon deleted.";
}
else
{
TempData["Error"] = "Failed to delete dungeon.";
}
return RedirectToPage("/Dungeons/Index");
}
private static string FormatDuration(TimeSpan duration)
{
if (duration.TotalHours >= 1)
return $"{(int)duration.TotalHours}h {duration.Minutes}m";
if (duration.TotalMinutes >= 1)
return $"{(int)duration.TotalMinutes}m {duration.Seconds}s";
return $"{(int)duration.TotalSeconds}s";
}
}
+1 -1
View File
@@ -493,7 +493,7 @@
<!-- Animations Section -->
@if (!Model.IsNew)
{
<div class="card">
<div id="animations-section" class="card">
<div class="p-4 border-b border-gray-700 flex items-center justify-between">
<h2 class="text-lg font-semibold text-white">Animations (@Model.MobAnimations.Count)</h2>
<div class="flex gap-2">
+3 -3
View File
@@ -451,7 +451,7 @@ public class EditModel : AdminPageModel
_db.MobAnimationAssignments.Add(assignment);
await _db.SaveChangesAsync();
return RedirectToPage("/Mobs/Edit", new { id = mobId });
return Redirect($"/admin/mobs/edit?id={mobId}#animations-section");
}
public async Task<IActionResult> OnPostRemoveAnimationAsync(int assignmentId, int mobId)
@@ -463,7 +463,7 @@ public class EditModel : AdminPageModel
await _db.SaveChangesAsync();
}
return RedirectToPage("/Mobs/Edit", new { id = mobId });
return Redirect($"/admin/mobs/edit?id={mobId}#animations-section");
}
public async Task<IActionResult> OnPostToggleAnimationAsync(int assignmentId, int mobId)
@@ -475,6 +475,6 @@ public class EditModel : AdminPageModel
await _db.SaveChangesAsync();
}
return RedirectToPage("/Mobs/Edit", new { id = mobId });
return Redirect($"/admin/mobs/edit?id={mobId}#animations-section");
}
}
@@ -1,647 +0,0 @@
@page "/admin/roomtemplates/edit"
@model RoomTemplates.EditModel
@using DataServer.Data.Entities
@{
ViewData["Title"] = Model.Room.Id == 0 ? "New Room Template" : $"Edit: {Model.Room.Name}";
var roomTypes = Enum.GetValues<RoomType>();
var tileTypes = Enum.GetValues<TileType>();
}
<div class="mb-4">
<a href="/admin/roomtemplates" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Room Templates</a>
</div>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded text-sm @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
<!-- Room Settings -->
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-4">Room Settings</h2>
<form method="post" id="roomForm">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Room.Id" />
<input type="hidden" asp-for="Room.TileDataJson" id="tileDataJson" />
<input type="hidden" asp-for="Room.SpawnPointsJson" id="spawnPointsJson" />
<input type="hidden" asp-for="Room.ConnectionPointsJson" id="connectionPointsJson" />
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Name</label>
<input type="text" asp-for="Room.Name" class="input w-full text-sm" placeholder="Treasure Room A" required />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Type</label>
<select asp-for="Room.Type" class="input w-full text-sm">
@foreach (var t in roomTypes)
{
<option value="@((int)t)">@t</option>
}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Description</label>
<textarea asp-for="Room.Description" class="input w-full text-sm" rows="2" placeholder="Optional description"></textarea>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Tags</label>
<input type="text" asp-for="Room.Tags" class="input w-full text-sm" placeholder="treasure, medium, stone" />
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Width</label>
<input type="number" asp-for="Room.Width" class="input w-full text-sm" min="3" max="50" onchange="resizeGrid()" />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Height</label>
<input type="number" asp-for="Room.Height" class="input w-full text-sm" min="3" max="50" onchange="resizeGrid()" />
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Min Tier</label>
<input type="number" asp-for="Room.MinTier" class="input w-full text-sm" min="1" />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Max Tier (0=∞)</label>
<input type="number" asp-for="Room.MaxTier" class="input w-full text-sm" min="0" />
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Weight</label>
<input type="number" asp-for="Room.Weight" class="input w-full text-sm" min="1" />
<p class="text-xs text-gray-500 mt-1">Higher = more common in generation</p>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Room.IsEnabled" class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
<label asp-for="Room.IsEnabled" class="text-sm text-gray-300">Enabled</label>
</div>
<div class="pt-3 border-t border-gray-700">
<button type="submit" class="btn btn-primary w-full">Save Room Template</button>
</div>
</div>
</form>
</div>
<!-- Tile Palette & Tools -->
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-4">Tools & Palette</h2>
<!-- Tool Mode Selector -->
<div class="mb-4 p-2 bg-gray-800 rounded">
<div class="flex gap-1 mb-2">
<button onclick="setMode('tiles')" class="flex-1 px-2 py-1.5 text-xs rounded mode-btn active" data-mode="tiles">🎨 Tiles</button>
<button onclick="setMode('spawns')" class="flex-1 px-2 py-1.5 text-xs rounded mode-btn" data-mode="spawns">📍 Spawns</button>
<button onclick="setMode('connections')" class="flex-1 px-2 py-1.5 text-xs rounded mode-btn" data-mode="connections">🚪 Connections</button>
</div>
</div>
<!-- Tile Mode Panel -->
<div id="tileModePanel">
@if (Model.TileMapSheets.Count == 0)
{
<p class="text-gray-400 text-sm">No tilemap sheets found. <a href="/admin/tilemaps" class="text-blue-400">Create one first.</a></p>
}
else
{
<!-- TileMap Sheet Selector -->
<div class="mb-3">
<select id="sheetSelector" class="input w-full text-sm" onchange="selectSheet(this.value)">
@foreach (var sheet in Model.TileMapSheets)
{
<option value="@sheet.Id">@sheet.Name (@(sheet.Tiles?.Count ?? 0) tiles)</option>
}
</select>
</div>
<!-- Type Filter -->
<div class="mb-3 flex flex-wrap gap-1">
<button onclick="filterTiles('all')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter active" data-filter="all">All</button>
<button onclick="filterTiles('Floor')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Floor">Floor</button>
<button onclick="filterTiles('Wall')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Wall">Wall</button>
<button onclick="filterTiles('Door')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Door">Door</button>
</div>
<!-- Tile Grid -->
<div id="tilePalette" class="bg-gray-900 rounded p-2 overflow-auto" style="max-height: 35vh;">
<!-- Populated by JavaScript -->
</div>
<!-- Selected Tile Info -->
<div id="selectedTileInfo" class="mt-3 p-2 bg-gray-800 rounded text-xs hidden">
<span class="text-gray-400">Selected:</span>
<span id="selectedTileName" class="text-white ml-1">None</span>
</div>
<!-- Tools -->
<div class="mt-3 flex flex-wrap gap-2">
<button onclick="setTool('paint')" class="btn btn-secondary text-xs py-1 px-2 tool-btn active" data-tool="paint">🖌️ Paint</button>
<button onclick="setTool('erase')" class="btn btn-secondary text-xs py-1 px-2 tool-btn" data-tool="erase">🧹 Erase</button>
<button onclick="setTool('fill')" class="btn btn-secondary text-xs py-1 px-2 tool-btn" data-tool="fill">🪣 Fill</button>
<button onclick="clearAllTiles()" class="btn bg-red-600 hover:bg-red-700 text-xs py-1 px-2">Clear</button>
</div>
}
</div>
<!-- Spawn Mode Panel -->
<div id="spawnModePanel" class="hidden">
<p class="text-sm text-gray-400 mb-3">Click on the grid to place spawn points.</p>
<div class="space-y-2">
<button onclick="setSpawnType('PlayerSpawn')" class="w-full px-3 py-2 text-sm rounded flex items-center gap-2 spawn-type-btn" data-spawn="PlayerSpawn">
<span class="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-white text-xs">P</span>
<span>Player Spawn</span>
</button>
<button onclick="setSpawnType('MobSpawn')" class="w-full px-3 py-2 text-sm rounded flex items-center gap-2 spawn-type-btn active" data-spawn="MobSpawn">
<span class="w-6 h-6 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">M</span>
<span>Mob Spawn</span>
</button>
<button onclick="setSpawnType('BossSpawn')" class="w-full px-3 py-2 text-sm rounded flex items-center gap-2 spawn-type-btn" data-spawn="BossSpawn">
<span class="w-6 h-6 bg-purple-500 rounded-full flex items-center justify-center text-white text-xs">B</span>
<span>Boss Spawn</span>
</button>
<button onclick="setSpawnType('ChestSpawn')" class="w-full px-3 py-2 text-sm rounded flex items-center gap-2 spawn-type-btn" data-spawn="ChestSpawn">
<span class="w-6 h-6 bg-yellow-500 rounded-full flex items-center justify-center text-white text-xs">C</span>
<span>Chest Spawn</span>
</button>
</div>
<div class="mt-4 p-2 bg-gray-800 rounded text-xs">
<p class="text-gray-400 mb-2">Spawn Points: <span id="spawnCount">0</span></p>
<button onclick="clearAllSpawns()" class="btn bg-red-600 hover:bg-red-700 text-xs py-1 px-2">Clear All Spawns</button>
</div>
</div>
<!-- Connection Mode Panel -->
<div id="connectionModePanel" class="hidden">
<p class="text-sm text-gray-400 mb-3">Click on room edges to add/remove connection points (where hallways attach).</p>
<div class="grid grid-cols-2 gap-2 mb-4">
<div class="p-2 bg-gray-800 rounded text-center">
<span class="text-cyan-400 font-bold">N</span>
<p class="text-xs text-gray-500">North: <span id="connNorth">0</span></p>
</div>
<div class="p-2 bg-gray-800 rounded text-center">
<span class="text-cyan-400 font-bold">S</span>
<p class="text-xs text-gray-500">South: <span id="connSouth">0</span></p>
</div>
<div class="p-2 bg-gray-800 rounded text-center">
<span class="text-cyan-400 font-bold">E</span>
<p class="text-xs text-gray-500">East: <span id="connEast">0</span></p>
</div>
<div class="p-2 bg-gray-800 rounded text-center">
<span class="text-cyan-400 font-bold">W</span>
<p class="text-xs text-gray-500">West: <span id="connWest">0</span></p>
</div>
</div>
<div class="p-2 bg-gray-800 rounded text-xs">
<p class="text-gray-400 mb-2">Connection Width:</p>
<input type="number" id="connectionWidth" value="2" min="1" max="5" class="input w-full text-sm" />
</div>
<button onclick="clearAllConnections()" class="mt-3 btn bg-red-600 hover:bg-red-700 text-xs py-1 px-2">Clear All Connections</button>
</div>
</div>
<!-- Room Editor Canvas -->
<div class="card p-4 xl:col-span-1">
<div class="flex items-center justify-between mb-4">
<h2 class="text-lg font-semibold text-white">Room Editor</h2>
<span id="gridInfo" class="text-sm text-gray-400">@Model.Room.Width × @Model.Room.Height</span>
</div>
<div class="bg-gray-900 rounded p-2 overflow-auto" style="max-height: 70vh;">
<div id="roomCanvas" class="relative inline-block" style="image-rendering: pixelated;">
<!-- Grid will be rendered by JavaScript -->
</div>
</div>
<div class="mt-3 text-xs text-gray-400">
<p>Tiles: Click to place • Right-click to erase • Drag to paint</p>
<p>Spawns: Click to place/remove • Connections: Click room edges</p>
</div>
<!-- Legend -->
<div class="mt-3 p-2 bg-gray-800 rounded">
<p class="text-xs text-gray-400 mb-2">Legend:</p>
<div class="flex flex-wrap gap-2 text-xs">
<span class="flex items-center gap-1"><span class="w-3 h-3 bg-green-500 rounded-full"></span> Player</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 bg-red-500 rounded-full"></span> Mob</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 bg-purple-500 rounded-full"></span> Boss</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 bg-yellow-500 rounded-full"></span> Chest</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 bg-cyan-500 rounded"></span> Connection</span>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
// Configuration
const TILE_DISPLAY_SIZE = 24;
let roomWidth = @Model.Room.Width;
let roomHeight = @Model.Room.Height;
let currentMode = 'tiles'; // tiles, spawns, connections
let currentTool = 'paint';
let selectedTile = null;
let selectedSheetId = @(Model.TileMapSheets.FirstOrDefault()?.Id ?? 0);
let isMouseDown = false;
let currentFilter = 'all';
let selectedSpawnType = 'MobSpawn';
// Room data
let roomTiles = @Html.Raw(Model.Room.TileDataJson ?? "[]");
let spawnPoints = @Html.Raw(Model.Room.SpawnPointsJson ?? "[]");
let connectionPoints = @Html.Raw(Model.Room.ConnectionPointsJson ?? "[]");
// Tilemap sheets data
const sheets = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.TileMapSheets.Select(s => new {
s.Id, s.Name, s.CdnPath, s.TileWidth, s.TileHeight, s.SheetWidth, s.SheetHeight, s.Columns, s.Rows,
Tiles = (s.Tiles ?? new List<TileDefinition>()).Select(t => new { t.Id, t.FrameIndex, t.Name, Type = (int)t.Type, t.Tags, t.IsWalkable }).ToArray()
})));
const cdnBaseUrl = '@Model.CdnBaseUrl';
const TileType = { Floor: 0, Wall: 1, Door: 2, Water: 3, Lava: 4, Pit: 5, Stairs: 6, PlayerSpawn: 10, MobSpawn: 11, BossSpawn: 12, ChestSpawn: 13 };
const TileTypeName = { 0: 'Floor', 1: 'Wall', 2: 'Door', 3: 'Water', 4: 'Lava', 5: 'Pit', 6: 'Stairs', 10: 'PlayerSpawn', 11: 'MobSpawn', 12: 'BossSpawn', 13: 'ChestSpawn' };
const SpawnColors = { PlayerSpawn: '#22c55e', MobSpawn: '#ef4444', BossSpawn: '#a855f7', ChestSpawn: '#eab308' };
const SpawnLetters = { PlayerSpawn: 'P', MobSpawn: 'M', BossSpawn: 'B', ChestSpawn: 'C' };
// Initialize
document.addEventListener('DOMContentLoaded', () => {
if (sheets.length > 0) {
selectSheet(sheets[0].Id);
}
renderRoomGrid();
updateCounters();
});
// Mode switching
function setMode(mode) {
currentMode = mode;
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active', 'bg-blue-600'));
document.querySelector(`.mode-btn[data-mode="${mode}"]`)?.classList.add('active', 'bg-blue-600');
document.getElementById('tileModePanel').classList.toggle('hidden', mode !== 'tiles');
document.getElementById('spawnModePanel').classList.toggle('hidden', mode !== 'spawns');
document.getElementById('connectionModePanel').classList.toggle('hidden', mode !== 'connections');
renderRoomGrid();
}
// Tile palette
function selectSheet(sheetId) {
selectedSheetId = parseInt(sheetId);
renderTilePalette();
}
function renderTilePalette() {
const sheet = sheets.find(s => s.Id === selectedSheetId);
if (!sheet) return;
const palette = document.getElementById('tilePalette');
const imgUrl = `${cdnBaseUrl}/${sheet.CdnPath}`;
const displaySize = 32;
const scale = displaySize / sheet.TileWidth;
const scaledSheetW = sheet.SheetWidth * scale;
const scaledSheetH = sheet.SheetHeight * scale;
let html = `<div class="grid gap-1" style="grid-template-columns: repeat(auto-fill, minmax(${displaySize}px, 1fr));">`;
for (const tile of sheet.Tiles) {
if (currentFilter !== 'all' && tile.Type !== TileType[currentFilter]) continue;
const col = tile.FrameIndex % sheet.Columns;
const row = Math.floor(tile.FrameIndex / sheet.Columns);
const bgPosX = col * sheet.TileWidth * scale;
const bgPosY = row * sheet.TileHeight * scale;
const isSelected = selectedTile && selectedTile.id === tile.Id;
const borderClass = isSelected ? 'border-yellow-400 border-2' : 'border-gray-600 border';
html += `<div class="cursor-pointer ${borderClass} hover:border-yellow-300 transition-all"
onclick="selectTile(${tile.Id}, ${sheet.Id})"
title="${tile.Name || 'Tile ' + tile.FrameIndex} (${TileTypeName[tile.Type]})"
style="width: ${displaySize}px; height: ${displaySize}px; background-image: url('${imgUrl}'); background-position: -${bgPosX}px -${bgPosY}px; background-size: ${scaledSheetW}px ${scaledSheetH}px; image-rendering: pixelated;">
</div>`;
}
html += '</div>';
palette.innerHTML = html;
}
function selectTile(tileId, sheetId) {
const sheet = sheets.find(s => s.Id === sheetId);
const tile = sheet?.Tiles.find(t => t.Id === tileId);
if (tile) {
selectedTile = { id: tile.Id, sheetId: sheetId, frameIndex: tile.FrameIndex, name: tile.Name || `Tile ${tile.FrameIndex}` };
document.getElementById('selectedTileInfo').classList.remove('hidden');
document.getElementById('selectedTileName').textContent = selectedTile.name;
renderTilePalette();
}
}
function filterTiles(filter) {
currentFilter = filter;
document.querySelectorAll('.tile-filter').forEach(b => b.classList.remove('active', 'bg-blue-600'));
document.querySelector(`.tile-filter[data-filter="${filter}"]`)?.classList.add('active', 'bg-blue-600');
renderTilePalette();
}
function setTool(tool) {
currentTool = tool;
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active', 'bg-blue-600'));
document.querySelector(`.tool-btn[data-tool="${tool}"]`)?.classList.add('active', 'bg-blue-600');
}
function setSpawnType(type) {
selectedSpawnType = type;
document.querySelectorAll('.spawn-type-btn').forEach(b => b.classList.remove('active', 'bg-gray-700'));
document.querySelector(`.spawn-type-btn[data-spawn="${type}"]`)?.classList.add('active', 'bg-gray-700');
}
// Room grid rendering
function renderRoomGrid() {
const canvas = document.getElementById('roomCanvas');
const width = parseInt(document.getElementById('Room_Width').value) || roomWidth;
const height = parseInt(document.getElementById('Room_Height').value) || roomHeight;
roomWidth = width;
roomHeight = height;
document.getElementById('gridInfo').textContent = `${width} × ${height}`;
let html = `<div class="grid relative" style="grid-template-columns: repeat(${width}, ${TILE_DISPLAY_SIZE}px);">`;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const placement = roomTiles.find(t => t.X === x && t.Y === y);
let bgStyle = 'background-color: #1f2937;';
if (placement) {
for (const sheet of sheets) {
const tile = sheet.Tiles.find(t => t.Id === placement.TileDefinitionId);
if (tile) {
const col = tile.FrameIndex % sheet.Columns;
const row = Math.floor(tile.FrameIndex / sheet.Columns);
const scale = TILE_DISPLAY_SIZE / sheet.TileWidth;
bgStyle = `background-image: url('${cdnBaseUrl}/${sheet.CdnPath}'); background-position: -${col * sheet.TileWidth * scale}px -${row * sheet.TileHeight * scale}px; background-size: ${sheet.SheetWidth * scale}px ${sheet.SheetHeight * scale}px;`;
break;
}
}
}
// Check for spawn point
const spawn = spawnPoints.find(s => s.X === x && s.Y === y);
let spawnOverlay = '';
if (spawn) {
const color = SpawnColors[spawn.Type] || '#888';
const letter = SpawnLetters[spawn.Type] || '?';
spawnOverlay = `<div class="absolute inset-0 flex items-center justify-center pointer-events-none">
<span class="w-5 h-5 rounded-full flex items-center justify-center text-white text-xs font-bold" style="background: ${color};">${letter}</span>
</div>`;
}
// Check for connection point
const conn = connectionPoints.find(c => c.X === x && c.Y === y);
let connOverlay = '';
if (conn) {
connOverlay = `<div class="absolute inset-0 border-2 border-cyan-400 pointer-events-none"></div>`;
}
// Edge detection for connection mode
const isEdge = (x === 0 || x === width - 1 || y === 0 || y === height - 1);
const edgeClass = currentMode === 'connections' && isEdge ? 'ring-1 ring-cyan-500/50' : '';
html += `<div class="relative border border-gray-700/50 hover:border-blue-400 cursor-crosshair ${edgeClass}"
style="width: ${TILE_DISPLAY_SIZE}px; height: ${TILE_DISPLAY_SIZE}px; ${bgStyle} image-rendering: pixelated;"
data-x="${x}" data-y="${y}"
onmousedown="handleGridClick(event, ${x}, ${y})"
onmouseenter="handleGridHover(event, ${x}, ${y})"
oncontextmenu="event.preventDefault(); handleRightClick(${x}, ${y});">
${spawnOverlay}${connOverlay}
</div>`;
}
}
html += '</div>';
canvas.innerHTML = html;
}
// Grid interactions
function handleGridClick(event, x, y) {
event.preventDefault();
isMouseDown = true;
if (currentMode === 'tiles') {
if (event.button === 2 || currentTool === 'erase') {
eraseTile(x, y);
} else if (currentTool === 'fill') {
floodFill(x, y);
} else if (selectedTile) {
placeTile(x, y);
}
} else if (currentMode === 'spawns') {
toggleSpawn(x, y);
} else if (currentMode === 'connections') {
toggleConnection(x, y);
}
}
function handleGridHover(event, x, y) {
if (!isMouseDown || currentMode !== 'tiles') return;
if (currentTool === 'erase') {
eraseTile(x, y);
} else if (currentTool === 'paint' && selectedTile) {
placeTile(x, y);
}
}
function handleRightClick(x, y) {
if (currentMode === 'tiles') {
eraseTile(x, y);
} else if (currentMode === 'spawns') {
removeSpawn(x, y);
} else if (currentMode === 'connections') {
removeConnection(x, y);
}
}
document.addEventListener('mouseup', () => { isMouseDown = false; });
// Tile operations
function placeTile(x, y) {
if (!selectedTile) return;
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
roomTiles.push({ X: x, Y: y, TileDefinitionId: selectedTile.id, Layer: 0, Rotation: 0, FlipX: false, FlipY: false });
updateAllData();
renderRoomGrid();
}
function eraseTile(x, y) {
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
updateAllData();
renderRoomGrid();
}
function floodFill(startX, startY) {
if (!selectedTile) return;
const existingTile = roomTiles.find(t => t.X === startX && t.Y === startY);
const targetTileId = existingTile?.TileDefinitionId ?? null;
if (targetTileId === selectedTile.id) return;
const stack = [[startX, startY]];
const visited = new Set();
while (stack.length > 0) {
const [x, y] = stack.pop();
const key = `${x},${y}`;
if (visited.has(key) || x < 0 || x >= roomWidth || y < 0 || y >= roomHeight) continue;
visited.add(key);
const tile = roomTiles.find(t => t.X === x && t.Y === y);
if ((tile?.TileDefinitionId ?? null) !== targetTileId) continue;
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
roomTiles.push({ X: x, Y: y, TileDefinitionId: selectedTile.id, Layer: 0, Rotation: 0, FlipX: false, FlipY: false });
stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
}
updateAllData();
renderRoomGrid();
}
function clearAllTiles() {
if (!confirm('Clear all tiles?')) return;
roomTiles = [];
updateAllData();
renderRoomGrid();
}
// Spawn operations
function toggleSpawn(x, y) {
const existing = spawnPoints.findIndex(s => s.X === x && s.Y === y);
if (existing >= 0) {
spawnPoints.splice(existing, 1);
} else {
spawnPoints.push({ X: x, Y: y, Type: selectedSpawnType, EntityId: null, Tags: null });
}
updateAllData();
updateCounters();
renderRoomGrid();
}
function removeSpawn(x, y) {
spawnPoints = spawnPoints.filter(s => !(s.X === x && s.Y === y));
updateAllData();
updateCounters();
renderRoomGrid();
}
function clearAllSpawns() {
if (!confirm('Clear all spawn points?')) return;
spawnPoints = [];
updateAllData();
updateCounters();
renderRoomGrid();
}
// Connection operations
function toggleConnection(x, y) {
// Only allow on edges
const isNorth = y === 0;
const isSouth = y === roomHeight - 1;
const isWest = x === 0;
const isEast = x === roomWidth - 1;
if (!isNorth && !isSouth && !isWest && !isEast) return;
const existing = connectionPoints.findIndex(c => c.X === x && c.Y === y);
if (existing >= 0) {
connectionPoints.splice(existing, 1);
} else {
let direction = 'north';
if (isNorth) direction = 'north';
else if (isSouth) direction = 'south';
else if (isEast) direction = 'east';
else if (isWest) direction = 'west';
const width = parseInt(document.getElementById('connectionWidth').value) || 2;
connectionPoints.push({ X: x, Y: y, Direction: direction, Width: width });
}
updateAllData();
updateCounters();
renderRoomGrid();
}
function removeConnection(x, y) {
connectionPoints = connectionPoints.filter(c => !(c.X === x && c.Y === y));
updateAllData();
updateCounters();
renderRoomGrid();
}
function clearAllConnections() {
if (!confirm('Clear all connection points?')) return;
connectionPoints = [];
updateAllData();
updateCounters();
renderRoomGrid();
}
// Utilities
function resizeGrid() {
const newWidth = parseInt(document.getElementById('Room_Width').value) || 10;
const newHeight = parseInt(document.getElementById('Room_Height').value) || 10;
roomTiles = roomTiles.filter(t => t.X < newWidth && t.Y < newHeight);
spawnPoints = spawnPoints.filter(s => s.X < newWidth && s.Y < newHeight);
connectionPoints = connectionPoints.filter(c => c.X < newWidth && c.Y < newHeight);
roomWidth = newWidth;
roomHeight = newHeight;
updateAllData();
updateCounters();
renderRoomGrid();
}
function updateAllData() {
document.getElementById('tileDataJson').value = JSON.stringify(roomTiles);
document.getElementById('spawnPointsJson').value = JSON.stringify(spawnPoints);
document.getElementById('connectionPointsJson').value = JSON.stringify(connectionPoints);
}
function updateCounters() {
document.getElementById('spawnCount').textContent = spawnPoints.length;
document.getElementById('connNorth').textContent = connectionPoints.filter(c => c.Direction === 'north').length;
document.getElementById('connSouth').textContent = connectionPoints.filter(c => c.Direction === 'south').length;
document.getElementById('connEast').textContent = connectionPoints.filter(c => c.Direction === 'east').length;
document.getElementById('connWest').textContent = connectionPoints.filter(c => c.Direction === 'west').length;
}
// Save on form submit
document.getElementById('roomForm').addEventListener('submit', () => {
updateAllData();
});
</script>
<style>
.tool-btn.active, .tile-filter.active, .mode-btn.active { background-color: #2563eb !important; }
.spawn-type-btn { background-color: #374151; }
.spawn-type-btn:hover { background-color: #4b5563; }
.spawn-type-btn.active { background-color: #4b5563; border: 1px solid #6b7280; }
</style>
}
@@ -1,138 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
using System.Text.Json;
namespace Server.Services.Admin.Pages.RoomTemplates;
public class EditModel : AdminPageModel
{
private readonly GameDbContext _db;
private readonly IConfiguration _config;
public EditModel(GameDbContext db, IConfiguration config)
{
_db = db;
_config = config;
}
[BindProperty]
public RoomTemplate Room { get; set; } = new();
public List<TileMapSheet> TileMapSheets { get; set; } = new();
public List<TileDefinition> AllTiles { get; set; } = new();
public string CdnBaseUrl { get; set; } = "";
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync(int? id)
{
CdnBaseUrl = _config["Cdn:BaseUrl"]?.TrimEnd('/') ?? "https://assets.aeternalisgames.com";
if (!CdnBaseUrl.EndsWith("/downloads")) CdnBaseUrl += "/downloads";
TileMapSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.Include(s => s.Tiles!.Where(t => t.IsEnabled))
.OrderBy(s => s.Name)
.ToListAsync();
AllTiles = TileMapSheets.SelectMany(s => s.Tiles ?? new List<TileDefinition>()).ToList();
if (id.HasValue)
{
var room = await _db.RoomTemplates.FindAsync(id.Value);
if (room != null)
{
Room = room;
}
}
else
{
Room = new RoomTemplate
{
Width = 10,
Height = 10,
MinTier = 1,
Weight = 100,
IsEnabled = true
};
}
}
public async Task<IActionResult> OnPostAsync()
{
CdnBaseUrl = _config["Cdn:BaseUrl"]?.TrimEnd('/') ?? "https://assets.aeternalisgames.com";
if (!CdnBaseUrl.EndsWith("/downloads")) CdnBaseUrl += "/downloads";
try
{
if (Room.Id == 0)
{
Room.CreatedAt = DateTime.UtcNow;
Room.UpdatedAt = DateTime.UtcNow;
_db.RoomTemplates.Add(Room);
await _db.SaveChangesAsync();
Message = $"Room template '{Room.Name}' created.";
return RedirectToPage(new { id = Room.Id });
}
else
{
var existing = await _db.RoomTemplates.FindAsync(Room.Id);
if (existing == null)
{
Message = "Room template not found.";
IsError = true;
return Page();
}
existing.Name = Room.Name;
existing.Description = Room.Description;
existing.Tags = Room.Tags;
existing.Type = Room.Type;
existing.Width = Room.Width;
existing.Height = Room.Height;
existing.MinTier = Room.MinTier;
existing.MaxTier = Room.MaxTier;
existing.Weight = Room.Weight;
existing.TileDataJson = Room.TileDataJson;
existing.SpawnPointsJson = Room.SpawnPointsJson;
existing.ConnectionPointsJson = Room.ConnectionPointsJson;
existing.IsEnabled = Room.IsEnabled;
existing.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
Room = existing;
Message = "Room template updated.";
}
}
catch (Exception ex)
{
Message = $"Error: {ex.Message}";
IsError = true;
}
TileMapSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.Include(s => s.Tiles!.Where(t => t.IsEnabled))
.OrderBy(s => s.Name)
.ToListAsync();
AllTiles = TileMapSheets.SelectMany(s => s.Tiles ?? new List<TileDefinition>()).ToList();
return Page();
}
public async Task<IActionResult> OnPostSaveTilesAsync(int roomId, string tileData)
{
var room = await _db.RoomTemplates.FindAsync(roomId);
if (room != null)
{
room.TileDataJson = tileData;
room.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new { success = true });
}
return new JsonResult(new { success = false, error = "Room not found" });
}
}
@@ -1,134 +0,0 @@
@page "/admin/roomtemplates"
@model RoomTemplates.IndexModel
@using DataServer.Data.Entities
@{
ViewData["Title"] = "Room Templates";
}
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4 md:mb-6">
<div>
<h1 class="text-xl md:text-2xl font-bold text-white">Room Templates</h1>
<p class="text-gray-400 text-sm">Create and manage room layouts for dungeon generation</p>
</div>
<a href="/admin/roomtemplates/edit" class="btn btn-primary text-sm">+ New Room</a>
</div>
<!-- Room Type Filters -->
<div class="flex flex-wrap gap-2 mb-4">
<span class="text-gray-400 text-sm py-1">Filter:</span>
@foreach (var type in Enum.GetValues<RoomType>().Take(10))
{
var count = Model.Rooms.Count(r => r.Type == type);
if (count > 0)
{
<span class="px-2 py-1 text-xs rounded bg-gray-700 text-gray-300">@type (@count)</span>
}
}
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-4">
@foreach (var room in Model.Rooms)
{
<div class="card p-4">
<div class="flex justify-between items-start mb-3">
<div class="min-w-0 flex-1">
<h3 class="text-base md:text-lg font-semibold text-white truncate">@room.Name</h3>
<p class="text-xs text-gray-400">@room.Width×@room.Height tiles</p>
</div>
<div class="flex flex-col items-end gap-1 ml-2">
<span class="px-2 py-0.5 text-xs rounded @GetRoomTypeColor(room.Type)">@room.Type</span>
<span class="px-2 py-0.5 text-xs rounded @(room.IsEnabled ? "bg-green-900 text-green-300" : "bg-red-900 text-red-300")">
@(room.IsEnabled ? "On" : "Off")
</span>
</div>
</div>
@if (!string.IsNullOrEmpty(room.Description))
{
<p class="text-sm text-gray-400 mb-3 line-clamp-2">@room.Description</p>
}
<div class="grid grid-cols-2 gap-1 text-xs mb-3">
<div>
<span class="text-gray-500">Tier:</span>
<span class="text-gray-300">@room.MinTier - @(room.MaxTier == 0 ? "∞" : room.MaxTier.ToString())</span>
</div>
<div>
<span class="text-gray-500">Weight:</span>
<span class="text-gray-300">@room.Weight</span>
</div>
</div>
@if (!string.IsNullOrEmpty(room.Tags))
{
<div class="flex flex-wrap gap-1 mb-3">
@foreach (var tag in room.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries).Take(4))
{
<span class="px-1.5 py-0.5 bg-blue-900/50 text-blue-300 text-xs rounded">@tag.Trim()</span>
}
</div>
}
<!-- Mini Preview -->
<div class="bg-gray-900 rounded p-2 mb-3 h-20 flex items-center justify-center">
@if (!string.IsNullOrEmpty(room.TileDataJson))
{
<span class="text-xs text-gray-500">@(CountTiles(room.TileDataJson)) tiles placed</span>
}
else
{
<span class="text-xs text-gray-500">No tiles placed</span>
}
</div>
<div class="flex gap-2">
<a href="/admin/roomtemplates/edit?id=@room.Id" class="btn btn-secondary flex-1 text-center text-sm py-1.5">Edit</a>
<form method="post" asp-page-handler="Duplicate" class="flex-shrink-0">
<input type="hidden" name="id" value="@room.Id" />
<button type="submit" class="btn btn-secondary text-sm py-1.5 px-2" title="Duplicate">📋</button>
</form>
<form method="post" asp-page-handler="Delete" class="flex-shrink-0">
<input type="hidden" name="id" value="@room.Id" />
<button type="submit" class="btn bg-red-600 hover:bg-red-700 text-sm py-1.5 px-2"
onclick="return confirm('Delete this room template?')" title="Delete">🗑️</button>
</form>
</div>
</div>
}
</div>
@if (Model.Rooms.Count == 0)
{
<div class="card p-8 md:p-12 text-center">
<p class="text-gray-400 mb-4">No room templates yet. Create rooms to use in dungeon generation.</p>
<a href="/admin/roomtemplates/edit" class="btn btn-primary">Create Your First Room</a>
</div>
}
@functions {
string GetRoomTypeColor(RoomType type)
{
return type switch
{
RoomType.Entrance => "bg-green-900 text-green-300",
RoomType.Exit => "bg-blue-900 text-blue-300",
RoomType.Boss => "bg-red-900 text-red-300",
RoomType.Treasure => "bg-yellow-900 text-yellow-300",
RoomType.Secret => "bg-purple-900 text-purple-300",
RoomType.Shop => "bg-cyan-900 text-cyan-300",
RoomType.Hallway => "bg-gray-700 text-gray-300",
_ => "bg-gray-600 text-gray-300"
};
}
int CountTiles(string? json)
{
if (string.IsNullOrEmpty(json)) return 0;
try
{
var tiles = System.Text.Json.JsonSerializer.Deserialize<List<TilePlacement>>(json);
return tiles?.Count ?? 0;
}
catch { return 0; }
}
}
@@ -1,64 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
namespace Server.Services.Admin.Pages.RoomTemplates;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<RoomTemplate> Rooms { get; set; } = new();
public async Task OnGetAsync()
{
Rooms = await _db.RoomTemplates
.OrderBy(r => r.Type)
.ThenBy(r => r.Name)
.ToListAsync();
}
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var room = await _db.RoomTemplates.FindAsync(id);
if (room != null)
{
_db.RoomTemplates.Remove(room);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
public async Task<IActionResult> OnPostDuplicateAsync(int id)
{
var room = await _db.RoomTemplates.FindAsync(id);
if (room != null)
{
var copy = new RoomTemplate
{
Name = room.Name + " (Copy)",
Description = room.Description,
Tags = room.Tags,
Type = room.Type,
Width = room.Width,
Height = room.Height,
MinTier = room.MinTier,
MaxTier = room.MaxTier,
Weight = room.Weight,
TileDataJson = room.TileDataJson,
SpawnPointsJson = room.SpawnPointsJson,
ConnectionPointsJson = room.ConnectionPointsJson,
IsEnabled = false
};
_db.RoomTemplates.Add(copy);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
}
+9 -409
View File
@@ -3,8 +3,6 @@
@using DataServer.Data.Entities
@{
ViewData["Title"] = Model.Sheet.Id == 0 ? "New TileMap Sheet" : $"Edit: {Model.Sheet.Name}";
var tileTypes = Enum.GetValues<TileType>();
var socketTypes = Enum.GetValues<SocketType>();
// Build image URL - handle both with and without /downloads/ path
var imageUrl = Model.Sheet.CdnPath;
if (!string.IsNullOrEmpty(imageUrl))
@@ -126,282 +124,23 @@
</div>
</div>
<!-- Note about Tile Templates -->
@if (Model.Sheet.Id > 0)
{
<!-- Tile Editor Section -->
<div class="card p-4 md:p-6 mt-4 md:mt-6">
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4">
<h2 class="text-lg md:text-xl font-semibold text-white">Tile Definitions</h2>
<div class="flex flex-wrap gap-2">
<form method="post" asp-page-handler="AutoGenerate" class="flex gap-2">
<input type="hidden" name="sheetId" value="@Model.Sheet.Id" />
<select name="defaultType" class="input text-sm py-1">
<option value="0">Floor (walkable)</option>
<option value="1">Wall (blocked)</option>
</select>
<button type="submit" class="btn btn-secondary text-sm py-1">Auto-Generate</button>
</form>
<!-- Socket bulk actions -->
<form method="post" asp-page-handler="AutoConfigureSockets" class="inline">
<input type="hidden" name="sheetId" value="@Model.Sheet.Id" />
<button type="submit" class="btn btn-secondary text-sm py-1" title="Set sockets based on tile type">Auto Sockets</button>
</form>
<div class="flex items-center gap-3">
<div class="text-2xl">💡</div>
<div>
<h3 class="font-semibold text-white">Create Tile Templates</h3>
<p class="text-gray-400 text-sm mt-1">
To use tiles from this sheet, create <a href="/admin/dungeonbuilder/tiles" class="text-blue-400 hover:underline">Tile Templates</a>
which define walkability, sockets, and other properties.
</p>
</div>
</div>
<p class="text-gray-400 text-sm mb-4">Click on a tile to define its properties. Defined: @Model.TileDefinitions.Count / @Model.Sheet.TotalTiles</p>
<!-- Interactive Tile Grid -->
<div class="bg-gray-900 rounded-lg p-2 md:p-4 overflow-auto" style="max-height: 60vh;">
<div class="relative inline-block" id="tileGridContainer" style="image-rendering: pixelated;">
@if (!string.IsNullOrEmpty(Model.Sheet.CdnPath))
{
<img src="@imageUrl"
alt="@Model.Sheet.Name"
id="tileGridImage"
class="max-w-none"
onerror="this.style.display='none';" />
<!-- Clickable tile overlay -->
<div id="tileClickOverlay" class="absolute top-0 left-0"
style="width: @(Model.Sheet.SheetWidth)px; height: @(Model.Sheet.SheetHeight)px;">
@for (int row = 0; row < Model.Sheet.Rows; row++)
{
@for (int col = 0; col < Model.Sheet.Columns; col++)
{
var frameIndex = row * Model.Sheet.Columns + col;
var tileDef = Model.TileDefinitions.FirstOrDefault(t => t.FrameIndex == frameIndex);
var hasDefinition = tileDef != null;
var tileColor = hasDefinition ? GetTileTypeColor(tileDef!.Type) : "transparent";
<div class="absolute cursor-pointer border border-gray-600/30 hover:border-yellow-400 hover:bg-yellow-400/30 transition-all"
style="left: @(col * Model.Sheet.TileWidth)px; top: @(row * Model.Sheet.TileHeight)px; width: @(Model.Sheet.TileWidth)px; height: @(Model.Sheet.TileHeight)px; background-color: @tileColor;"
onclick="openTileEditor(@frameIndex, @(tileDef?.Id ?? 0))"
title="Frame @frameIndex @(hasDefinition ? $"({tileDef!.Type})" : "")">
</div>
}
}
</div>
}
</div>
</div>
<!-- Tile Type Legend -->
<div class="mt-3 flex flex-wrap gap-1 md:gap-2 text-xs">
<span class="text-gray-400">Legend:</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(34, 197, 94, 0.3);">Floor</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(239, 68, 68, 0.3);">Wall</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(168, 85, 247, 0.3);">Door</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(59, 130, 246, 0.3);">Water</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(249, 115, 22, 0.3);">Lava</span>
<span class="px-1.5 py-0.5 rounded" style="background-color: rgba(234, 179, 8, 0.3);">Spawn</span>
</div>
<!-- Defined Tiles Table -->
@if (Model.TileDefinitions.Count > 0)
{
<div class="mt-6">
<h3 class="text-base md:text-lg font-semibold text-white mb-3">Defined Tiles (@Model.TileDefinitions.Count)</h3>
<div class="overflow-x-auto -mx-4 md:mx-0">
<table class="w-full text-xs md:text-sm min-w-[700px]">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-700">
<th class="p-2">#</th>
<th class="p-2">Preview</th>
<th class="p-2">Name</th>
<th class="p-2">Type</th>
<th class="p-2">Sockets</th>
<th class="p-2">Props</th>
<th class="p-2">Actions</th>
</tr>
</thead>
<tbody>
@foreach (var tile in Model.TileDefinitions.Take(50))
{
var col = tile.FrameIndex % Model.Sheet.Columns;
var row = tile.FrameIndex / Model.Sheet.Columns;
<tr class="border-b border-gray-800 hover:bg-gray-800/50">
<td class="p-2 text-gray-300">@tile.FrameIndex</td>
<td class="p-2">
<div class="w-6 h-6 md:w-8 md:h-8 bg-gray-900 overflow-hidden" style="image-rendering: pixelated;">
<div style="width: @(Model.Sheet.TileWidth)px; height: @(Model.Sheet.TileHeight)px; background-image: url('@imageUrl'); background-position: -@(col * Model.Sheet.TileWidth)px -@(row * Model.Sheet.TileHeight)px; transform: scale(@(24.0 / Model.Sheet.TileWidth)); transform-origin: top left;"></div>
</div>
</td>
<td class="p-2 text-gray-300 max-w-[100px] truncate">@(tile.Name ?? "-")</td>
<td class="p-2">
<span class="px-1.5 py-0.5 text-xs rounded" style="background-color: @GetTileTypeColor(tile.Type);">@tile.Type</span>
</td>
<td class="p-2 text-xs">
<span class="@GetSocketBadgeClass(tile.SocketN)" title="North">N</span>
<span class="@GetSocketBadgeClass(tile.SocketE)" title="East">E</span>
<span class="@GetSocketBadgeClass(tile.SocketS)" title="South">S</span>
<span class="@GetSocketBadgeClass(tile.SocketW)" title="West">W</span>
</td>
<td class="p-2 text-xs">
@if (tile.IsWalkable) { <span class="text-green-400" title="Walkable">W</span> }
@if (tile.BlocksProjectiles) { <span class="text-red-400" title="Blocks Projectiles">P</span> }
@if (tile.BlocksLineOfSight) { <span class="text-yellow-400" title="Blocks LOS">L</span> }
</td>
<td class="p-2">
<button onclick="openTileEditor(@tile.FrameIndex, @tile.Id)" class="text-blue-400 hover:text-blue-300 mr-1">Edit</button>
<form method="post" asp-page-handler="DeleteTile" class="inline">
<input type="hidden" name="tileId" value="@tile.Id" />
<input type="hidden" name="sheetId" value="@Model.Sheet.Id" />
<button type="submit" class="text-red-400 hover:text-red-300" onclick="return confirm('Delete?')">×</button>
</form>
</td>
</tr>
}
</tbody>
</table>
@if (Model.TileDefinitions.Count > 50)
{
<p class="text-gray-500 text-xs p-2">Showing first 50 of @Model.TileDefinitions.Count tiles</p>
}
</div>
</div>
}
</div>
}
<!-- Tile Editor Modal -->
<div id="tileEditorModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
<div class="bg-gray-900 rounded-xl shadow-xl p-4 md:p-6 w-full max-w-lg border border-gray-700 max-h-[90vh] overflow-y-auto">
<h3 class="text-lg font-semibold text-white mb-4">Edit Tile <span id="modalFrameIndex"></span></h3>
<form method="post" asp-page-handler="SaveTile">
@Html.AntiForgeryToken()
<input type="hidden" name="sheetId" value="@Model.Sheet.Id" />
<input type="hidden" name="frameIndex" id="editFrameIndex" />
<div class="space-y-3 md:space-y-4">
<!-- Tile Preview -->
<div class="flex justify-center">
<div id="modalTilePreview" class="bg-gray-800 border border-gray-600" style="image-rendering: pixelated; width: 64px; height: 64px;"></div>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Name (optional)</label>
<input type="text" name="name" id="editName" class="input w-full text-sm" placeholder="Stone Floor A" />
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Type</label>
<select name="type" id="editType" class="input w-full text-sm" onchange="onTypeChange()">
@foreach (var t in tileTypes)
{
<option value="@((int)t)">@t</option>
}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Render Layer</label>
<select name="renderLayer" id="editRenderLayer" class="input w-full text-sm">
<option value="0">0 - Ground</option>
<option value="1">1 - Floor Decor</option>
<option value="2">2 - Walls</option>
<option value="3">3 - Ceiling</option>
</select>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Tags</label>
<input type="text" name="tags" id="editTags" class="input w-full text-sm" placeholder="stone, cracked" />
</div>
<!-- Socket Configuration -->
<div class="border border-gray-700 rounded-lg p-3">
<div class="flex items-center justify-between mb-2">
<label class="text-sm font-medium text-gray-300">Sockets</label>
<div class="flex gap-1">
<button type="button" onclick="setAllSockets(1)" class="text-xs px-2 py-0.5 bg-green-900/50 text-green-400 rounded hover:bg-green-900">All Open</button>
<button type="button" onclick="setAllSockets(0)" class="text-xs px-2 py-0.5 bg-red-900/50 text-red-400 rounded hover:bg-red-900">All Closed</button>
</div>
</div>
<div class="grid grid-cols-3 gap-2 text-center">
<!-- North -->
<div></div>
<div>
<label class="text-xs text-gray-400 block">North</label>
<select name="socketN" id="editSocketN" class="input w-full text-xs py-1" onchange="updateSocketCustom('N')">
<option value="0">Closed</option>
<option value="1">Open</option>
<option value="2">Custom</option>
</select>
<input type="text" name="socketNCustom" id="editSocketNCustom" class="input w-full text-xs py-1 mt-1 hidden" placeholder="Custom type" />
</div>
<div></div>
<!-- West / Center / East -->
<div>
<label class="text-xs text-gray-400 block">West</label>
<select name="socketW" id="editSocketW" class="input w-full text-xs py-1" onchange="updateSocketCustom('W')">
<option value="0">Closed</option>
<option value="1">Open</option>
<option value="2">Custom</option>
</select>
<input type="text" name="socketWCustom" id="editSocketWCustom" class="input w-full text-xs py-1 mt-1 hidden" placeholder="Custom type" />
</div>
<div class="flex items-center justify-center">
<div class="w-8 h-8 bg-gray-700 rounded flex items-center justify-center text-gray-500">
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><rect x="2" y="2" width="16" height="16" rx="2"/></svg>
</div>
</div>
<div>
<label class="text-xs text-gray-400 block">East</label>
<select name="socketE" id="editSocketE" class="input w-full text-xs py-1" onchange="updateSocketCustom('E')">
<option value="0">Closed</option>
<option value="1">Open</option>
<option value="2">Custom</option>
</select>
<input type="text" name="socketECustom" id="editSocketECustom" class="input w-full text-xs py-1 mt-1 hidden" placeholder="Custom type" />
</div>
<!-- South -->
<div></div>
<div>
<label class="text-xs text-gray-400 block">South</label>
<select name="socketS" id="editSocketS" class="input w-full text-xs py-1" onchange="updateSocketCustom('S')">
<option value="0">Closed</option>
<option value="1">Open</option>
<option value="2">Custom</option>
</select>
<input type="text" name="socketSCustom" id="editSocketSCustom" class="input w-full text-xs py-1 mt-1 hidden" placeholder="Custom type" />
</div>
<div></div>
</div>
<p class="text-xs text-gray-500 mt-2">Open↔Open, Closed↔Closed. Custom must match exactly.</p>
</div>
<div class="grid grid-cols-3 gap-2 text-sm">
<label class="flex items-center gap-1.5 text-gray-300">
<input type="checkbox" name="isWalkable" id="editWalkable" value="true" class="rounded" />
Walk
</label>
<label class="flex items-center gap-1.5 text-gray-300">
<input type="checkbox" name="blocksProjectiles" id="editBlocksProj" value="true" class="rounded" />
Block Proj
</label>
<label class="flex items-center gap-1.5 text-gray-300">
<input type="checkbox" name="blocksLineOfSight" id="editBlocksLOS" value="true" class="rounded" />
Block LOS
</label>
</div>
</div>
<div class="flex gap-2 mt-5">
<button type="submit" class="btn btn-primary flex-1 text-sm">Save</button>
<button type="button" onclick="closeTileEditor()" class="btn btn-secondary flex-1 text-sm">Cancel</button>
</div>
</form>
</div>
</div>
<!-- CDN Browser Modal -->
<div id="cdnBrowserModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
<div class="bg-gray-900 rounded-xl shadow-xl p-4 md:p-6 w-full max-w-2xl border border-gray-700 max-h-[90vh] overflow-hidden flex flex-col">
@@ -431,110 +170,10 @@
@section Scripts {
<script>
const tileDefinitions = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.TileDefinitions.ToDictionary(t => t.FrameIndex, t => new {
t.Id, t.FrameIndex, t.Name, t.Type, t.Tags, t.IsWalkable, t.BlocksProjectiles, t.BlocksLineOfSight, t.RenderLayer,
SocketN = (int)t.SocketN, SocketE = (int)t.SocketE, SocketS = (int)t.SocketS, SocketW = (int)t.SocketW,
t.SocketNCustom, t.SocketECustom, t.SocketSCustom, t.SocketWCustom
})));
const sheetWidth = @Model.Sheet.SheetWidth;
const sheetHeight = @Model.Sheet.SheetHeight;
const tileWidth = @Model.Sheet.TileWidth;
const tileHeight = @Model.Sheet.TileHeight;
const columns = @Model.Sheet.Columns;
const imageUrl = '@imageUrl';
function openTileEditor(frameIndex, existingId) {
document.getElementById('editFrameIndex').value = frameIndex;
document.getElementById('modalFrameIndex').textContent = '#' + frameIndex;
const col = frameIndex % columns;
const row = Math.floor(frameIndex / columns);
// Set preview with proper scaling
const preview = document.getElementById('modalTilePreview');
const scale = 64 / Math.max(tileWidth, tileHeight);
preview.style.width = '64px';
preview.style.height = '64px';
preview.style.backgroundImage = `url('${imageUrl}')`;
preview.style.backgroundPosition = `-${col * tileWidth * scale}px -${row * tileHeight * scale}px`;
preview.style.backgroundSize = `${sheetWidth * scale}px ${sheetHeight * scale}px`;
// Load existing data
const existing = tileDefinitions[frameIndex];
if (existing) {
document.getElementById('editName').value = existing.Name || '';
document.getElementById('editType').value = existing.Type;
document.getElementById('editTags').value = existing.Tags || '';
document.getElementById('editRenderLayer').value = existing.RenderLayer;
document.getElementById('editWalkable').checked = existing.IsWalkable;
document.getElementById('editBlocksProj').checked = existing.BlocksProjectiles;
document.getElementById('editBlocksLOS').checked = existing.BlocksLineOfSight;
// Sockets
document.getElementById('editSocketN').value = existing.SocketN;
document.getElementById('editSocketE').value = existing.SocketE;
document.getElementById('editSocketS').value = existing.SocketS;
document.getElementById('editSocketW').value = existing.SocketW;
document.getElementById('editSocketNCustom').value = existing.SocketNCustom || '';
document.getElementById('editSocketECustom').value = existing.SocketECustom || '';
document.getElementById('editSocketSCustom').value = existing.SocketSCustom || '';
document.getElementById('editSocketWCustom').value = existing.SocketWCustom || '';
} else {
document.getElementById('editName').value = '';
document.getElementById('editType').value = '0';
document.getElementById('editTags').value = '';
document.getElementById('editRenderLayer').value = '0';
document.getElementById('editWalkable').checked = true;
document.getElementById('editBlocksProj').checked = false;
document.getElementById('editBlocksLOS').checked = false;
// Default sockets for new tile
document.getElementById('editSocketN').value = '1'; // Open
document.getElementById('editSocketE').value = '1';
document.getElementById('editSocketS').value = '1';
document.getElementById('editSocketW').value = '1';
document.getElementById('editSocketNCustom').value = '';
document.getElementById('editSocketECustom').value = '';
document.getElementById('editSocketSCustom').value = '';
document.getElementById('editSocketWCustom').value = '';
}
// Update custom field visibility
['N', 'E', 'S', 'W'].forEach(updateSocketCustom);
document.getElementById('tileEditorModal').classList.remove('hidden');
document.getElementById('tileEditorModal').classList.add('flex');
}
function closeTileEditor() {
document.getElementById('tileEditorModal').classList.add('hidden');
document.getElementById('tileEditorModal').classList.remove('flex');
}
function updateSocketCustom(dir) {
const select = document.getElementById('editSocket' + dir);
const custom = document.getElementById('editSocket' + dir + 'Custom');
custom.classList.toggle('hidden', select.value !== '2');
}
function setAllSockets(value) {
['N', 'E', 'S', 'W'].forEach(dir => {
document.getElementById('editSocket' + dir).value = value;
updateSocketCustom(dir);
});
}
function onTypeChange() {
const type = parseInt(document.getElementById('editType').value);
// Auto-set sockets based on type
if (type === 0 || type === 30) { // Floor, FloorDecor
setAllSockets(1); // Open
document.getElementById('editWalkable').checked = true;
} else if (type === 1 || type === 31) { // Wall, WallDecor
setAllSockets(0); // Closed
document.getElementById('editWalkable').checked = false;
document.getElementById('editBlocksProj').checked = true;
document.getElementById('editBlocksLOS').checked = true;
}
}
function showCdnBrowser() {
document.getElementById('cdnBrowserModal').classList.remove('hidden');
@@ -588,47 +227,8 @@
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
closeTileEditor();
closeCdnBrowser();
}
});
</script>
}
@functions {
string GetTileTypeColor(TileType type)
{
return type switch
{
TileType.Floor => "rgba(34, 197, 94, 0.3)",
TileType.Wall => "rgba(239, 68, 68, 0.3)",
TileType.Door => "rgba(168, 85, 247, 0.3)",
TileType.Water => "rgba(59, 130, 246, 0.3)",
TileType.Lava => "rgba(249, 115, 22, 0.3)",
TileType.Pit => "rgba(31, 41, 55, 0.5)",
TileType.Stairs => "rgba(236, 72, 153, 0.3)",
TileType.PlayerSpawn => "rgba(234, 179, 8, 0.4)",
TileType.MobSpawn => "rgba(234, 179, 8, 0.3)",
TileType.BossSpawn => "rgba(220, 38, 38, 0.4)",
TileType.ChestSpawn => "rgba(251, 191, 36, 0.4)",
TileType.Trigger => "rgba(139, 92, 246, 0.3)",
TileType.Transition => "rgba(14, 165, 233, 0.3)",
TileType.Secret => "rgba(163, 163, 163, 0.3)",
TileType.Trap => "rgba(239, 68, 68, 0.4)",
TileType.FloorDecor => "rgba(34, 197, 94, 0.2)",
TileType.WallDecor => "rgba(239, 68, 68, 0.2)",
_ => "transparent"
};
}
string GetSocketBadgeClass(SocketType socket)
{
return socket switch
{
SocketType.Open => "text-green-400",
SocketType.Closed => "text-red-400",
SocketType.Custom => "text-yellow-400",
_ => "text-gray-400"
};
}
}