Delta state system: replace full-push with game.state_delta
After any game action, push a structured GameStateDelta instead of the full GameStateDto to both players and spectators. Full state is preserved for: initial connect (game.ready), reconnect/get_state, spectate ACK, and turn-timer expiry. Server: - GameMessages.cs: add GameStateDeltaPush, GameStateDelta, TileDelta, UnitDelta, PlayerStatsDelta, GameMetaDelta record types - GameEngine.cs: make ToCardDto internal (used by differ) - GameStateDiffer.cs: new file — ComputeDelta (viewer-specific) and ComputeSpectatorDelta; diffs tiles, field units, hands, discards, archs, player stats, and game meta - GameHandlerBase.cs: PushStateToPlayersAsync gains optional prevState param; when provided pushes delta, else falls back to full push - All 10 action handlers: pass prev state to PushStateToPlayersAsync Client: - Game.gd: _state_version tracking, _apply_delta, _merge_unit_delta, request_sync, game.state_delta push handler with auto-resync on gap - in_game_settings.gd + InGameSettings.tscn: Request Sync button Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -0,0 +1,366 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// Computes a <see cref="GameStateDelta"/> from two <see cref="GameState"/> snapshots.
|
||||
/// Used to send only changed data after each game action instead of the full state.
|
||||
/// </summary>
|
||||
internal static class GameStateDiffer
|
||||
{
|
||||
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Compute a viewer-specific delta (own hand visible; opponent hand = count only).
|
||||
/// </summary>
|
||||
public static GameStateDelta ComputeDelta(GameState prev, GameState next, string viewerAccountId)
|
||||
{
|
||||
var changedTiles = DiffTiles(prev, next);
|
||||
var (addedUnits, removedIds, changed) = DiffAllFieldUnits(prev, next);
|
||||
|
||||
// Viewer's zones
|
||||
prev.Players.TryGetValue(viewerAccountId, out var prevViewer);
|
||||
next.Players.TryGetValue(viewerAccountId, out var nextViewer);
|
||||
|
||||
List<CardInstanceDto>? handAdded = null;
|
||||
List<string>? handRemovedIds = null;
|
||||
List<CardInstanceDto>? discardAdded = null;
|
||||
|
||||
if (prevViewer != null && nextViewer != null)
|
||||
{
|
||||
var prevHandIds = new HashSet<string>(prevViewer.Hand.Select(c => c.InstanceId));
|
||||
var nextHandIds = new HashSet<string>(nextViewer.Hand.Select(c => c.InstanceId));
|
||||
|
||||
var added = nextHandIds.Except(prevHandIds).ToHashSet();
|
||||
if (added.Count > 0)
|
||||
handAdded = nextViewer.Hand
|
||||
.Where(c => added.Contains(c.InstanceId))
|
||||
.Select(GameEngine.ToCardDto)
|
||||
.ToList();
|
||||
|
||||
var removed = prevHandIds.Except(nextHandIds).ToList();
|
||||
if (removed.Count > 0)
|
||||
handRemovedIds = removed;
|
||||
|
||||
// Discard: only appended; emit new tail entries
|
||||
if (nextViewer.Discard.Count > prevViewer.Discard.Count)
|
||||
discardAdded = nextViewer.Discard
|
||||
.Skip(prevViewer.Discard.Count)
|
||||
.Select(GameEngine.ToCardDto)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// Opponent's counts
|
||||
var prevOpp = prev.Players.Values.FirstOrDefault(p => p.AccountId != viewerAccountId);
|
||||
var nextOpp = next.Players.Values.FirstOrDefault(p => p.AccountId != viewerAccountId);
|
||||
|
||||
int? oppHandCount = null;
|
||||
int? oppDeckCount = null;
|
||||
|
||||
if (prevOpp != null && nextOpp != null)
|
||||
{
|
||||
if (prevOpp.Hand.Count != nextOpp.Hand.Count) oppHandCount = nextOpp.Hand.Count;
|
||||
if (prevOpp.Deck.Count != nextOpp.Deck.Count) oppDeckCount = nextOpp.Deck.Count;
|
||||
}
|
||||
|
||||
// ArchSpirits
|
||||
UnitDelta? ownArchDelta = null;
|
||||
UnitDelta? oppArchDelta = null;
|
||||
|
||||
if (prevViewer?.ArchSpirit != null && nextViewer?.ArchSpirit != null)
|
||||
ownArchDelta = DiffUnit(prevViewer.ArchSpirit, nextViewer.ArchSpirit);
|
||||
if (prevOpp?.ArchSpirit != null && nextOpp?.ArchSpirit != null)
|
||||
oppArchDelta = DiffUnit(prevOpp.ArchSpirit, nextOpp.ArchSpirit);
|
||||
|
||||
// Player stats
|
||||
PlayerStatsDelta? ownStats = null;
|
||||
PlayerStatsDelta? oppStats = null;
|
||||
|
||||
if (prevViewer != null && nextViewer != null)
|
||||
ownStats = DiffPlayerStats(prevViewer, nextViewer);
|
||||
if (prevOpp != null && nextOpp != null)
|
||||
oppStats = DiffPlayerStats(prevOpp, nextOpp);
|
||||
|
||||
var metaDelta = DiffMeta(prev, next);
|
||||
|
||||
return new GameStateDelta(
|
||||
StateVersion : next.NextActionSequence,
|
||||
ChangedTiles : changedTiles,
|
||||
AddedUnits : addedUnits,
|
||||
RemovedUnitIds : removedIds,
|
||||
ChangedUnits : changed,
|
||||
HandAdded : handAdded,
|
||||
HandRemovedIds : handRemovedIds,
|
||||
DiscardAdded : discardAdded,
|
||||
OpponentHandCount : oppHandCount,
|
||||
OpponentDeckCount : oppDeckCount,
|
||||
OwnArchSpiritDelta : ownArchDelta,
|
||||
OpponentArchSpiritDelta : oppArchDelta,
|
||||
OwnStatsDelta : ownStats,
|
||||
OpponentStatsDelta : oppStats,
|
||||
MetaDelta : metaDelta);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compute a spectator delta: tile/unit/archspirit/meta changes visible to all;
|
||||
/// hand card details suppressed. P1 mapped to "own", P2 to "opponent" in the result.
|
||||
/// </summary>
|
||||
public static GameStateDelta ComputeSpectatorDelta(GameState prev, GameState next)
|
||||
{
|
||||
var changedTiles = DiffTiles(prev, next);
|
||||
var (addedUnits, removedIds, changed) = DiffAllFieldUnits(prev, next);
|
||||
|
||||
// Map p1 → "own", p2 → "opponent" for archspirit and stats fields
|
||||
prev.Players.TryGetValue(prev.PlayerOneAccountId, out var prevP1);
|
||||
next.Players.TryGetValue(next.PlayerOneAccountId, out var nextP1);
|
||||
var prevP2 = prev.Players.Values.FirstOrDefault(p => p.AccountId != prev.PlayerOneAccountId);
|
||||
var nextP2 = next.Players.Values.FirstOrDefault(p => p.AccountId != next.PlayerOneAccountId);
|
||||
|
||||
UnitDelta? ownArchDelta = null;
|
||||
UnitDelta? oppArchDelta = null;
|
||||
|
||||
if (prevP1?.ArchSpirit != null && nextP1?.ArchSpirit != null)
|
||||
ownArchDelta = DiffUnit(prevP1.ArchSpirit, nextP1.ArchSpirit);
|
||||
if (prevP2?.ArchSpirit != null && nextP2?.ArchSpirit != null)
|
||||
oppArchDelta = DiffUnit(prevP2.ArchSpirit, nextP2.ArchSpirit);
|
||||
|
||||
PlayerStatsDelta? ownStats = null;
|
||||
PlayerStatsDelta? oppStats = null;
|
||||
|
||||
if (prevP1 != null && nextP1 != null) ownStats = DiffPlayerStats(prevP1, nextP1);
|
||||
if (prevP2 != null && nextP2 != null) oppStats = DiffPlayerStats(prevP2, nextP2);
|
||||
|
||||
var metaDelta = DiffMeta(prev, next);
|
||||
|
||||
return new GameStateDelta(
|
||||
StateVersion : next.NextActionSequence,
|
||||
ChangedTiles : changedTiles,
|
||||
AddedUnits : addedUnits,
|
||||
RemovedUnitIds : removedIds,
|
||||
ChangedUnits : changed,
|
||||
HandAdded : null,
|
||||
HandRemovedIds : null,
|
||||
DiscardAdded : null,
|
||||
OpponentHandCount : null,
|
||||
OpponentDeckCount : null,
|
||||
OwnArchSpiritDelta : ownArchDelta,
|
||||
OpponentArchSpiritDelta : oppArchDelta,
|
||||
OwnStatsDelta : ownStats,
|
||||
OpponentStatsDelta : oppStats,
|
||||
MetaDelta : metaDelta);
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static List<TileDelta>? DiffTiles(GameState prev, GameState next)
|
||||
{
|
||||
if (prev.Board == null || next.Board == null) return null;
|
||||
|
||||
List<TileDelta>? result = null;
|
||||
|
||||
foreach (var nextTile in next.Board.Tiles.Values)
|
||||
{
|
||||
var key = nextTile.Coord.ToKey();
|
||||
|
||||
if (!prev.Board.Tiles.TryGetValue(key, out var prevTile))
|
||||
{
|
||||
// New tile (board resize edge case — emit all fields)
|
||||
result ??= new List<TileDelta>();
|
||||
result.Add(new TileDelta(
|
||||
X : nextTile.Coord.X,
|
||||
Y : nextTile.Coord.Y,
|
||||
Base1 : nextTile.Base1.ToString(),
|
||||
Base2 : nextTile.Base2.ToString(),
|
||||
ResolvedAffinity : AffinitySystem.Resolve(nextTile.Base1, nextTile.Base2).ToString(),
|
||||
OccupantId : nextTile.OccupantId,
|
||||
OccupantCleared : false,
|
||||
OccupantOwner : nextTile.OccupantOwner,
|
||||
RuinId : nextTile.RuinId,
|
||||
RuinCleared : false,
|
||||
RuinOwner : nextTile.RuinOwner));
|
||||
continue;
|
||||
}
|
||||
|
||||
bool base1Changed = prevTile.Base1 != nextTile.Base1;
|
||||
bool base2Changed = prevTile.Base2 != nextTile.Base2;
|
||||
bool occupantChanged = prevTile.OccupantId != nextTile.OccupantId;
|
||||
bool occOwnerChanged = prevTile.OccupantOwner != nextTile.OccupantOwner;
|
||||
bool ruinChanged = prevTile.RuinId != nextTile.RuinId;
|
||||
bool ruinOwnerChanged = prevTile.RuinOwner != nextTile.RuinOwner;
|
||||
|
||||
if (!base1Changed && !base2Changed && !occupantChanged &&
|
||||
!occOwnerChanged && !ruinChanged && !ruinOwnerChanged)
|
||||
continue;
|
||||
|
||||
result ??= new List<TileDelta>();
|
||||
result.Add(new TileDelta(
|
||||
X : nextTile.Coord.X,
|
||||
Y : nextTile.Coord.Y,
|
||||
Base1 : base1Changed ? nextTile.Base1.ToString() : null,
|
||||
Base2 : base2Changed ? nextTile.Base2.ToString() : null,
|
||||
ResolvedAffinity : (base1Changed || base2Changed)
|
||||
? AffinitySystem.Resolve(nextTile.Base1, nextTile.Base2).ToString()
|
||||
: null,
|
||||
OccupantId : occupantChanged && nextTile.OccupantId != null ? nextTile.OccupantId : null,
|
||||
OccupantCleared : occupantChanged && nextTile.OccupantId == null,
|
||||
OccupantOwner : occOwnerChanged ? nextTile.OccupantOwner : null,
|
||||
RuinId : ruinChanged && nextTile.RuinId != null ? nextTile.RuinId : null,
|
||||
RuinCleared : ruinChanged && nextTile.RuinId == null,
|
||||
RuinOwner : ruinOwnerChanged ? nextTile.RuinOwner : null));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static (List<CardInstanceDto>? added, List<string>? removed, List<UnitDelta>? changed)
|
||||
DiffAllFieldUnits(GameState prev, GameState next)
|
||||
{
|
||||
var prevById = new Dictionary<string, CardInstance>();
|
||||
var nextById = new Dictionary<string, CardInstance>();
|
||||
|
||||
foreach (var ps in prev.Players.Values)
|
||||
foreach (var u in ps.Field)
|
||||
prevById[u.InstanceId] = u;
|
||||
|
||||
foreach (var ps in next.Players.Values)
|
||||
foreach (var u in ps.Field)
|
||||
nextById[u.InstanceId] = u;
|
||||
|
||||
List<CardInstanceDto>? added = null;
|
||||
List<string>? removed = null;
|
||||
List<UnitDelta>? changed = null;
|
||||
|
||||
foreach (var (id, nextUnit) in nextById)
|
||||
{
|
||||
if (!prevById.TryGetValue(id, out var prevUnit))
|
||||
{
|
||||
added ??= new List<CardInstanceDto>();
|
||||
added.Add(GameEngine.ToCardDto(nextUnit));
|
||||
}
|
||||
else
|
||||
{
|
||||
var delta = DiffUnit(prevUnit, nextUnit);
|
||||
if (delta != null)
|
||||
{
|
||||
changed ??= new List<UnitDelta>();
|
||||
changed.Add(delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var id in prevById.Keys)
|
||||
{
|
||||
if (!nextById.ContainsKey(id))
|
||||
{
|
||||
removed ??= new List<string>();
|
||||
removed.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
return (added, removed, changed);
|
||||
}
|
||||
|
||||
private static UnitDelta? DiffUnit(CardInstance prevC, CardInstance nextC)
|
||||
{
|
||||
var prevFc = prevC as FieldCard;
|
||||
var nextFc = nextC as FieldCard;
|
||||
|
||||
bool abilityUsesChanged = !AbilityUsesEqual(prevC.AbilityUsesThisTurn, nextC.AbilityUsesThisTurn);
|
||||
|
||||
bool anyChange =
|
||||
prevC.CurrentHealth != nextC.CurrentHealth ||
|
||||
prevC.MaxHealth != nextC.MaxHealth ||
|
||||
prevC.CurrentDefense != nextC.CurrentDefense ||
|
||||
prevC.MaxDefense != nextC.MaxDefense ||
|
||||
prevC.Damage != nextC.Damage ||
|
||||
prevC.IsExhausted != nextC.IsExhausted ||
|
||||
prevC.CanMove != nextC.CanMove ||
|
||||
prevC.CanAttack != nextC.CanAttack ||
|
||||
prevC.CanBeAttacked != nextC.CanBeAttacked ||
|
||||
prevC.CanUseAbility != nextC.CanUseAbility ||
|
||||
(prevFc?.CurrentMp ?? 0) != (nextFc?.CurrentMp ?? 0) ||
|
||||
prevC.MaxMp != nextC.MaxMp ||
|
||||
prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ||
|
||||
prevFc?.Position != nextFc?.Position ||
|
||||
prevC.EffectsJson != nextC.EffectsJson ||
|
||||
prevC.AbilitiesJson != nextC.AbilitiesJson ||
|
||||
abilityUsesChanged;
|
||||
|
||||
if (!anyChange) return null;
|
||||
|
||||
CoordDto? positionDelta = null;
|
||||
if (prevFc?.Position != nextFc?.Position && nextFc?.Position is { } pos)
|
||||
positionDelta = new CoordDto(pos.X, pos.Y);
|
||||
|
||||
string? abilityUsesJson = abilityUsesChanged && nextC.AbilityUsesThisTurn != null
|
||||
? JsonSerializer.Serialize(nextC.AbilityUsesThisTurn, _json)
|
||||
: null;
|
||||
|
||||
return new UnitDelta(
|
||||
InstanceId : nextC.InstanceId,
|
||||
CurrentHealth : prevC.CurrentHealth != nextC.CurrentHealth ? nextC.CurrentHealth : null,
|
||||
MaxHealth : prevC.MaxHealth != nextC.MaxHealth ? nextC.MaxHealth : null,
|
||||
CurrentDefense : prevC.CurrentDefense != nextC.CurrentDefense ? nextC.CurrentDefense : null,
|
||||
MaxDefense : prevC.MaxDefense != nextC.MaxDefense ? nextC.MaxDefense : null,
|
||||
Damage : prevC.Damage != nextC.Damage ? nextC.Damage : null,
|
||||
IsExhausted : prevC.IsExhausted != nextC.IsExhausted ? nextC.IsExhausted : null,
|
||||
CanMove : prevC.CanMove != nextC.CanMove ? nextC.CanMove : null,
|
||||
CanAttack : prevC.CanAttack != nextC.CanAttack ? nextC.CanAttack : null,
|
||||
CanBeAttacked : prevC.CanBeAttacked != nextC.CanBeAttacked ? nextC.CanBeAttacked : null,
|
||||
CanUseAbility : prevC.CanUseAbility != nextC.CanUseAbility ? nextC.CanUseAbility : null,
|
||||
CurrentMp : (prevFc?.CurrentMp ?? 0) != (nextFc?.CurrentMp ?? 0) ? nextFc?.CurrentMp : null,
|
||||
MaxMp : prevC.MaxMp != nextC.MaxMp ? nextC.MaxMp : null,
|
||||
ExtraAttacksRemaining : prevC.ExtraAttacksRemaining != nextC.ExtraAttacksRemaining ? nextC.ExtraAttacksRemaining : null,
|
||||
Position : positionDelta,
|
||||
EffectsJson : prevC.EffectsJson != nextC.EffectsJson ? nextC.EffectsJson : null,
|
||||
AbilitiesJson : prevC.AbilitiesJson != nextC.AbilitiesJson ? nextC.AbilitiesJson : null,
|
||||
AbilityUsesJson : abilityUsesJson);
|
||||
}
|
||||
|
||||
private static PlayerStatsDelta? DiffPlayerStats(PlayerState prev, PlayerState next)
|
||||
{
|
||||
bool spChanged = prev.CurrentSp != next.CurrentSp;
|
||||
bool stChanged = prev.CurrentSt != next.CurrentSt;
|
||||
bool deckChanged = prev.Deck.Count != next.Deck.Count;
|
||||
bool handChanged = prev.Hand.Count != next.Hand.Count;
|
||||
bool discardChanged = prev.Discard.Count != next.Discard.Count;
|
||||
|
||||
if (!spChanged && !stChanged && !deckChanged && !handChanged && !discardChanged)
|
||||
return null;
|
||||
|
||||
return new PlayerStatsDelta(
|
||||
CurrentSp : spChanged ? next.CurrentSp : null,
|
||||
CurrentSt : stChanged ? next.CurrentSt : null,
|
||||
DeckCount : deckChanged ? next.Deck.Count : null,
|
||||
HandCount : handChanged ? next.Hand.Count : null,
|
||||
DiscardCount : discardChanged ? next.Discard.Count : null);
|
||||
}
|
||||
|
||||
private static GameMetaDelta? DiffMeta(GameState prev, GameState next)
|
||||
{
|
||||
bool phaseChanged = prev.Phase != next.Phase;
|
||||
bool activeChanged = prev.ActivePlayerAccountId != next.ActivePlayerAccountId;
|
||||
bool turnChanged = prev.TurnNumber != next.TurnNumber;
|
||||
|
||||
if (!phaseChanged && !activeChanged && !turnChanged) return null;
|
||||
|
||||
return new GameMetaDelta(
|
||||
Phase : phaseChanged ? next.Phase.ToString() : null,
|
||||
ActivePlayerAccountId : activeChanged ? next.ActivePlayerAccountId : null,
|
||||
TurnNumber : turnChanged ? next.TurnNumber : null);
|
||||
}
|
||||
|
||||
private static bool AbilityUsesEqual(Dictionary<int, int>? a, Dictionary<int, int>? b)
|
||||
{
|
||||
if (a == null && b == null) return true;
|
||||
if (a == null || b == null) return false;
|
||||
if (a.Count != b.Count) return false;
|
||||
foreach (var (k, v) in a)
|
||||
if (!b.TryGetValue(k, out var bv) || bv != v) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user