Big cleanup

This commit is contained in:
dingo
2025-12-26 12:20:48 -05:00
parent 724dd5b7c5
commit 84d49520a0
23 changed files with 5 additions and 1072 deletions
-5
View File
@@ -1,5 +0,0 @@
namespace Server.Persistence;
public interface IWalPublisher
{
Task PublishAsync(string type, ulong charId, ulong zoneId, object payload, long tickId);
}
-28
View File
@@ -1,28 +0,0 @@
using System.Text.Json;
using Server.Redis;
namespace Server.Persistence;
public sealed class WalPublisher : IWalPublisher
{
private readonly IRedisManager _redis;
public WalPublisher(IRedisManager redis) { _redis = redis; }
public async Task PublishAsync(string type, ulong charId, ulong zoneId, object payload, long tickId)
{
var ev = new
{
eventId = Guid.NewGuid().ToString("N"),
type,
charId,
zoneId,
tickId,
ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
payload = payload
};
var json = JsonSerializer.Serialize(ev);
await _redis.Db.StreamAddAsync("wal:game", new StackExchange.Redis.NameValueEntry[] {
new("data", json)
}, maxLength: 1_000_000, useApproximateMaxLength: true);
}
}
-4
View File
@@ -11,7 +11,6 @@ using DataServer.Data;
using Server.Networking; using Server.Networking;
using Server.Networking.Handling; using Server.Networking.Handling;
using Server.Networking.Messages; using Server.Networking.Messages;
using Server.Persistence;
using Server.Redis; using Server.Redis;
using Server.Services; using Server.Services;
using Server.Services.Auth; using Server.Services.Auth;
@@ -60,9 +59,6 @@ builder.Services.AddOptions<DatabaseOptions>()
// Redis + zone leases + WAL // Redis + zone leases + WAL
builder.Services.AddSingleton<IRedisManager, RedisManager>(); builder.Services.AddSingleton<IRedisManager, RedisManager>();
builder.Services.AddSingleton<IZoneLeaseService, ZoneLeaseService>();
builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService<IZoneLeaseService>());
builder.Services.AddSingleton<IWalPublisher, WalPublisher>();
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>(); builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
builder.Services.AddScoped<ISessionAudit, SessionAudit>(); builder.Services.AddScoped<ISessionAudit, SessionAudit>();
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>(); builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
-82
View File
@@ -1,82 +0,0 @@
// Server.Services.Characters/CharacterService.cs
using Microsoft.Extensions.Logging;
using DataServer.Data;
namespace Server.Services.Characters;
public sealed class CharacterService : ICharacterService
{
private readonly ILogger<CharacterService> _log;
private readonly ICharactersRepository _repo;
public CharacterService(ILogger<CharacterService> log, ICharactersRepository repo)
{ _log = log; _repo = repo; }
public async Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct)
{
var one = await _repo.FindByAccountAsync(accountId, ct);
return (true, null, one is null ? Array.Empty<Old_Character>() : new[] { one });
}
public async Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(name) || name.Length is < 3 or > 32)
return (false, "invalid_name", null!);
name = name.Trim();
// 1 char / account
if (await _repo.FindByAccountAsync(accountId, ct) is not null)
return (false, "char_limit", null!);
// unique names
if (await _repo.FindByNameAsync(name, ct) is not null)
return (false, "name_taken", null!);
var now = DateTime.UtcNow;
var c = new Old_Character
{
AccountId = accountId,
Name = name,
Level = 1,
Xp = 0,
StatStrength = 1,
StatDexterity = 1,
StatWisdom = 1,
StatIntelligence = 1,
StatEndurance = 1,
HpCurrent = 10,
HpMax = 10,
MpCurrent = 0,
MpMax = 0,
StaminaCurrent = 0,
StaminaMax = 0,
ZoneId = 1,
PosX = 0,
PosY = 0,
PosZ = 0,
FacingDeg = 0f,
AppearanceJson = null,
CreatedAt = now,
UpdatedAt = now
};
var created = await _repo.AddAsync(c, ct);
_log.LogInformation("Character {Id} '{Name}' created for account {Acct}", created.Id, created.Name, accountId);
return (true, null, created);
}
public async Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct)
{
var c = await _repo.FindByIdAsync(characterId, ct);
if (c is null || c.AccountId != accountId)
return (false, "char_not_found", null!);
return (true, null, c);
}
}
@@ -1,36 +0,0 @@
using Microsoft.EntityFrameworkCore;
namespace DataServer.Data;
public interface ICharactersRepository
{
Task<Old_Character?> FindByIdAsync(ulong id, CancellationToken ct);
Task<Old_Character?> FindByNameAsync(string name, CancellationToken ct);
Task<Old_Character?> FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique)
Task<Old_Character> AddAsync(Old_Character c, CancellationToken ct);
Task SaveAsync(CancellationToken ct);
}
public sealed class CharactersRepository : ICharactersRepository
{
private readonly GameDbContext _db;
public CharactersRepository(GameDbContext db) => _db = db;
public Task<Old_Character?> FindByIdAsync(ulong id, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.Id == id, ct);
public Task<Old_Character?> FindByNameAsync(string name, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.Name == name, ct);
public Task<Old_Character?> FindByAccountAsync(ulong accountId, CancellationToken ct) =>
_db.Characters.FirstOrDefaultAsync(x => x.AccountId == accountId, ct);
public async Task<Old_Character> AddAsync(Old_Character c, CancellationToken ct)
{
_db.Characters.Add(c);
await _db.SaveChangesAsync(ct);
return c;
}
public Task SaveAsync(CancellationToken ct) => _db.SaveChangesAsync(ct);
}
-10
View File
@@ -1,10 +0,0 @@
using DataServer.Data;
namespace Server.Services.Characters;
public interface ICharacterService
{
Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct);
Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct);
Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct);
}
-9
View File
@@ -1,9 +0,0 @@
namespace Server.Services;
public interface IZoneLeaseService
{
ValueTask<bool> TryAcquireAsync(ulong zoneId, CancellationToken ct = default);
ValueTask<bool> RenewAsync(ulong zoneId, CancellationToken ct = default);
ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default);
bool IsOwner(ulong zoneId);
long CurrentFence(ulong zoneId);
}
-87
View File
@@ -1,87 +0,0 @@
// Server.Services.World/WorldHandler.cs
using Server.Networking;
using Server.Networking.Handling;
using Server.Networking.Messages;
using Server.Services.Auth;
namespace Server.Services.World;
public sealed class WorldHandler : IClientMessageHandler
{
private readonly ILogger<WorldHandler> _log;
private readonly IWorldService _world;
private readonly ISessionRegistry _sessions;
private readonly IZoneLeaseService _lease;
private readonly IMessageSerializer _ser;
private readonly HandlerContext _ctx;
public WorldHandler(
ILogger<WorldHandler> log,
IWorldService world,
ISessionRegistry sessions,
IZoneLeaseService lease,
IMessageSerializer ser)
{
_log = log; _world = world; _sessions = sessions; _lease = lease; _ser = ser;
_ctx = new HandlerContext(ser);
}
public IReadOnlyCollection<int> SupportedOpCodes => new[]
{
OpCodes.WORLD_SPAWN_REQUEST,
OpCodes.WORLD_INPUT
};
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
// Expect: TryGet(connId, out accountId, out token)
if (!_sessions.TryGet(connection.Id, out var accountId, out var token))
{
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "auth_required" }, ct);
return;
}
// Expect: TryGetCharacter(connId, out characterId) ← add this to ISessionRegistry if missing
if (!_sessions.TryGetCharacter(connection.Id, out var charId))
{
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "character_required" }, ct);
return;
}
switch (opCode)
{
case OpCodes.WORLD_SPAWN_REQUEST:
{
var req = _ser.Deserialize<WorldSpawnRequest>(payload);
if (!_lease.IsOwner((ulong)req.ZoneId))
{
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = "not_owner_zone" }, ct);
return;
}
var result = await _world.SpawnAsync(accountId, charId, ct);
var ok = result.ok; var error = result.error; var self = result.self; var neighbors = result.neighbors;
if (!ok)
{
await _ctx.ReplyObjectAsync(connection, OpCodes.ERROR, new { error = error ?? "spawn_failed" }, ct);
return;
}
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, self, ct);
foreach (var n in neighbors)
await _ctx.ReplyObjectAsync(connection, OpCodes.WORLD_SPAWN, n, ct);
break;
}
case OpCodes.WORLD_INPUT:
{
var req = _ser.Deserialize<WorldInput>(payload);
if (!_lease.IsOwner((ulong)req.ZoneId)) return; // ignore for MVP
_world.EnqueueInput((ulong)req.ZoneId, charId, req.Dx, req.Dy, req.Facing, req.ClientSeq);
break;
}
}
}
}
-122
View File
@@ -1,122 +0,0 @@
// Server.Services.World/WorldService.cs
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using DataServer.Data;
using Server.World;
using StackExchange.Redis;
using Server.Networking.Messages;
namespace Server.Services.World;
public sealed class WorldService : IWorldService
{
private readonly ILogger<WorldService> _log;
private readonly ICharactersRepository _chars;
private readonly IPresenceStore _presence;
private readonly IDatabase _db; // Redis
private readonly TimeSpan _cellTtl = TimeSpan.FromSeconds(30);
// In-memory zone state (per owner node)
private sealed record Entity(ulong Id, string Name, float X, float Y, float Z, float FacingRad, float Speed);
private readonly ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, Entity>> _zones = new();
private readonly ConcurrentDictionary<ulong, ConcurrentQueue<(ulong CharId, float Dx, float Dy, float FacingRad)>> _inputs = new();
public WorldService(
ILogger<WorldService> log,
ICharactersRepository chars,
IPresenceStore presence,
IDatabase db)
{
_log = log; _chars = chars; _presence = presence; _db = db;
}
public async Task<(bool ok, string? error, WorldSpawn self, IEnumerable<WorldSpawn> neighbors)>
SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct)
{
// Prefer Redis presence; fallback to DB row.
var pos = await _presence.GetAsync(characterId, ct);
Old_Character? row;
if (pos is null)
{
row = await _chars.FindByIdAsync(characterId, ct);
if (row is null || row.AccountId != accountId)
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
var facingRad = row.FacingDeg * (MathF.PI / 180f);
pos = new Pos(row.ZoneId, (float)row.PosX, (float)row.PosY, (float)row.PosZ, facingRad);
await _presence.SetAsync(characterId, pos, ct);
}
else
{
row = await _chars.FindByIdAsync(characterId, ct);
if (row is null)
return (false, "char_not_found", default!, Array.Empty<WorldSpawn>());
}
// Update spatial cell
var cell = SpatialIndex.Cell(pos.X, pos.Y, pos.Z);
await SpatialIndex.UpdateAsync(_db, pos.ZoneId, characterId, cell, cell, _cellTtl);
// Track in-memory entity
var zone = _zones.GetOrAdd(pos.ZoneId, _ => new());
var ent = new Entity(characterId, row!.Name, pos.X, pos.Y, pos.Z, pos.FacingRad, 5f);
zone[characterId] = ent;
var self = new WorldSpawn(ent.Id, ent.Name, (int)pos.ZoneId, ent.X, ent.Y, ent.Z, ent.FacingRad, ent.Speed);
var neighbors = zone.Values.Where(e => e.Id != ent.Id)
.Select(e => new WorldSpawn(e.Id, e.Name, (int)pos.ZoneId, e.X, e.Y, e.Z, e.FacingRad, e.Speed))
.ToArray();
return (true, null, self, neighbors);
}
public void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq)
{
var q = _inputs.GetOrAdd(zoneId, _ => new());
q.Enqueue((characterId, dx, dy, facingRad));
}
public async Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct)
{
if (!_zones.TryGetValue(zoneId, out var ents)) return;
if (_inputs.TryGetValue(zoneId, out var q))
{
while (q.TryDequeue(out var itm))
{
if (!ents.TryGetValue(itm.CharId, out var e)) continue;
// Normalize input
var dx = itm.Dx; var dy = itm.Dy;
var mag = MathF.Sqrt(dx * dx + dy * dy);
if (mag > 1e-4f) { dx /= mag; dy /= mag; }
var nx = e.X + dx * e.Speed * dt;
var ny = e.Y + dy * e.Speed * dt;
var nf = float.IsFinite(itm.FacingRad) ? itm.FacingRad : e.FacingRad;
var updated = e with { X = nx, Y = ny, FacingRad = nf };
ents[e.Id] = updated;
await _presence.SetAsync(e.Id, new Pos(zoneId, nx, ny, e.Z, nf), ct);
var oldCell = SpatialIndex.Cell(e.X, e.Y, e.Z);
var newCell = SpatialIndex.Cell(nx, ny, e.Z);
await SpatialIndex.UpdateAsync(_db, zoneId, e.Id, oldCell, newCell, _cellTtl);
}
}
}
public WorldState BuildSnapshot(ulong zoneId, long tick)
{
if (!_zones.TryGetValue(zoneId, out var ents))
return new WorldState((int)zoneId, tick, Array.Empty<WorldEntityState>());
var list = ents.Values.Select(e => new WorldEntityState(e.Id, e.X, e.Y, e.Z, e.FacingRad, e.Speed)).ToArray();
return new WorldState((int)zoneId, tick, list);
}
}
-67
View File
@@ -1,67 +0,0 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Server.Redis;
namespace Server.Services;
public sealed class ZoneLeaseService : IZoneLeaseService, IHostedService, IDisposable
{
private readonly IRedisManager _redis;
private readonly ILogger<ZoneLeaseService> _log;
private readonly string _podId = Environment.GetEnvironmentVariable("POD_ID") ?? Guid.NewGuid().ToString("N");
private readonly TimeSpan _ttl = TimeSpan.FromSeconds(5);
private readonly TimeSpan _renew = TimeSpan.FromSeconds(2);
private readonly ConcurrentDictionary<ulong, long> _owned = new();
private Timer? _timer;
public ZoneLeaseService(IRedisManager redis, ILogger<ZoneLeaseService> log)
{ _redis = redis; _log = log; }
public bool IsOwner(ulong zoneId) => _owned.ContainsKey(zoneId);
public long CurrentFence(ulong zoneId) => _owned.TryGetValue(zoneId, out var f) ? f : -1;
public async ValueTask<bool> TryAcquireAsync(ulong zoneId, CancellationToken ct = default)
{
var fence = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var val = $"{_podId}:{fence}";
var key = $"zone:owner:{{{zoneId}}}"; // hash tag for cluster
var ok = await _redis.Db.StringSetAsync(key, val, _ttl, when: StackExchange.Redis.When.NotExists);
if (ok) { _owned[zoneId] = fence; _log.LogInformation("Zone {Zone} acquired, fence={Fence}", zoneId, fence); }
return ok;
}
public async ValueTask<bool> RenewAsync(ulong zoneId, CancellationToken ct = default)
{
if (!_owned.TryGetValue(zoneId, out var fence)) return false;
var key = $"zone:owner:{{{zoneId}}}";
// renew if matches (Lua CAS)
const string lua = @"
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('PEXPIRE', KEYS[1], ARGV[2]); return 1
else return 0 end";
var res = (int)(long)await _redis.Db.ScriptEvaluateAsync(lua,
new StackExchange.Redis.RedisKey[] { key },
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}", (long)_ttl.TotalMilliseconds });
return res == 1;
}
public async ValueTask ReleaseAsync(ulong zoneId, CancellationToken ct = default)
{
if (!_owned.TryRemove(zoneId, out var fence)) return;
var key = $"zone:owner:{{{zoneId}}}";
const string lua = @"if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
await _redis.Db.ScriptEvaluateAsync(lua,
new StackExchange.Redis.RedisKey[] { key },
new StackExchange.Redis.RedisValue[] { $"{_podId}:{fence}" });
_log.LogInformation("Zone {Zone} released", zoneId);
}
// Background renew loop
public Task StartAsync(CancellationToken _) { _timer = new Timer(async _ => await RenewAll(), null, _renew, _renew); return Task.CompletedTask; }
public Task StopAsync(CancellationToken _) { _timer?.Dispose(); return Task.CompletedTask; }
private async Task RenewAll()
{
foreach (var z in _owned.Keys) { if (!await RenewAsync(z)) _owned.TryRemove(z, out _); }
}
public void Dispose() => _timer?.Dispose();
}
-23
View File
@@ -1,23 +0,0 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Server.Networking.Messages;
namespace Server.Services.World;
public interface IWorldService
{
/// Spawn the selected character into the world (owner-only).
/// Returns the player's own spawn data and a list of already-present neighbors to display.
Task<(bool ok, string? error, WorldSpawn self, IEnumerable<WorldSpawn> neighbors)>
SpawnAsync(ulong accountId, ulong characterId, CancellationToken ct);
/// Queue a client input for the zone owner to process.
void EnqueueInput(ulong zoneId, ulong characterId, float dx, float dy, float facingRad, uint clientSeq);
/// Owner tick: integrate movement, update presence/grid.
Task TickOwnerAsync(ulong zoneId, float dt, CancellationToken ct);
/// Build a snapshot (naive: full-zone). Call at 10Hz and broadcast.
WorldState BuildSnapshot(ulong zoneId, long tick);
}
-4
View File
@@ -1,4 +0,0 @@
namespace Server.World;
public sealed record Pos(ulong ZoneId, float X, float Y, float Z, float FacingRad);
-42
View File
@@ -1,42 +0,0 @@
// Server.World/Presence.cs
using StackExchange.Redis;
namespace Server.World;
public interface IPresenceStore
{
Task SetAsync(ulong charId, Pos p, CancellationToken ct);
Task<Pos?> GetAsync(ulong charId, CancellationToken ct);
}
public sealed class RedisPresenceStore : IPresenceStore
{
private readonly IDatabase _db;
public RedisPresenceStore(IDatabase db) => _db = db;
private static RedisKey PKey(ulong cid) => new($"p:{cid}:pos");
public async Task SetAsync(ulong charId, Pos p, CancellationToken ct)
{
var entries = new HashEntry[]
{
new("zone", (long)p.ZoneId),
new("x", p.X), new("y", p.Y), new("z", p.Z),
new("facingRad", p.FacingRad),
new("ts", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()),
};
await _db.HashSetAsync(PKey(charId), entries);
}
public async Task<Pos?> GetAsync(ulong charId, CancellationToken ct)
{
var vals = await _db.HashGetAllAsync(PKey(charId));
if (vals.Length == 0) return null;
ulong zone = (ulong)(long)vals.First(v => v.Name == "zone").Value;
float x = (float)vals.First(v => v.Name == "x").Value;
float y = (float)vals.First(v => v.Name == "y").Value;
float z = (float)vals.First(v => v.Name == "z").Value;
float f = (float)vals.First(v => v.Name == "facingRad").Value;
return new Pos(zone, x, y, z, f);
}
}
-37
View File
@@ -1,37 +0,0 @@
using StackExchange.Redis;
namespace Server.World;
public static class SpatialIndex
{
public const int CellSize = 50; // units
public static (int cx, int cy, int cz) Cell(double x, double y, double z) =>
((int)Math.Floor(x / CellSize), (int)Math.Floor(y / CellSize), (int)Math.Floor(z / CellSize));
public static async Task UpdateAsync(IDatabase db, ulong zoneId, ulong charId,
(int cx, int cy, int cz) oldCell, (int cx, int cy, int cz) newCell, TimeSpan ttl)
{
var oldKey = $"z:{{{zoneId}}}:c:{oldCell.cx}:{oldCell.cy}:{oldCell.cz}";
var newKey = $"z:{{{zoneId}}}:c:{newCell.cx}:{newCell.cy}:{newCell.cz}";
var batch = db.CreateBatch();
var tasks = new List<Task>();
if (oldCell != newCell)
tasks.Add(batch.SetRemoveAsync(oldKey, charId));
tasks.Add(batch.SetAddAsync(newKey, charId));
tasks.Add(batch.KeyExpireAsync(newKey, ttl));
batch.Execute();
await Task.WhenAll(tasks);
}
public static IEnumerable<string> NeighborCellKeys(ulong zoneId, (int cx, int cy, int cz) c, int r = 1)
{
for (int dx = -r; dx <= r; dx++)
for (int dy = -r; dy <= r; dy++)
yield return $"z:{{{zoneId}}}:c:{c.cx + dx}:{c.cy + dy}:{c.cz}";
}
}
-4
View File
@@ -11,11 +11,7 @@ public sealed class GameDbContext : DbContext
public DbSet<Account> Accounts => Set<Account>(); public DbSet<Account> Accounts => Set<Account>();
public DbSet<Session> Sessions => Set<Session>(); public DbSet<Session> Sessions => Set<Session>();
public DbSet<Old_Character> Characters => Set<Old_Character>();
public DbSet<Zone> Zones => Set<Zone>(); public DbSet<Zone> Zones => Set<Zone>();
public DbSet<ItemTemplate> ItemTemplates => Set<ItemTemplate>();
public DbSet<InventoryItem> Inventory => Set<InventoryItem>();
public DbSet<EquipmentSlot> Equipment => Set<EquipmentSlot>();
public DbSet<DungeonCharacter> DungeonCharacters => Set<DungeonCharacter>(); public DbSet<DungeonCharacter> DungeonCharacters => Set<DungeonCharacter>();
public DbSet<DungeonCharacterItem> DungeonCharacterItems => Set<DungeonCharacterItem>(); public DbSet<DungeonCharacterItem> DungeonCharacterItems => Set<DungeonCharacterItem>();
public DbSet<DungeonStashItem> DungeonStashItems => Set<DungeonStashItem>(); public DbSet<DungeonStashItem> DungeonStashItems => Set<DungeonStashItem>();
+3 -2
View File
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore; using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data; namespace DataServer.Data;
@@ -20,7 +21,7 @@ public sealed class Account
public DateTime UpdatedAt { get; set; } public DateTime UpdatedAt { get; set; }
public ICollection<Session> Sessions { get; set; } = new List<Session>(); public ICollection<Session> Sessions { get; set; } = new List<Session>();
public ICollection<Old_Character> Characters { get; set; } = new List<Old_Character>(); public ICollection<DungeonCharacter> Characters { get; set; } = new List<DungeonCharacter>();
// Helper methods // Helper methods
public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin; public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin;
-156
View File
@@ -1,156 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DataServer.Data;
namespace DataServer.Data.Entities;
/// <summary>
/// Derived stats calculator - used at runtime
/// </summary>
public static class CharacterStats
{
public static int GetMaxHealth(Character c) => 50 + (c.Endurance * 10);
public static int GetMaxMana(Character c) => 20 + (c.Wisdom * 8);
public static int GetMaxStamina(Character c) => 50 + (c.Endurance * 5);
public static float GetXpBonus(Character c) => 1.0f + (c.Wisdom * 0.02f);
public static float GetMoveSpeed(Character c) => 100f + (c.Dexterity * 2f);
public static float GetAttackSpeed(Character c) => 1.0f + (c.Dexterity * 0.02f);
public static float GetRegenRate(Character c) => 1.0f + (c.Endurance * 0.1f);
/// <summary>
/// Calculate combat stats including equipment bonuses
/// </summary>
public static CharacterCombatStats GetCombatStats(Character c, List<ItemDefinition>? equippedItems = null)
{
var stats = new CharacterCombatStats
{
Strength = c.Strength,
Intelligence = c.Intelligence,
Wisdom = c.Wisdom,
Endurance = c.Endurance,
Dexterity = c.Dexterity
};
if (equippedItems != null)
{
foreach (var item in equippedItems)
{
stats.Strength += item.BonusStrength;
stats.Intelligence += item.BonusIntelligence;
stats.Wisdom += item.BonusWisdom;
stats.Endurance += item.BonusEndurance;
stats.Dexterity += item.BonusDexterity;
stats.BonusHealth += item.BonusHealth;
stats.BonusMana += item.BonusMana;
stats.Armor += item.Armor;
stats.MagicResist += item.MagicResist;
}
}
stats.MaxHealth = 50 + (stats.Endurance * 10) + stats.BonusHealth;
stats.MaxMana = 20 + (stats.Wisdom * 8) + stats.BonusMana;
stats.MaxStamina = 50 + (stats.Endurance * 5);
stats.MoveSpeed = 100f + (stats.Dexterity * 2f);
stats.AttackSpeed = 1.0f + (stats.Dexterity * 0.02f);
stats.RegenRate = 1.0f + (stats.Endurance * 0.1f);
stats.PhysicalDamageMultiplier = 1.0f + (stats.Strength * 0.05f);
stats.SpellDamageMultiplier = 1.0f + (stats.Intelligence * 0.05f);
stats.XpBonus = 1.0f + (stats.Wisdom * 0.02f);
return stats;
}
}
public class CharacterCombatStats
{
public int Strength { get; set; }
public int Intelligence { get; set; }
public int Wisdom { get; set; }
public int Endurance { get; set; }
public int Dexterity { get; set; }
public int MaxHealth { get; set; }
public int MaxMana { get; set; }
public int MaxStamina { get; set; }
public int BonusHealth { get; set; }
public int BonusMana { get; set; }
public int Armor { get; set; }
public int MagicResist { get; set; }
public float MoveSpeed { get; set; }
public float AttackSpeed { get; set; }
public float RegenRate { get; set; }
public float PhysicalDamageMultiplier { get; set; }
public float SpellDamageMultiplier { get; set; }
public float XpBonus { get; set; }
}
/// <summary>
/// Persistent player character with stats and equipment
/// </summary>
[Table("characters")]
public class Character
{
[Key]
public ulong Id { get; set; }
[Required]
public ulong AccountId { get; set; }
[Required]
[MaxLength(32)]
public string Name { get; set; } = "";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime LastPlayedAt { get; set; } = DateTime.UtcNow;
// Progression
public int Level { get; set; } = 1;
public long Experience { get; set; } = 0;
public int UnspentStatPoints { get; set; } = 5; // Start with 5 points
// Core Stats (5 points per level to distribute)
public int Strength { get; set; } = 1; // Physical damage, heavy equipment
public int Intelligence { get; set; } = 1; // Spell damage, magical equipment
public int Wisdom { get; set; } = 1; // Max mana, XP bonus, spell learning
public int Endurance { get; set; } = 1; // Max HP, max stamina, regen rate
public int Dexterity { get; set; } = 1; // Move speed, attack speed, light equipment
// Derived stats (calculated from base stats)
[NotMapped] public int MaxHealth => 50 + (Endurance * 10);
[NotMapped] public int MaxMana => 20 + (Wisdom * 8);
[NotMapped] public int MaxStamina => 50 + (Endurance * 5);
[NotMapped] public float XpBonus => 1.0f + (Wisdom * 0.02f); // 2% per WIS
[NotMapped] public float MoveSpeed => 100f + (Dexterity * 2f);
[NotMapped] public float AttackSpeed => 1.0f + (Dexterity * 0.02f);
[NotMapped] public float RegenRate => 1.0f + (Endurance * 0.1f); // HP/Mana/Stamina regen multiplier
// Current state (saved on logout/death)
public int CurrentHealth { get; set; } = 50;
public int CurrentMana { get; set; } = 20;
// Equipment slots (ItemId references, null = empty)
public ulong? EquippedWeapon { get; set; }
public ulong? EquippedOffhand { get; set; }
public ulong? EquippedHead { get; set; }
public ulong? EquippedChest { get; set; }
public ulong? EquippedLegs { get; set; }
public ulong? EquippedBoots { get; set; }
public ulong? EquippedGloves { get; set; }
public ulong? EquippedAccessory { get; set; }
// Lifetime stats
public int TotalKills { get; set; }
public int TotalDeaths { get; set; }
public int PlayersKilled { get; set; }
public int DungeonsCompleted { get; set; }
public int BossesKilled { get; set; }
// Soft delete
public bool IsDeleted { get; set; } = false;
// Navigation
public virtual Account? Account { get; set; }
public virtual ICollection<CharacterItem> Inventory { get; set; } = new List<CharacterItem>();
public virtual ICollection<StashItem> Stash { get; set; } = new List<StashItem>();
public virtual ICollection<LearnedSpell> LearnedSpells { get; set; } = new List<LearnedSpell>();
}
+2 -2
View File
@@ -59,7 +59,7 @@ public class DungeonVisit
// Navigation // Navigation
public virtual DungeonInstance? Dungeon { get; set; } public virtual DungeonInstance? Dungeon { get; set; }
public virtual Character? Character { get; set; } //public virtual Character? Character { get; set; }
} }
@@ -103,7 +103,7 @@ public class LootTableEntry
// Navigation // Navigation
public virtual LootTable? LootTable { get; set; } public virtual LootTable? LootTable { get; set; }
public virtual ItemDefinition? ItemDefinition { get; set; } //public virtual ItemDefinition? ItemDefinition { get; set; }
} }
// Enums // Enums
-34
View File
@@ -1,34 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data;
public sealed class EquipmentSlot
{
public ulong Id { get; set; }
public ulong CharacterId { get; set; }
public byte SlotCode { get; set; } // 1=head,2=chest,...
public ulong ItemTemplateId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Old_Character? Old_Character { get; set; }
public ItemTemplate? ItemTemplate { get; set; }
}
public sealed class EquipmentSlotConfig : IEntityTypeConfiguration<EquipmentSlot>
{
public void Configure(EntityTypeBuilder<EquipmentSlot> e)
{
e.ToTable("equipment");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedOnAdd();
e.HasIndex(x => new { x.CharacterId, x.SlotCode }).IsUnique();
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade);
e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict);
}
}
-36
View File
@@ -1,36 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data;
public sealed class InventoryItem
{
public ulong Id { get; set; }
public ulong CharacterId { get; set; }
public uint SlotIndex { get; set; }
public ulong ItemTemplateId { get; set; }
public uint Quantity { get; set; } = 1;
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Old_Character? Old_Character { get; set; }
public ItemTemplate? ItemTemplate { get; set; }
}
public sealed class InventoryItemConfig : IEntityTypeConfiguration<InventoryItem>
{
public void Configure(EntityTypeBuilder<InventoryItem> e)
{
e.ToTable("inventories");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedOnAdd();
e.HasIndex(x => new { x.CharacterId, x.SlotIndex }).IsUnique();
e.HasIndex(x => x.CharacterId);
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade);
e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict);
}
}
-33
View File
@@ -1,33 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data;
public sealed class ItemTemplate
{
public ulong Id { get; set; }
public string Name { get; set; } = "";
public byte ItemType { get; set; } = 1;
public byte Rarity { get; set; } = 1;
public uint MaxStack { get; set; } = 1;
public uint Weight { get; set; } = 0;
public string? StatsJson { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
public sealed class ItemTemplateConfig : IEntityTypeConfiguration<ItemTemplate>
{
public void Configure(EntityTypeBuilder<ItemTemplate> e)
{
e.ToTable("item_templates");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedOnAdd();
e.Property(x => x.Name).HasMaxLength(64).IsRequired();
e.HasIndex(x => x.Name).IsUnique();
e.Property(x => x.StatsJson).HasColumnType("json");
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
}
}
-185
View File
@@ -1,185 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using DataServer.Data.Enums;
namespace DataServer.Data.Entities;
/// <summary>
/// Item template/definition - what an item IS
/// </summary>
[Table("item_definitions")]
public class ItemDefinition
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(64)]
public string Name { get; set; } = "";
[MaxLength(256)]
public string Description { get; set; } = "";
public ItemType Type { get; set; }
public ItemRarity Rarity { get; set; } = ItemRarity.Common;
public EquipmentSlot? EquipSlot { get; set; } // Null if not equippable
// Stat requirements to equip/use
public int RequiredStrength { get; set; } = 0;
public int RequiredIntelligence { get; set; } = 0;
public int RequiredWisdom { get; set; } = 0;
public int RequiredDexterity { get; set; } = 0;
public int RequiredLevel { get; set; } = 1;
// Stat bonuses when equipped
public int BonusStrength { get; set; } = 0;
public int BonusIntelligence { get; set; } = 0;
public int BonusWisdom { get; set; } = 0;
public int BonusEndurance { get; set; } = 0;
public int BonusDexterity { get; set; } = 0;
public int BonusHealth { get; set; } = 0;
public int BonusMana { get; set; } = 0;
// Weapon stats
public int MinDamage { get; set; } = 0;
public int MaxDamage { get; set; } = 0;
public float AttackRange { get; set; } = 0; // 0 = melee
public DamageType DamageType { get; set; } = DamageType.Physical;
// Armor stats
public int Armor { get; set; } = 0;
public int MagicResist { get; set; } = 0;
// Consumable effects
public int HealAmount { get; set; } = 0;
public int ManaRestore { get; set; } = 0;
public int StaminaRestore { get; set; } = 0;
// Special
public bool IsTeleportScroll { get; set; } = false;
public int? TeachesSpellId { get; set; } // For spell tomes
// Stacking
public bool Stackable { get; set; } = false;
public int MaxStack { get; set; } = 1;
// Visuals
public int SpriteId { get; set; } = 0;
public bool IsEnabled { get; set; } = true;
}
/// <summary>
/// Actual item instance owned by a character (inventory or equipped)
/// </summary>
[Table("character_items")]
public class CharacterItem
{
[Key]
public ulong Id { get; set; }
public ulong CharacterId { get; set; }
public int ItemDefinitionId { get; set; }
public int Quantity { get; set; } = 1;
public int SlotIndex { get; set; } // Inventory position (0-29 for example)
public DateTime AcquiredAt { get; set; } = DateTime.UtcNow;
// Navigation
public virtual Character? Character { get; set; }
public virtual ItemDefinition? Definition { get; set; }
}
/// <summary>
/// Items stored in character's stash (safe storage in hub)
/// </summary>
[Table("stash_items")]
public class StashItem
{
[Key]
public ulong Id { get; set; }
public ulong CharacterId { get; set; }
public int ItemDefinitionId { get; set; }
public int Quantity { get; set; } = 1;
public int SlotIndex { get; set; }
public DateTime StoredAt { get; set; } = DateTime.UtcNow;
// Navigation
public virtual Character? Character { get; set; }
public virtual ItemDefinition? Definition { get; set; }
}
/// <summary>
/// Spell definition - learnable abilities
/// </summary>
[Table("spell_definitions")]
public class SpellDefinition
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(64)]
public string Name { get; set; } = "";
[MaxLength(256)]
public string Description { get; set; } = "";
public SpellType Type { get; set; }
// Requirements
public int RequiredWisdom { get; set; } = 1;
public int RequiredIntelligence { get; set; } = 0;
public int RequiredLevel { get; set; } = 1;
// Costs
public int ManaCost { get; set; } = 10;
public float Cooldown { get; set; } = 1.0f; // Seconds
// Effects
public int BaseDamage { get; set; } = 0; // Scales with INT
public int BaseHealing { get; set; } = 0; // Scales with WIS
public float Range { get; set; } = 100f;
public float AreaOfEffect { get; set; } = 0; // 0 = single target
// Special
public bool IsTeleport { get; set; } = false;
public bool IsShield { get; set; } = false;
public int ShieldAmount { get; set; } = 0;
// Visuals
public int SpriteId { get; set; } = 0;
public string EffectColor { get; set; } = "#ffffff";
public bool IsEnabled { get; set; } = true;
}
/// <summary>
/// Spells a character has learned
/// </summary>
[Table("learned_spells")]
public class LearnedSpell
{
[Key]
public ulong Id { get; set; }
public ulong CharacterId { get; set; }
public int SpellDefinitionId { get; set; }
public DateTime LearnedAt { get; set; } = DateTime.UtcNow;
// Could add spell levels/upgrades later
public int SpellLevel { get; set; } = 1;
// Navigation
public virtual Character? Character { get; set; }
public virtual SpellDefinition? Definition { get; set; }
}
-64
View File
@@ -1,64 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DataServer.Data;
public sealed class Old_Character
{
public ulong Id { get; set; }
public ulong AccountId { get; set; }
public string Name { get; set; } = "";
public uint Level { get; set; } = 1;
public ulong Xp { get; set; } = 0;
public uint StatStrength { get; set; } = 1;
public uint StatDexterity { get; set; } = 1;
public uint StatWisdom { get; set; } = 1;
public uint StatIntelligence { get; set; } = 1;
public uint StatEndurance { get; set; } = 1;
public uint HpCurrent { get; set; } = 10;
public uint HpMax { get; set; } = 10;
public uint MpCurrent { get; set; } = 0;
public uint MpMax { get; set; } = 0;
public uint StaminaCurrent { get; set; } = 0;
public uint StaminaMax { get; set; } = 0;
public ulong ZoneId { get; set; }
public double PosX { get; set; }
public double PosY { get; set; }
public double PosZ { get; set; }
public float FacingDeg { get; set; }
// store as JSON in MySQL 8
public string? AppearanceJson { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Account? Account { get; set; }
public Zone? Zone { get; set; }
}
public sealed class CharacterConfig : IEntityTypeConfiguration<Old_Character>
{
public void Configure(EntityTypeBuilder<Old_Character> e)
{
e.ToTable("characters");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedOnAdd();
e.Property(x => x.Name).HasMaxLength(32).IsRequired();
e.HasIndex(x => x.AccountId).IsUnique(); // 1 character per account (change later if needed)
e.HasIndex(x => x.ZoneId);
e.Property(x => x.AppearanceJson).HasColumnType("json");
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)")
.ValueGeneratedOnAddOrUpdate();
e.HasOne(x => x.Account).WithMany(a => a.Characters).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade);
e.HasOne(x => x.Zone).WithMany().HasForeignKey(x => x.ZoneId).OnDelete(DeleteBehavior.Restrict);
}
}