ItemDB+API

This commit is contained in:
dingo
2025-12-04 09:30:32 -05:00
parent 841b241ef2
commit d66ff2af40
10 changed files with 2183 additions and 1 deletions
+300
View File
@@ -0,0 +1,300 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
using VoidScavengers.Game;
namespace VoidScavengers.Api;
/// <summary>
/// API endpoints for game items and recipes
/// </summary>
[ApiController]
[Route("api/items")]
public class ItemsController : ControllerBase
{
private readonly GameDbContext _db;
private readonly IItemService _itemService;
public ItemsController(GameDbContext db, IItemService itemService)
{
_db = db;
_itemService = itemService;
}
/// <summary>
/// Get all items (from cache)
/// </summary>
[HttpGet]
public IActionResult GetAllItems([FromQuery] ItemCategory? category = null)
{
var items = category.HasValue
? _itemService.GetItemsByCategory(category.Value)
: _itemService.GetAllItems();
return Ok(items);
}
/// <summary>
/// Get a specific item
/// </summary>
[HttpGet("{id}")]
public IActionResult GetItem(int id)
{
var item = _itemService.GetItem(id);
if (item == null)
return NotFound(new { error = "Item not found" });
return Ok(item);
}
/// <summary>
/// Get all recipes (from cache)
/// </summary>
[HttpGet("recipes")]
public IActionResult GetAllRecipes()
{
var recipes = _itemService.GetAllRecipes();
// Enrich with item names
var enriched = recipes.Select(r => new
{
r.Id,
r.ResultItemId,
ResultItemName = _itemService.GetItem(r.ResultItemId)?.Name ?? "Unknown",
r.ScrapCost,
r.EnergyCost,
r.RareCost
});
return Ok(enriched);
}
/// <summary>
/// Force reload the item cache (admin only)
/// </summary>
[HttpPost("reload")]
public async Task<IActionResult> ReloadCache([FromHeader(Name = "X-Admin-Key")] string? adminKey)
{
// Simple admin key check - in production use proper auth
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
await _itemService.ReloadCacheAsync();
return Ok(new { message = "Cache reloaded", itemCount = _itemService.GetAllItems().Count });
}
/// <summary>
/// Create or update an item (admin only)
/// </summary>
[HttpPost]
public async Task<IActionResult> UpsertItem(
[FromHeader(Name = "X-Admin-Key")] string? adminKey,
[FromBody] GameItemDto dto)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existing = await _db.GameItems.FindAsync(dto.Id);
if (existing == null)
{
var item = new GameItem
{
Id = dto.Id,
Name = dto.Name,
Category = dto.Category,
CraftCost = dto.CraftCost,
Description = dto.Description,
LootValue = dto.LootValue,
Stackable = dto.Stackable,
IsEnabled = dto.IsEnabled,
Damage = dto.Damage,
FireRate = dto.FireRate,
ProjectileSpeed = dto.ProjectileSpeed,
Range = dto.Range,
AmmoType = dto.AmmoType,
PelletCount = dto.PelletCount,
Spread = dto.Spread,
ExplosionRadius = dto.ExplosionRadius,
HarvestMultiplier = dto.HarvestMultiplier,
ScanRadius = dto.ScanRadius,
ScanCooldown = dto.ScanCooldown,
ShieldHealth = dto.ShieldHealth,
ShieldDuration = dto.ShieldDuration,
HealAmount = dto.HealAmount,
ShieldBoostDuration = dto.ShieldBoostDuration,
DamageReduction = dto.DamageReduction,
SpeedBoostDuration = dto.SpeedBoostDuration,
SpeedMultiplier = dto.SpeedMultiplier,
HealthBonus = dto.HealthBonus,
SpeedPenalty = dto.SpeedPenalty,
DashDistance = dto.DashDistance,
DashCooldown = dto.DashCooldown,
CreatedAt = DateTime.UtcNow
};
_db.GameItems.Add(item);
}
else
{
existing.Name = dto.Name;
existing.Category = dto.Category;
existing.CraftCost = dto.CraftCost;
existing.Description = dto.Description;
existing.LootValue = dto.LootValue;
existing.Stackable = dto.Stackable;
existing.IsEnabled = dto.IsEnabled;
existing.Damage = dto.Damage;
existing.FireRate = dto.FireRate;
existing.ProjectileSpeed = dto.ProjectileSpeed;
existing.Range = dto.Range;
existing.AmmoType = dto.AmmoType;
existing.PelletCount = dto.PelletCount;
existing.Spread = dto.Spread;
existing.ExplosionRadius = dto.ExplosionRadius;
existing.HarvestMultiplier = dto.HarvestMultiplier;
existing.ScanRadius = dto.ScanRadius;
existing.ScanCooldown = dto.ScanCooldown;
existing.ShieldHealth = dto.ShieldHealth;
existing.ShieldDuration = dto.ShieldDuration;
existing.HealAmount = dto.HealAmount;
existing.ShieldBoostDuration = dto.ShieldBoostDuration;
existing.DamageReduction = dto.DamageReduction;
existing.SpeedBoostDuration = dto.SpeedBoostDuration;
existing.SpeedMultiplier = dto.SpeedMultiplier;
existing.HealthBonus = dto.HealthBonus;
existing.SpeedPenalty = dto.SpeedPenalty;
existing.DashDistance = dto.DashDistance;
existing.DashCooldown = dto.DashCooldown;
}
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new { message = existing == null ? "Item created" : "Item updated", id = dto.Id });
}
/// <summary>
/// Create or update a recipe (admin only)
/// </summary>
[HttpPost("recipes")]
public async Task<IActionResult> UpsertRecipe(
[FromHeader(Name = "X-Admin-Key")] string? adminKey,
[FromBody] GameRecipeDto dto)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existing = await _db.GameRecipes.FindAsync(dto.Id);
if (existing == null)
{
var recipe = new GameRecipe
{
Id = dto.Id,
ResultItemId = dto.ResultItemId,
ScrapCost = dto.ScrapCost,
EnergyCost = dto.EnergyCost,
RareCost = dto.RareCost,
IsEnabled = dto.IsEnabled,
CreatedAt = DateTime.UtcNow
};
_db.GameRecipes.Add(recipe);
}
else
{
existing.ResultItemId = dto.ResultItemId;
existing.ScrapCost = dto.ScrapCost;
existing.EnergyCost = dto.EnergyCost;
existing.RareCost = dto.RareCost;
existing.IsEnabled = dto.IsEnabled;
}
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new { message = existing == null ? "Recipe created" : "Recipe updated", id = dto.Id });
}
/// <summary>
/// Seed default items if database is empty (admin only)
/// </summary>
[HttpPost("seed")]
public async Task<IActionResult> SeedDefaults([FromHeader(Name = "X-Admin-Key")] string? adminKey)
{
var expectedKey = Environment.GetEnvironmentVariable("ADMIN_KEY") ?? "dev-admin-key";
if (adminKey != expectedKey)
return Unauthorized(new { error = "Invalid admin key" });
var existingItemCount = await _db.GameItems.CountAsync();
var existingRecipeCount = await _db.GameRecipes.CountAsync();
if (existingItemCount > 0 || existingRecipeCount > 0)
return BadRequest(new { error = "Database already has items/recipes. Clear first or use upsert." });
var defaultItems = DefaultItemData.GetDefaultItems();
var defaultRecipes = DefaultItemData.GetDefaultRecipes();
_db.GameItems.AddRange(defaultItems);
_db.GameRecipes.AddRange(defaultRecipes);
await _db.SaveChangesAsync();
await _itemService.ReloadCacheAsync();
return Ok(new {
message = "Default items seeded",
itemsAdded = defaultItems.Count,
recipesAdded = defaultRecipes.Count
});
}
}
public class GameItemDto
{
public int Id { get; set; }
public string Name { get; set; } = "";
public ItemCategory Category { get; set; }
public int CraftCost { get; set; }
public string Description { get; set; } = "";
public int LootValue { get; set; }
public bool Stackable { get; set; }
public bool IsEnabled { get; set; } = true;
public int Damage { get; set; }
public float FireRate { get; set; }
public float ProjectileSpeed { get; set; }
public float Range { get; set; }
public int AmmoType { get; set; }
public int PelletCount { get; set; } = 1;
public float Spread { get; set; }
public float ExplosionRadius { get; set; }
public float HarvestMultiplier { get; set; } = 1f;
public float ScanRadius { get; set; }
public float ScanCooldown { get; set; }
public int ShieldHealth { get; set; }
public float ShieldDuration { get; set; }
public int HealAmount { get; set; }
public float ShieldBoostDuration { get; set; }
public float DamageReduction { get; set; }
public float SpeedBoostDuration { get; set; }
public float SpeedMultiplier { get; set; } = 1f;
public int HealthBonus { get; set; }
public float SpeedPenalty { get; set; }
public float DashDistance { get; set; }
public float DashCooldown { get; set; }
}
public class GameRecipeDto
{
public int Id { get; set; }
public int ResultItemId { get; set; }
public int ScrapCost { get; set; }
public int EnergyCost { get; set; }
public int RareCost { get; set; }
public bool IsEnabled { get; set; } = true;
}
+343
View File
@@ -0,0 +1,343 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
namespace VoidScavengers.Api;
/// <summary>
/// API endpoints for player statistics and leaderboards
/// </summary>
[ApiController]
[Route("api/stats")]
public class StatsController : ControllerBase
{
private readonly GameDbContext _db;
public StatsController(GameDbContext db)
{
_db = db;
}
/// <summary>
/// Get stats for a specific player by account ID
/// </summary>
[HttpGet("player/{accountId}")]
public async Task<IActionResult> GetPlayerStats(ulong accountId)
{
var stats = await _db.PlayerStats
.Where(s => s.AccountId == accountId)
.Select(s => new PlayerStatsDto
{
AccountId = s.AccountId,
Username = s.Account.Username,
MatchesPlayed = s.MatchesPlayed,
Wins = s.Wins,
Losses = s.Losses,
Extractions = s.Extractions,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
TotalDamageDealt = s.TotalDamageDealt,
TotalDamageTaken = s.TotalDamageTaken,
TotalScrapCollected = s.TotalScrapCollected,
TotalEnergyCollected = s.TotalEnergyCollected,
TotalRareCollected = s.TotalRareCollected,
ItemsCrafted = s.ItemsCrafted,
TotalPlayTimeSeconds = s.TotalPlayTimeSeconds,
LongestSurvivalSeconds = s.LongestSurvivalSeconds,
Elo = s.Elo
})
.FirstOrDefaultAsync();
if (stats == null)
return NotFound(new { error = "Player stats not found" });
return Ok(stats);
}
/// <summary>
/// Get stats for a player by username
/// </summary>
[HttpGet("player/name/{username}")]
public async Task<IActionResult> GetPlayerStatsByName(string username)
{
var stats = await _db.PlayerStats
.Where(s => s.Account.Username == username)
.Select(s => new PlayerStatsDto
{
AccountId = s.AccountId,
Username = s.Account.Username,
MatchesPlayed = s.MatchesPlayed,
Wins = s.Wins,
Losses = s.Losses,
Extractions = s.Extractions,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
TotalDamageDealt = s.TotalDamageDealt,
TotalDamageTaken = s.TotalDamageTaken,
TotalScrapCollected = s.TotalScrapCollected,
TotalEnergyCollected = s.TotalEnergyCollected,
TotalRareCollected = s.TotalRareCollected,
ItemsCrafted = s.ItemsCrafted,
TotalPlayTimeSeconds = s.TotalPlayTimeSeconds,
LongestSurvivalSeconds = s.LongestSurvivalSeconds,
Elo = s.Elo
})
.FirstOrDefaultAsync();
if (stats == null)
return NotFound(new { error = "Player not found" });
return Ok(stats);
}
/// <summary>
/// Get leaderboard by Elo rating
/// </summary>
[HttpGet("leaderboard")]
public async Task<IActionResult> GetLeaderboard(
[FromQuery] string sort = "elo",
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
pageSize = Math.Clamp(pageSize, 1, 100);
page = Math.Max(1, page);
var query = _db.PlayerStats
.Where(s => s.MatchesPlayed >= 5); // Minimum games to appear on leaderboard
query = sort.ToLower() switch
{
"wins" => query.OrderByDescending(s => s.Wins),
"kills" => query.OrderByDescending(s => s.Kills),
"winrate" => query.OrderByDescending(s => s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed : 0),
"kd" => query.OrderByDescending(s => s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills),
"extractions" => query.OrderByDescending(s => s.Extractions),
"playtime" => query.OrderByDescending(s => s.TotalPlayTimeSeconds),
_ => query.OrderByDescending(s => s.Elo)
};
var totalCount = await query.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var entries = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(s => new LeaderboardEntryDto
{
Rank = 0, // Calculated below
AccountId = s.AccountId,
Username = s.Account.Username,
Elo = s.Elo,
Wins = s.Wins,
Losses = s.Losses,
WinRate = s.MatchesPlayed > 0 ? (float)s.Wins / s.MatchesPlayed * 100 : 0,
Kills = s.Kills,
Deaths = s.Deaths,
KdRatio = s.Deaths > 0 ? (float)s.Kills / s.Deaths : s.Kills,
Extractions = s.Extractions,
MatchesPlayed = s.MatchesPlayed
})
.ToListAsync();
// Calculate ranks
int startRank = (page - 1) * pageSize + 1;
for (int i = 0; i < entries.Count; i++)
{
entries[i].Rank = startRank + i;
}
return Ok(new LeaderboardResponse
{
Entries = entries,
Page = page,
PageSize = pageSize,
TotalPages = totalPages,
TotalCount = totalCount,
SortBy = sort
});
}
/// <summary>
/// Get match history for a player
/// </summary>
[HttpGet("player/{accountId}/history")]
public async Task<IActionResult> GetMatchHistory(
ulong accountId,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
{
pageSize = Math.Clamp(pageSize, 1, 50);
page = Math.Max(1, page);
var query = _db.MatchHistory
.Where(m => m.AccountId == accountId)
.OrderByDescending(m => m.PlayedAt);
var totalCount = await query.CountAsync();
var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
var matches = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(m => new MatchHistoryDto
{
MatchId = m.MatchId,
PlayedAt = m.PlayedAt,
Result = m.Result.ToString(),
Placement = m.Placement,
TotalPlayers = m.TotalPlayers,
Kills = m.Kills,
Deaths = m.Deaths,
DamageDealt = m.DamageDealt,
DamageTaken = m.DamageTaken,
ScrapCollected = m.ScrapCollected,
EnergyCollected = m.EnergyCollected,
RareCollected = m.RareCollected,
ItemsCrafted = m.ItemsCrafted,
SurvivalTimeSeconds = m.SurvivalTimeSeconds,
EloChange = m.EloChange,
EloAfter = m.EloAfter
})
.ToListAsync();
return Ok(new MatchHistoryResponse
{
Matches = matches,
Page = page,
PageSize = pageSize,
TotalPages = totalPages,
TotalCount = totalCount
});
}
/// <summary>
/// Get global statistics
/// </summary>
[HttpGet("global")]
public async Task<IActionResult> GetGlobalStats()
{
var stats = await _db.PlayerStats
.GroupBy(s => 1)
.Select(g => new GlobalStatsDto
{
TotalPlayers = g.Count(),
TotalMatchesPlayed = g.Sum(s => s.MatchesPlayed),
TotalKills = g.Sum(s => s.Kills),
TotalExtractions = g.Sum(s => s.Extractions),
TotalPlayTimeHours = g.Sum(s => s.TotalPlayTimeSeconds) / 3600.0,
AverageElo = g.Average(s => (double)s.Elo),
TopElo = g.Max(s => s.Elo)
})
.FirstOrDefaultAsync();
if (stats == null)
{
return Ok(new GlobalStatsDto());
}
// Get active players (played in last 7 days)
var sevenDaysAgo = DateTime.UtcNow.AddDays(-7);
stats.ActivePlayers = await _db.MatchHistory
.Where(m => m.PlayedAt >= sevenDaysAgo)
.Select(m => m.AccountId)
.Distinct()
.CountAsync();
return Ok(stats);
}
}
// DTOs
public class PlayerStatsDto
{
public ulong AccountId { get; set; }
public string Username { get; set; } = "";
public int MatchesPlayed { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public int Extractions { get; set; }
public float WinRate { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public float KdRatio { get; set; }
public long TotalDamageDealt { get; set; }
public long TotalDamageTaken { get; set; }
public long TotalScrapCollected { get; set; }
public long TotalEnergyCollected { get; set; }
public long TotalRareCollected { get; set; }
public int ItemsCrafted { get; set; }
public long TotalPlayTimeSeconds { get; set; }
public int LongestSurvivalSeconds { get; set; }
public int Elo { get; set; }
}
public class LeaderboardEntryDto
{
public int Rank { get; set; }
public ulong AccountId { get; set; }
public string Username { get; set; } = "";
public int Elo { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public float WinRate { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public float KdRatio { get; set; }
public int Extractions { get; set; }
public int MatchesPlayed { get; set; }
}
public class LeaderboardResponse
{
public List<LeaderboardEntryDto> Entries { get; set; } = new();
public int Page { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalCount { get; set; }
public string SortBy { get; set; } = "";
}
public class MatchHistoryDto
{
public string MatchId { get; set; } = "";
public DateTime PlayedAt { get; set; }
public string Result { get; set; } = "";
public int Placement { get; set; }
public int TotalPlayers { get; set; }
public int Kills { get; set; }
public int Deaths { get; set; }
public int DamageDealt { get; set; }
public int DamageTaken { get; set; }
public int ScrapCollected { get; set; }
public int EnergyCollected { get; set; }
public int RareCollected { get; set; }
public int ItemsCrafted { get; set; }
public int SurvivalTimeSeconds { get; set; }
public int EloChange { get; set; }
public int EloAfter { get; set; }
}
public class MatchHistoryResponse
{
public List<MatchHistoryDto> Matches { get; set; } = new();
public int Page { get; set; }
public int PageSize { get; set; }
public int TotalPages { get; set; }
public int TotalCount { get; set; }
}
public class GlobalStatsDto
{
public int TotalPlayers { get; set; }
public int ActivePlayers { get; set; }
public int TotalMatchesPlayed { get; set; }
public int TotalKills { get; set; }
public int TotalExtractions { get; set; }
public double TotalPlayTimeHours { get; set; }
public double AverageElo { get; set; }
public int TopElo { get; set; }
}
+279
View File
@@ -0,0 +1,279 @@
using System.Collections.Concurrent;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Server.Data;
namespace VoidScavengers.Game;
/// <summary>
/// Interface for item data access
/// </summary>
public interface IItemService
{
GameItemData? GetItem(int id);
GameRecipeData? GetRecipe(int id);
IReadOnlyList<GameItemData> GetAllItems();
IReadOnlyList<GameRecipeData> GetAllRecipes();
IReadOnlyList<GameItemData> GetItemsByCategory(ItemCategory category);
Task ReloadCacheAsync();
}
/// <summary>
/// Runtime item data (cached from database)
/// </summary>
public sealed class GameItemData
{
public int Id { get; init; }
public string Name { get; init; } = "";
public ItemCategory Category { get; init; }
public int CraftCost { get; init; }
public string Description { get; init; } = "";
public int LootValue { get; init; }
public bool Stackable { get; init; }
// Weapon stats
public int Damage { get; init; }
public float FireRate { get; init; }
public float ProjectileSpeed { get; init; }
public float Range { get; init; }
public int AmmoType { get; init; }
public int PelletCount { get; init; } = 1;
public float Spread { get; init; }
public float ExplosionRadius { get; init; }
// Tool stats
public float HarvestMultiplier { get; init; } = 1f;
public float ScanRadius { get; init; }
public float ScanCooldown { get; init; }
public int ShieldHealth { get; init; }
public float ShieldDuration { get; init; }
// Consumable stats
public int HealAmount { get; init; }
public float ShieldBoostDuration { get; init; }
public float DamageReduction { get; init; }
public float SpeedBoostDuration { get; init; }
public float SpeedMultiplier { get; init; } = 1f;
// Armor stats
public int HealthBonus { get; init; }
public float SpeedPenalty { get; init; }
public float DashDistance { get; init; }
public float DashCooldown { get; init; }
public static GameItemData FromEntity(GameItem e) => new()
{
Id = e.Id,
Name = e.Name,
Category = e.Category,
CraftCost = e.CraftCost,
Description = e.Description,
LootValue = e.LootValue,
Stackable = e.Stackable,
Damage = e.Damage,
FireRate = e.FireRate,
ProjectileSpeed = e.ProjectileSpeed,
Range = e.Range,
AmmoType = e.AmmoType,
PelletCount = e.PelletCount,
Spread = e.Spread,
ExplosionRadius = e.ExplosionRadius,
HarvestMultiplier = e.HarvestMultiplier,
ScanRadius = e.ScanRadius,
ScanCooldown = e.ScanCooldown,
ShieldHealth = e.ShieldHealth,
ShieldDuration = e.ShieldDuration,
HealAmount = e.HealAmount,
ShieldBoostDuration = e.ShieldBoostDuration,
DamageReduction = e.DamageReduction,
SpeedBoostDuration = e.SpeedBoostDuration,
SpeedMultiplier = e.SpeedMultiplier,
HealthBonus = e.HealthBonus,
SpeedPenalty = e.SpeedPenalty,
DashDistance = e.DashDistance,
DashCooldown = e.DashCooldown
};
}
/// <summary>
/// Runtime recipe data (cached from database)
/// </summary>
public sealed class GameRecipeData
{
public int Id { get; init; }
public int ResultItemId { get; init; }
public int ScrapCost { get; init; }
public int EnergyCost { get; init; }
public int RareCost { get; init; }
public bool CanCraft(int scrap, int energy, int rare)
{
return scrap >= ScrapCost && energy >= EnergyCost && rare >= RareCost;
}
public static GameRecipeData FromEntity(GameRecipe e) => new()
{
Id = e.Id,
ResultItemId = e.ResultItemId,
ScrapCost = e.ScrapCost,
EnergyCost = e.EnergyCost,
RareCost = e.RareCost
};
}
/// <summary>
/// Cached item service that loads from database and refreshes periodically
/// </summary>
public sealed class CachedItemService : IItemService, IDisposable
{
private readonly ILogger<CachedItemService> _log;
private readonly IServiceScopeFactory _scopeFactory;
private readonly Timer _refreshTimer;
private ConcurrentDictionary<int, GameItemData> _items = new();
private ConcurrentDictionary<int, GameRecipeData> _recipes = new();
private ConcurrentDictionary<ItemCategory, List<GameItemData>> _itemsByCategory = new();
private static readonly TimeSpan RefreshInterval = TimeSpan.FromMinutes(5);
public CachedItemService(ILogger<CachedItemService> log, IServiceScopeFactory scopeFactory)
{
_log = log;
_scopeFactory = scopeFactory;
// Initial load
_ = ReloadCacheAsync();
// Periodic refresh
_refreshTimer = new Timer(_ => _ = ReloadCacheAsync(), null, RefreshInterval, RefreshInterval);
}
public GameItemData? GetItem(int id) => _items.TryGetValue(id, out var item) ? item : null;
public GameRecipeData? GetRecipe(int id) => _recipes.TryGetValue(id, out var recipe) ? recipe : null;
public IReadOnlyList<GameItemData> GetAllItems() => _items.Values.ToList();
public IReadOnlyList<GameRecipeData> GetAllRecipes() => _recipes.Values.ToList();
public IReadOnlyList<GameItemData> GetItemsByCategory(ItemCategory category)
{
return _itemsByCategory.TryGetValue(category, out var items) ? items : new List<GameItemData>();
}
public async Task ReloadCacheAsync()
{
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Load items
var items = await db.GameItems
.Where(i => i.IsEnabled)
.ToListAsync();
var newItems = new ConcurrentDictionary<int, GameItemData>();
var newByCategory = new ConcurrentDictionary<ItemCategory, List<GameItemData>>();
foreach (var item in items)
{
var data = GameItemData.FromEntity(item);
newItems[item.Id] = data;
if (!newByCategory.ContainsKey(item.Category))
newByCategory[item.Category] = new List<GameItemData>();
newByCategory[item.Category].Add(data);
}
// Load recipes
var recipes = await db.GameRecipes
.Where(r => r.IsEnabled)
.ToListAsync();
var newRecipes = new ConcurrentDictionary<int, GameRecipeData>();
foreach (var recipe in recipes)
{
newRecipes[recipe.Id] = GameRecipeData.FromEntity(recipe);
}
// Atomic swap
_items = newItems;
_recipes = newRecipes;
_itemsByCategory = newByCategory;
_log.LogInformation("Loaded {ItemCount} items and {RecipeCount} recipes from database",
items.Count, recipes.Count);
}
catch (Exception ex)
{
_log.LogError(ex, "Failed to reload item cache from database");
}
}
public void Dispose()
{
_refreshTimer.Dispose();
}
}
/// <summary>
/// Fallback static item database (used if DB is empty or for seeding)
/// </summary>
public static class DefaultItemData
{
public static List<GameItem> GetDefaultItems() => new()
{
// Resources
new() { Id = 1, Name = "Scrap Metal", Category = ItemCategory.Resource, CraftCost = 0, Description = "Basic salvage material", LootValue = 1, Stackable = true },
new() { Id = 2, Name = "Energy Cell", Category = ItemCategory.Resource, CraftCost = 0, Description = "Charged power source", LootValue = 2, Stackable = true },
new() { Id = 3, Name = "Rare Alloy", Category = ItemCategory.Resource, CraftCost = 0, Description = "Precious refined metal", LootValue = 5, Stackable = true },
// Weapons
new() { Id = 100, Name = "Pulse Pistol", Category = ItemCategory.Weapon, CraftCost = 15, Description = "Basic sidearm", LootValue = 10, Stackable = false, Damage = 10, FireRate = 4f, ProjectileSpeed = 400f, Range = 300f },
new() { Id = 101, Name = "Scatter Gun", Category = ItemCategory.Weapon, CraftCost = 25, Description = "Close-range devastation", LootValue = 20, Stackable = false, Damage = 6, FireRate = 1.5f, ProjectileSpeed = 350f, Range = 150f, PelletCount = 5, Spread = 0.4f },
new() { Id = 102, Name = "Rail Rifle", Category = ItemCategory.Weapon, CraftCost = 40, Description = "Long-range precision", LootValue = 35, Stackable = false, Damage = 45, FireRate = 0.8f, ProjectileSpeed = 800f, Range = 600f },
new() { Id = 103, Name = "Plasma Launcher", Category = ItemCategory.Weapon, CraftCost = 60, Description = "Area damage weapon", LootValue = 50, Stackable = false, Damage = 30, FireRate = 0.5f, ProjectileSpeed = 250f, Range = 400f, ExplosionRadius = 50f },
// Tools
new() { Id = 200, Name = "Mining Laser", Category = ItemCategory.Tool, CraftCost = 15, Description = "Harvests resources faster", LootValue = 12, Stackable = false, HarvestMultiplier = 2.0f },
new() { Id = 201, Name = "Scanner", Category = ItemCategory.Tool, CraftCost = 20, Description = "Reveals nearby resources and players", LootValue = 15, Stackable = false, ScanRadius = 200f, ScanCooldown = 10f },
new() { Id = 202, Name = "Portable Shield", Category = ItemCategory.Tool, CraftCost = 35, Description = "Deployable cover", LootValue = 25, Stackable = false, ShieldHealth = 100, ShieldDuration = 15f },
// Consumables
new() { Id = 300, Name = "Repair Kit", Category = ItemCategory.Consumable, CraftCost = 10, Description = "Restores 30 health", LootValue = 8, Stackable = true, HealAmount = 30 },
new() { Id = 301, Name = "Shield Booster", Category = ItemCategory.Consumable, CraftCost = 15, Description = "Temporary damage reduction", LootValue = 12, Stackable = true, ShieldBoostDuration = 10f, DamageReduction = 0.3f },
new() { Id = 302, Name = "Speed Stim", Category = ItemCategory.Consumable, CraftCost = 12, Description = "Temporary speed boost", LootValue = 10, Stackable = true, SpeedBoostDuration = 8f, SpeedMultiplier = 1.5f },
// Armor
new() { Id = 400, Name = "Light Suit", Category = ItemCategory.Armor, CraftCost = 20, Description = "+20 max health", LootValue = 15, Stackable = false, HealthBonus = 20 },
new() { Id = 401, Name = "Heavy Suit", Category = ItemCategory.Armor, CraftCost = 45, Description = "+50 max health, slower", LootValue = 35, Stackable = false, HealthBonus = 50, SpeedPenalty = 0.15f },
new() { Id = 402, Name = "Thruster Pack", Category = ItemCategory.Armor, CraftCost = 30, Description = "Dash ability", LootValue = 25, Stackable = false, DashDistance = 100f, DashCooldown = 5f }
};
public static List<GameRecipe> GetDefaultRecipes() => new()
{
// Weapons
new() { Id = 1, ResultItemId = 100, ScrapCost = 5, EnergyCost = 2, RareCost = 0 },
new() { Id = 2, ResultItemId = 101, ScrapCost = 8, EnergyCost = 3, RareCost = 0 },
new() { Id = 3, ResultItemId = 102, ScrapCost = 10, EnergyCost = 5, RareCost = 2 },
new() { Id = 4, ResultItemId = 103, ScrapCost = 15, EnergyCost = 8, RareCost = 4 },
// Tools
new() { Id = 10, ResultItemId = 200, ScrapCost = 6, EnergyCost = 3, RareCost = 0 },
new() { Id = 11, ResultItemId = 201, ScrapCost = 8, EnergyCost = 4, RareCost = 1 },
new() { Id = 12, ResultItemId = 202, ScrapCost = 12, EnergyCost = 6, RareCost = 2 },
// Consumables
new() { Id = 20, ResultItemId = 300, ScrapCost = 3, EnergyCost = 2, RareCost = 0 },
new() { Id = 21, ResultItemId = 301, ScrapCost = 4, EnergyCost = 3, RareCost = 0 },
new() { Id = 22, ResultItemId = 302, ScrapCost = 3, EnergyCost = 4, RareCost = 0 },
// Armor
new() { Id = 30, ResultItemId = 400, ScrapCost = 8, EnergyCost = 0, RareCost = 1 },
new() { Id = 31, ResultItemId = 401, ScrapCost = 15, EnergyCost = 0, RareCost = 3 },
new() { Id = 32, ResultItemId = 402, ScrapCost = 10, EnergyCost = 5, RareCost = 2 }
};
}
@@ -0,0 +1,831 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Server.Data;
#nullable disable
namespace SystemRevivalServer.Migrations
{
[DbContext(typeof(GameDbContext))]
[Migration("20251204143006_AddVoidScavengersEntities")]
partial class AddVoidScavengersEntities
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder);
modelBuilder.Entity("Server.Data.Account", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime?>("BannedUntil")
.HasColumnType("datetime(6)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("Email")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<bool>("IsBanned")
.HasColumnType("tinyint(1)");
b.Property<byte[]>("PasswordHash")
.IsRequired()
.HasColumnType("varbinary(64)");
b.Property<byte[]>("PasswordSalt")
.IsRequired()
.HasColumnType("varbinary(32)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("accounts", (string)null);
});
modelBuilder.Entity("Server.Data.Character", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<string>("AppearanceJson")
.HasColumnType("json");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<float>("FacingDeg")
.HasColumnType("float");
b.Property<uint>("HpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("HpMax")
.HasColumnType("int unsigned");
b.Property<uint>("Level")
.HasColumnType("int unsigned");
b.Property<uint>("MpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("MpMax")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<double>("PosX")
.HasColumnType("double");
b.Property<double>("PosY")
.HasColumnType("double");
b.Property<double>("PosZ")
.HasColumnType("double");
b.Property<uint>("StaminaCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("StaminaMax")
.HasColumnType("int unsigned");
b.Property<uint>("StatDexterity")
.HasColumnType("int unsigned");
b.Property<uint>("StatEndurance")
.HasColumnType("int unsigned");
b.Property<uint>("StatIntelligence")
.HasColumnType("int unsigned");
b.Property<uint>("StatStrength")
.HasColumnType("int unsigned");
b.Property<uint>("StatWisdom")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<ulong>("Xp")
.HasColumnType("bigint unsigned");
b.Property<ulong>("ZoneId")
.HasColumnType("bigint unsigned");
b.HasKey("Id");
b.HasIndex("AccountId")
.IsUnique();
b.HasIndex("ZoneId");
b.ToTable("characters", (string)null);
});
modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<byte>("SlotCode")
.HasColumnType("tinyint unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("ItemTemplateId");
b.HasIndex("CharacterId", "SlotCode")
.IsUnique();
b.ToTable("equipment", (string)null);
});
modelBuilder.Entity("Server.Data.GameItem", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<int>("AmmoType")
.HasColumnType("int");
b.Property<int>("Category")
.HasColumnType("int");
b.Property<int>("CraftCost")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("Damage")
.HasColumnType("int");
b.Property<float>("DamageReduction")
.HasColumnType("float");
b.Property<float>("DashCooldown")
.HasColumnType("float");
b.Property<float>("DashDistance")
.HasColumnType("float");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<float>("ExplosionRadius")
.HasColumnType("float");
b.Property<float>("FireRate")
.HasColumnType("float");
b.Property<float>("HarvestMultiplier")
.HasColumnType("float");
b.Property<int>("HealAmount")
.HasColumnType("int");
b.Property<int>("HealthBonus")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("LootValue")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<int>("PelletCount")
.HasColumnType("int");
b.Property<float>("ProjectileSpeed")
.HasColumnType("float");
b.Property<float>("Range")
.HasColumnType("float");
b.Property<float>("ScanCooldown")
.HasColumnType("float");
b.Property<float>("ScanRadius")
.HasColumnType("float");
b.Property<float>("ShieldBoostDuration")
.HasColumnType("float");
b.Property<float>("ShieldDuration")
.HasColumnType("float");
b.Property<int>("ShieldHealth")
.HasColumnType("int");
b.Property<float>("SpeedBoostDuration")
.HasColumnType("float");
b.Property<float>("SpeedMultiplier")
.HasColumnType("float");
b.Property<float>("SpeedPenalty")
.HasColumnType("float");
b.Property<float>("Spread")
.HasColumnType("float");
b.Property<bool>("Stackable")
.HasColumnType("tinyint(1)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("Category");
b.HasIndex("IsEnabled");
b.ToTable("game_items", (string)null);
});
modelBuilder.Entity("Server.Data.GameRecipe", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("EnergyCost")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("RareCost")
.HasColumnType("int");
b.Property<int>("ResultItemId")
.HasColumnType("int");
b.Property<int>("ScrapCost")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.HasIndex("ResultItemId");
b.ToTable("game_recipes", (string)null);
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<uint>("Quantity")
.HasColumnType("int unsigned");
b.Property<uint>("SlotIndex")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("CharacterId");
b.HasIndex("ItemTemplateId");
b.HasIndex("CharacterId", "SlotIndex")
.IsUnique();
b.ToTable("inventories", (string)null);
});
modelBuilder.Entity("Server.Data.ItemTemplate", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<byte>("ItemType")
.HasColumnType("tinyint unsigned");
b.Property<uint>("MaxStack")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<byte>("Rarity")
.HasColumnType("tinyint unsigned");
b.Property<string>("StatsJson")
.HasColumnType("json");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<uint>("Weight")
.HasColumnType("int unsigned");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("item_templates", (string)null);
});
modelBuilder.Entity("Server.Data.MatchHistory", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<int>("DamageDealt")
.HasColumnType("int");
b.Property<int>("DamageTaken")
.HasColumnType("int");
b.Property<int>("Deaths")
.HasColumnType("int");
b.Property<int>("EloAfter")
.HasColumnType("int");
b.Property<int>("EloChange")
.HasColumnType("int");
b.Property<int>("EnergyCollected")
.HasColumnType("int");
b.Property<int>("ItemsCrafted")
.HasColumnType("int");
b.Property<int>("Kills")
.HasColumnType("int");
b.Property<int>("MatchDurationSeconds")
.HasColumnType("int");
b.Property<string>("MatchId")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<int>("Placement")
.HasColumnType("int");
b.Property<DateTime>("PlayedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("RareCollected")
.HasColumnType("int");
b.Property<int>("Result")
.HasColumnType("int");
b.Property<int>("ScrapCollected")
.HasColumnType("int");
b.Property<int>("SurvivalTimeSeconds")
.HasColumnType("int");
b.Property<int>("TotalPlayers")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("MatchId");
b.HasIndex("PlayedAt");
b.ToTable("match_history", (string)null);
});
modelBuilder.Entity("Server.Data.PlayerStats", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("Deaths")
.HasColumnType("int");
b.Property<int>("Elo")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(1000);
b.Property<int>("Extractions")
.HasColumnType("int");
b.Property<int>("ItemsCrafted")
.HasColumnType("int");
b.Property<int>("Kills")
.HasColumnType("int");
b.Property<int>("LongestSurvivalSeconds")
.HasColumnType("int");
b.Property<int>("Losses")
.HasColumnType("int");
b.Property<int>("MatchesPlayed")
.HasColumnType("int");
b.Property<long>("TotalDamageDealt")
.HasColumnType("bigint");
b.Property<long>("TotalDamageTaken")
.HasColumnType("bigint");
b.Property<long>("TotalEnergyCollected")
.HasColumnType("bigint");
b.Property<long>("TotalPlayTimeSeconds")
.HasColumnType("bigint");
b.Property<long>("TotalRareCollected")
.HasColumnType("bigint");
b.Property<long>("TotalScrapCollected")
.HasColumnType("bigint");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<int>("Wins")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AccountId")
.IsUnique();
b.ToTable("player_stats", (string)null);
});
modelBuilder.Entity("Server.Data.Session", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("CreatedIp")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<DateTime?>("RevokedAt")
.HasColumnType("datetime(6)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("UserAgent")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("sessions", (string)null);
});
modelBuilder.Entity("Server.Data.Zone", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<double>("MaxX")
.HasColumnType("double");
b.Property<double>("MaxY")
.HasColumnType("double");
b.Property<double>("MaxZ")
.HasColumnType("double");
b.Property<double>("MinX")
.HasColumnType("double");
b.Property<double>("MinY")
.HasColumnType("double");
b.Property<double>("MinZ")
.HasColumnType("double");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("zones", (string)null);
});
modelBuilder.Entity("Server.Data.Character", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithMany("Characters")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.Zone", "Zone")
.WithMany()
.HasForeignKey("ZoneId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Account");
b.Navigation("Zone");
});
modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
{
b.HasOne("Server.Data.Character", "Character")
.WithMany()
.HasForeignKey("CharacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
.WithMany()
.HasForeignKey("ItemTemplateId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Character");
b.Navigation("ItemTemplate");
});
modelBuilder.Entity("Server.Data.GameRecipe", b =>
{
b.HasOne("Server.Data.GameItem", "ResultItem")
.WithMany()
.HasForeignKey("ResultItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ResultItem");
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.HasOne("Server.Data.Character", "Character")
.WithMany()
.HasForeignKey("CharacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
.WithMany()
.HasForeignKey("ItemTemplateId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Character");
b.Navigation("ItemTemplate");
});
modelBuilder.Entity("Server.Data.MatchHistory", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithMany()
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
});
modelBuilder.Entity("Server.Data.PlayerStats", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithOne()
.HasForeignKey("Server.Data.PlayerStats", "AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
});
modelBuilder.Entity("Server.Data.Session", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithMany("Sessions")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
});
modelBuilder.Entity("Server.Data.Account", b =>
{
b.Navigation("Characters");
b.Navigation("Sessions");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,118 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class AddVoidScavengersEntities : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "game_items",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
Name = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Category = table.Column<int>(type: "int", nullable: false),
CraftCost = table.Column<int>(type: "int", nullable: false),
Description = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
LootValue = table.Column<int>(type: "int", nullable: false),
Stackable = table.Column<bool>(type: "tinyint(1)", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false, defaultValue: true),
Damage = table.Column<int>(type: "int", nullable: false),
FireRate = table.Column<float>(type: "float", nullable: false),
ProjectileSpeed = table.Column<float>(type: "float", nullable: false),
Range = table.Column<float>(type: "float", nullable: false),
AmmoType = table.Column<int>(type: "int", nullable: false),
PelletCount = table.Column<int>(type: "int", nullable: false),
Spread = table.Column<float>(type: "float", nullable: false),
ExplosionRadius = table.Column<float>(type: "float", nullable: false),
HarvestMultiplier = table.Column<float>(type: "float", nullable: false),
ScanRadius = table.Column<float>(type: "float", nullable: false),
ScanCooldown = table.Column<float>(type: "float", nullable: false),
ShieldHealth = table.Column<int>(type: "int", nullable: false),
ShieldDuration = table.Column<float>(type: "float", nullable: false),
HealAmount = table.Column<int>(type: "int", nullable: false),
ShieldBoostDuration = table.Column<float>(type: "float", nullable: false),
DamageReduction = table.Column<float>(type: "float", nullable: false),
SpeedBoostDuration = table.Column<float>(type: "float", nullable: false),
SpeedMultiplier = table.Column<float>(type: "float", nullable: false),
HealthBonus = table.Column<int>(type: "int", nullable: false),
SpeedPenalty = table.Column<float>(type: "float", nullable: false),
DashDistance = table.Column<float>(type: "float", nullable: false),
DashCooldown = table.Column<float>(type: "float", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)")
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn)
},
constraints: table =>
{
table.PrimaryKey("PK_game_items", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "game_recipes",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false),
ResultItemId = table.Column<int>(type: "int", nullable: false),
IsEnabled = table.Column<bool>(type: "tinyint(1)", nullable: false, defaultValue: true),
ScrapCost = table.Column<int>(type: "int", nullable: false),
EnergyCost = table.Column<int>(type: "int", nullable: false),
RareCost = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)")
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn)
},
constraints: table =>
{
table.PrimaryKey("PK_game_recipes", x => x.Id);
table.ForeignKey(
name: "FK_game_recipes_game_items_ResultItemId",
column: x => x.ResultItemId,
principalTable: "game_items",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_game_items_Category",
table: "game_items",
column: "Category");
migrationBuilder.CreateIndex(
name: "IX_game_items_IsEnabled",
table: "game_items",
column: "IsEnabled");
migrationBuilder.CreateIndex(
name: "IX_game_recipes_IsEnabled",
table: "game_recipes",
column: "IsEnabled");
migrationBuilder.CreateIndex(
name: "IX_game_recipes_ResultItemId",
table: "game_recipes",
column: "ResultItemId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "game_recipes");
migrationBuilder.DropTable(
name: "game_items");
}
}
}
+173
View File
@@ -210,6 +210,168 @@ namespace SystemRevivalServer.Migrations
b.ToTable("equipment", (string)null);
});
modelBuilder.Entity("Server.Data.GameItem", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<int>("AmmoType")
.HasColumnType("int");
b.Property<int>("Category")
.HasColumnType("int");
b.Property<int>("CraftCost")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("Damage")
.HasColumnType("int");
b.Property<float>("DamageReduction")
.HasColumnType("float");
b.Property<float>("DashCooldown")
.HasColumnType("float");
b.Property<float>("DashDistance")
.HasColumnType("float");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.Property<float>("ExplosionRadius")
.HasColumnType("float");
b.Property<float>("FireRate")
.HasColumnType("float");
b.Property<float>("HarvestMultiplier")
.HasColumnType("float");
b.Property<int>("HealAmount")
.HasColumnType("int");
b.Property<int>("HealthBonus")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("LootValue")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<int>("PelletCount")
.HasColumnType("int");
b.Property<float>("ProjectileSpeed")
.HasColumnType("float");
b.Property<float>("Range")
.HasColumnType("float");
b.Property<float>("ScanCooldown")
.HasColumnType("float");
b.Property<float>("ScanRadius")
.HasColumnType("float");
b.Property<float>("ShieldBoostDuration")
.HasColumnType("float");
b.Property<float>("ShieldDuration")
.HasColumnType("float");
b.Property<int>("ShieldHealth")
.HasColumnType("int");
b.Property<float>("SpeedBoostDuration")
.HasColumnType("float");
b.Property<float>("SpeedMultiplier")
.HasColumnType("float");
b.Property<float>("SpeedPenalty")
.HasColumnType("float");
b.Property<float>("Spread")
.HasColumnType("float");
b.Property<bool>("Stackable")
.HasColumnType("tinyint(1)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("Category");
b.HasIndex("IsEnabled");
b.ToTable("game_items", (string)null);
});
modelBuilder.Entity("Server.Data.GameRecipe", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<int>("EnergyCost")
.HasColumnType("int");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint(1)")
.HasDefaultValue(true);
b.Property<int>("RareCost")
.HasColumnType("int");
b.Property<int>("ResultItemId")
.HasColumnType("int");
b.Property<int>("ScrapCost")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.HasIndex("ResultItemId");
b.ToTable("game_recipes", (string)null);
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.Property<ulong>("Id")
@@ -591,6 +753,17 @@ namespace SystemRevivalServer.Migrations
b.Navigation("ItemTemplate");
});
modelBuilder.Entity("Server.Data.GameRecipe", b =>
{
b.HasOne("Server.Data.GameItem", "ResultItem")
.WithMany()
.HasForeignKey("ResultItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ResultItem");
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.HasOne("Server.Data.Character", "Character")
+4 -1
View File
@@ -58,6 +58,9 @@ builder.Services.AddSingleton<MatchManager>();
builder.Services.AddSingleton<IClientMessageHandler, GameHandler>();
builder.Services.AddSingleton<MessageRouter>();
builder.Services.AddSingleton<IItemService, CachedItemService>();
builder.Services.AddControllers();
// Health checks
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("mysql", tags: new[] { "ready" });
@@ -181,5 +184,5 @@ app.Lifetime.ApplicationStopping.Register(() =>
// ---- (Optional) acquire a dev zone on startup ----
// var leases = app.Services.GetRequiredService<IZoneLeaseService>();
// _ = leases.TryAcquireAsync(zoneId: 1);
app.MapControllers();
await app.RunAsync();
+2
View File
@@ -16,6 +16,8 @@ public sealed class GameDbContext : DbContext
public DbSet<EquipmentSlot> Equipment => Set<EquipmentSlot>();
public DbSet<PlayerStats> PlayerStats => Set<PlayerStats>();
public DbSet<MatchHistory> MatchHistory => Set<MatchHistory>();
public DbSet<GameItem> GameItems => Set<GameItem>();
public DbSet<GameRecipe> GameRecipes => Set<GameRecipe>();
protected override void OnModelCreating(ModelBuilder b)
{
+84
View File
@@ -0,0 +1,84 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Server.Data;
/// <summary>
/// Database-backed item definition for Void Scavengers
/// </summary>
public sealed class GameItem
{
public int Id { get; set; }
public string Name { get; set; } = "";
public ItemCategory Category { get; set; }
public int CraftCost { get; set; }
public string Description { get; set; } = "";
public int LootValue { get; set; }
public bool Stackable { get; set; }
public bool IsEnabled { get; set; } = true;
// Weapon stats (JSON or individual columns)
public int Damage { get; set; }
public float FireRate { get; set; }
public float ProjectileSpeed { get; set; }
public float Range { get; set; }
public int AmmoType { get; set; }
public int PelletCount { get; set; } = 1;
public float Spread { get; set; }
public float ExplosionRadius { get; set; }
// Tool stats
public float HarvestMultiplier { get; set; } = 1f;
public float ScanRadius { get; set; }
public float ScanCooldown { get; set; }
public int ShieldHealth { get; set; }
public float ShieldDuration { get; set; }
// Consumable stats
public int HealAmount { get; set; }
public float ShieldBoostDuration { get; set; }
public float DamageReduction { get; set; }
public float SpeedBoostDuration { get; set; }
public float SpeedMultiplier { get; set; } = 1f;
// Armor stats
public int HealthBonus { get; set; }
public float SpeedPenalty { get; set; }
public float DashDistance { get; set; }
public float DashCooldown { get; set; }
// Timestamps
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public enum ItemCategory
{
Resource = 0,
Weapon = 1,
Tool = 2,
Consumable = 3,
Armor = 4
}
public sealed class GameItemConfig : IEntityTypeConfiguration<GameItem>
{
public void Configure(EntityTypeBuilder<GameItem> e)
{
e.ToTable("game_items");
e.HasKey(x => x.Id);
// Not auto-generated - we want specific IDs
e.Property(x => x.Id).ValueGeneratedNever();
e.Property(x => x.Name).HasMaxLength(64).IsRequired();
e.Property(x => x.Description).HasMaxLength(256);
e.Property(x => x.IsEnabled).HasDefaultValue(true);
e.HasIndex(x => x.Category);
e.HasIndex(x => x.IsEnabled);
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
}
}
+49
View File
@@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Server.Data;
/// <summary>
/// Database-backed crafting recipe for Void Scavengers
/// </summary>
public sealed class GameRecipe
{
public int Id { get; set; }
public int ResultItemId { get; set; }
public bool IsEnabled { get; set; } = true;
// Resource costs
public int ScrapCost { get; set; }
public int EnergyCost { get; set; }
public int RareCost { get; set; }
// Timestamps
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
// Navigation
public GameItem? ResultItem { get; set; }
}
public sealed class GameRecipeConfig : IEntityTypeConfiguration<GameRecipe>
{
public void Configure(EntityTypeBuilder<GameRecipe> e)
{
e.ToTable("game_recipes");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedNever();
e.HasIndex(x => x.ResultItemId);
e.HasIndex(x => x.IsEnabled);
e.HasOne(x => x.ResultItem)
.WithMany()
.HasForeignKey(x => x.ResultItemId)
.OnDelete(DeleteBehavior.Cascade);
e.Property(x => x.IsEnabled).HasDefaultValue(true);
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
}
}