Cut over game.state_delta to account-scoped multiplayer schema

This commit is contained in:
Shard
2026-03-27 12:42:57 +00:00
parent f07ea4135a
commit cb024c70e2
5 changed files with 260 additions and 257 deletions
+83 -90
View File
@@ -397,38 +397,27 @@ func _apply_delta(delta: Dictionary) -> void:
break
# 2. Added units (new units entering the field)
var added_units = delta.get("addedUnits")
var added_units = delta.get("unitsAdded")
if added_units is Array:
for unit: Dictionary in added_units:
var owner_id := str(unit.get("ownerId", "")) # not on CardInstanceDto, use position to find by ownerId?
# CardInstanceDto doesn't carry ownerId; find the right player by checking which player
# doesn't already have this unit. We append to the player who owns the tile.
# Fallback: use the unit's position coord to find the tile's occupant owner.
var placed := false
for p: Dictionary in state.get("players", []):
var field: Array = p.get("field", [])
# Check if this player already has the unit (shouldn't happen)
var found := false
for u: Dictionary in field:
if u.get("instanceId", "") == unit.get("instanceId", ""):
found = true
break
if not found and not placed:
# Determine ownership from the tile's occupantOwner matching this player's accountId
var pos: Dictionary = unit.get("position", {})
if not pos.is_empty():
var tile := get_tile(int(pos.get("x", -1)), int(pos.get("y", -1)))
if str(tile.get("occupantOwner", "")).to_lower() == str(p.get("accountId", "")).to_lower():
field.append(unit)
placed = true
# Fallback if we couldn't place via tile: append to active player's field
if not placed:
var my_p := get_my_player()
if not my_p.is_empty():
my_p.get("field", []).append(unit)
for add_entry: Dictionary in added_units:
var owner_id := str(add_entry.get("ownerAccountId", ""))
var unit := add_entry.get("unit", {}) as Dictionary
if unit.is_empty():
continue
var target := _player_by_id(owner_id)
if target.is_empty():
continue
var field: Array = target.get("field", [])
var exists := false
for u: Dictionary in field:
if str(u.get("instanceId", "")) == str(unit.get("instanceId", "")):
exists = true
break
if not exists:
field.append(unit)
# 3. Removed unit IDs
var removed_ids = delta.get("removedUnitIds")
var removed_ids = delta.get("unitsRemoved")
if removed_ids is Array:
for iid: String in removed_ids:
for p: Dictionary in state.get("players", []):
@@ -439,7 +428,7 @@ func _apply_delta(delta: Dictionary) -> void:
break
# 4. Changed units (merge non-null UnitDelta fields)
var changed_units = delta.get("changedUnits")
var changed_units = delta.get("unitsChanged")
if changed_units is Array:
for ud: Dictionary in changed_units:
var iid := str(ud.get("instanceId", ""))
@@ -447,72 +436,76 @@ func _apply_delta(delta: Dictionary) -> void:
if not unit.is_empty():
_merge_unit_delta(unit, ud)
# 5. Hand added / removed (own player only)
var hand_added = delta.get("handAdded")
if hand_added is Array and not hand_added.is_empty():
var my_hand: Array = get_my_player().get("hand", [])
for card: Dictionary in hand_added:
my_hand.append(card)
# 5. Viewer-private zones (own hand/discard only)
var private_delta = delta.get("privateByViewer")
if private_delta is Dictionary and not private_delta.is_empty():
var hand_added = private_delta.get("handAdded")
if hand_added is Array and not hand_added.is_empty():
var my_hand: Array = get_my_player().get("hand", [])
for card: Dictionary in hand_added:
my_hand.append(card)
var hand_removed = delta.get("handRemovedIds")
if hand_removed is Array:
var my_hand: Array = get_my_player().get("hand", [])
for iid: String in hand_removed:
for i in range(my_hand.size() - 1, -1, -1):
if my_hand[i].get("instanceId", "") == iid:
my_hand.remove_at(i)
break
var hand_removed = private_delta.get("handRemovedIds")
if hand_removed is Array:
var my_hand: Array = get_my_player().get("hand", [])
for iid: String in hand_removed:
for i in range(my_hand.size() - 1, -1, -1):
if my_hand[i].get("instanceId", "") == iid:
my_hand.remove_at(i)
break
# 6. Discard added
var discard_added = delta.get("discardAdded")
if discard_added is Array and not discard_added.is_empty():
var my_discard: Array = get_my_player().get("discard", [])
for card: Dictionary in discard_added:
my_discard.append(card)
var discard_added = private_delta.get("discardAdded")
if discard_added is Array and not discard_added.is_empty():
var my_discard: Array = get_my_player().get("discard", [])
for card: Dictionary in discard_added:
my_discard.append(card)
# 7. Opponent hand / deck counts
var opp_hand_count = delta.get("opponentHandCount")
var opp_deck_count = delta.get("opponentDeckCount")
var opp := get_opponent()
if not opp.is_empty():
if opp_hand_count != null: opp["handCount"] = int(opp_hand_count)
if opp_deck_count != null: opp["deckCount"] = int(opp_deck_count)
# 6. Public counts by account
var public_counts = delta.get("publicCountsByAccount")
if public_counts is Dictionary:
for aid_v: Variant in public_counts.keys():
var aid := str(aid_v)
var counts := public_counts.get(aid, {}) as Dictionary
var player := _player_by_id(aid)
if player.is_empty() or counts.is_empty():
continue
if counts.has("handCount") and counts["handCount"] != null: player["handCount"] = int(counts["handCount"])
if counts.has("deckCount") and counts["deckCount"] != null: player["deckCount"] = int(counts["deckCount"])
if counts.has("discardCount") and counts["discardCount"] != null: player["discardCount"] = int(counts["discardCount"])
# 8. ArchSpirits
var own_arch_delta = delta.get("ownArchSpiritDelta")
if own_arch_delta is Dictionary and not own_arch_delta.is_empty():
var my_arch: Dictionary = get_my_player().get("archSpirit", {})
if not my_arch.is_empty():
_merge_unit_delta(my_arch, own_arch_delta)
# 7. ArchSpirit deltas by account
var arch_by_account = delta.get("archSpiritByAccount")
if arch_by_account is Dictionary:
for aid_v: Variant in arch_by_account.keys():
var aid := str(aid_v)
var arch_delta := arch_by_account.get(aid, {}) as Dictionary
if arch_delta.is_empty():
continue
var player := _player_by_id(aid)
if player.is_empty():
continue
var arch: Dictionary = player.get("archSpirit", {})
if not arch.is_empty():
_merge_unit_delta(arch, arch_delta)
var opp_arch_delta = delta.get("opponentArchSpiritDelta")
if opp_arch_delta is Dictionary and not opp_arch_delta.is_empty():
var opp_arch: Dictionary = get_opponent().get("archSpirit", {})
if not opp_arch.is_empty():
_merge_unit_delta(opp_arch, opp_arch_delta)
# 8. Player stats by account
var stats_by_account = delta.get("playerStatsByAccount")
if stats_by_account is Dictionary:
for aid_v: Variant in stats_by_account.keys():
var aid := str(aid_v)
var stats := stats_by_account.get(aid, {}) as Dictionary
if stats.is_empty():
continue
var player := _player_by_id(aid)
if player.is_empty():
continue
if stats.has("currentSp") and stats["currentSp"] != null: player["currentSp"] = int(stats["currentSp"])
if stats.has("currentSt") and stats["currentSt"] != null: player["currentSt"] = int(stats["currentSt"])
if stats.has("deckCount") and stats["deckCount"] != null: player["deckCount"] = int(stats["deckCount"])
if stats.has("handCount") and stats["handCount"] != null: player["handCount"] = int(stats["handCount"])
if stats.has("discardCount") and stats["discardCount"] != null: player["discardCount"] = int(stats["discardCount"])
# 9. Player stats
var own_stats = delta.get("ownStatsDelta")
if own_stats is Dictionary and not own_stats.is_empty():
var my_p := get_my_player()
if not my_p.is_empty():
if own_stats.has("currentSp") and own_stats["currentSp"] != null: my_p["currentSp"] = int(own_stats["currentSp"])
if own_stats.has("currentSt") and own_stats["currentSt"] != null: my_p["currentSt"] = int(own_stats["currentSt"])
if own_stats.has("deckCount") and own_stats["deckCount"] != null: my_p["deckCount"] = int(own_stats["deckCount"])
if own_stats.has("handCount") and own_stats["handCount"] != null: my_p["handCount"] = int(own_stats["handCount"])
if own_stats.has("discardCount") and own_stats["discardCount"] != null: my_p["discardCount"] = int(own_stats["discardCount"])
var opp_stats = delta.get("opponentStatsDelta")
if opp_stats is Dictionary and not opp_stats.is_empty():
var opp_p := get_opponent()
if not opp_p.is_empty():
if opp_stats.has("currentSp") and opp_stats["currentSp"] != null: opp_p["currentSp"] = int(opp_stats["currentSp"])
if opp_stats.has("currentSt") and opp_stats["currentSt"] != null: opp_p["currentSt"] = int(opp_stats["currentSt"])
if opp_stats.has("deckCount") and opp_stats["deckCount"] != null: opp_p["deckCount"] = int(opp_stats["deckCount"])
if opp_stats.has("handCount") and opp_stats["handCount"] != null: opp_p["handCount"] = int(opp_stats["handCount"])
if opp_stats.has("discardCount") and opp_stats["discardCount"] != null: opp_p["discardCount"] = int(opp_stats["discardCount"])
# 10. Meta
# 9. Meta
var meta = delta.get("metaDelta")
if meta is Dictionary and not meta.is_empty():
if meta.has("phase") and meta["phase"] != null: state["phase"] = meta["phase"]
+5
View File
@@ -111,3 +111,8 @@
- [ ] Gameplay:
- [ ] Full timing windows and reaction timing.
- [ ] Mulligan rules.
- [ ] Networking/privacy hardening:
- [ ] Delta identity decoupling: replace client-visible `accountId` usage in game wire payloads with session-scoped `playerRef` identifiers.
- [ ] Server identity map: maintain authoritative `sessionId + playerRef -> accountId` mapping with strict invariants on join/reconnect/resume.
- [ ] Logging/telemetry split: keep internal accountId linkage in server logs only; expose `playerRef` (and display name) in client-visible/debug payloads.
+24 -15
View File
@@ -454,21 +454,16 @@ public sealed record GameStateDeltaPush(GameStateDelta Delta);
/// Own hand is shown in full; opponent hand = count only.
/// </summary>
public sealed record GameStateDelta(
int StateVersion,
IReadOnlyList<TileDelta>? ChangedTiles,
IReadOnlyList<CardInstanceDto>? AddedUnits,
IReadOnlyList<string>? RemovedUnitIds,
IReadOnlyList<UnitDelta>? ChangedUnits,
IReadOnlyList<CardInstanceDto>? HandAdded,
IReadOnlyList<string>? HandRemovedIds,
IReadOnlyList<CardInstanceDto>? DiscardAdded,
int? OpponentHandCount,
int? OpponentDeckCount,
UnitDelta? OwnArchSpiritDelta,
UnitDelta? OpponentArchSpiritDelta,
PlayerStatsDelta? OwnStatsDelta,
PlayerStatsDelta? OpponentStatsDelta,
GameMetaDelta? MetaDelta);
int StateVersion,
IReadOnlyList<TileDelta>? ChangedTiles,
IReadOnlyList<UnitSnapshot>? UnitsAdded,
IReadOnlyList<string>? UnitsRemoved,
IReadOnlyList<UnitDelta>? UnitsChanged,
IReadOnlyDictionary<string, UnitDelta>? ArchSpiritByAccount,
IReadOnlyDictionary<string, PlayerStatsDelta>? PlayerStatsByAccount,
IReadOnlyDictionary<string, PublicCountsDelta>? PublicCountsByAccount,
PrivateViewerDelta? PrivateByViewer,
GameMetaDelta? MetaDelta);
public sealed record TileDelta(
int X,
@@ -483,6 +478,10 @@ public sealed record TileDelta(
bool RuinCleared,
string? RuinOwner);
public sealed record UnitSnapshot(
string OwnerAccountId,
CardInstanceDto Unit);
public sealed record UnitDelta(
string InstanceId,
int? CurrentHealth,
@@ -503,6 +502,16 @@ public sealed record UnitDelta(
string? AbilitiesJson,
string? AbilityUsesJson);
public sealed record PublicCountsDelta(
int? DeckCount,
int? HandCount,
int? DiscardCount);
public sealed record PrivateViewerDelta(
IReadOnlyList<CardInstanceDto>? HandAdded,
IReadOnlyList<string>? HandRemovedIds,
IReadOnlyList<CardInstanceDto>? DiscardAdded);
public sealed record PlayerStatsDelta(
int? CurrentSp,
int? CurrentSt,
+126 -107
View File
@@ -15,23 +15,24 @@ internal static class GameStateDiffer
};
/// <summary>
/// Compute a viewer-specific delta (own hand visible; opponent hand = count only).
/// Compute a viewer-specific delta (private hand/discard only for the viewer;
/// all public data keyed by account ID).
/// </summary>
public static GameStateDelta ComputeDelta(GameState prev, GameState next, string viewerAccountId)
{
var changedTiles = DiffTiles(prev, next);
var (addedUnits, removedIds, changed) = DiffAllFieldUnits(prev, next);
var changedTiles = DiffTiles(prev, next);
var (unitsAdded, unitsRemoved, unitsChanged) = 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;
PrivateViewerDelta? privateByViewer = null;
if (prevViewer != null && nextViewer != null)
{
List<CardInstanceDto>? handAdded = null;
List<string>? handRemovedIds = null;
List<CardInstanceDto>? discardAdded = null;
var prevHandIds = new HashSet<string>(prevViewer.Hand.Select(c => c.InstanceId));
var nextHandIds = new HashSet<string>(nextViewer.Hand.Select(c => c.InstanceId));
@@ -46,112 +47,58 @@ internal static class GameStateDiffer
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();
if (handAdded != null || handRemovedIds != null || discardAdded != null)
privateByViewer = new PrivateViewerDelta(handAdded, handRemovedIds, discardAdded);
}
// 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 archByAccount = DiffArchByAccount(prev, next);
var statsByAccount = DiffStatsByAccount(prev, next);
var countsByAccount = DiffPublicCountsByAccount(prev, next, viewerAccountId);
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);
StateVersion: next.NextActionSequence,
ChangedTiles: changedTiles,
UnitsAdded: unitsAdded,
UnitsRemoved: unitsRemoved,
UnitsChanged: unitsChanged,
ArchSpiritByAccount: archByAccount,
PlayerStatsByAccount: statsByAccount,
PublicCountsByAccount: countsByAccount,
PrivateByViewer: privateByViewer,
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.
/// Compute spectator delta (public data only).
/// </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 changedTiles = DiffTiles(prev, next);
var (unitsAdded, unitsRemoved, unitsChanged) = DiffAllFieldUnits(prev, next);
var archByAccount = DiffArchByAccount(prev, next);
var statsByAccount = DiffStatsByAccount(prev, next);
var countsByAccount = DiffPublicCountsByAccount(prev, next, null);
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);
StateVersion: next.NextActionSequence,
ChangedTiles: changedTiles,
UnitsAdded: unitsAdded,
UnitsRemoved: unitsRemoved,
UnitsChanged: unitsChanged,
ArchSpiritByAccount: archByAccount,
PlayerStatsByAccount: statsByAccount,
PublicCountsByAccount: countsByAccount,
PrivateByViewer: null,
MetaDelta: metaDelta);
}
// ── Helpers ───────────────────────────────────────────────────────────────
@@ -216,34 +163,34 @@ internal static class GameStateDiffer
return result;
}
private static (List<CardInstanceDto>? added, List<string>? removed, List<UnitDelta>? changed)
private static (List<UnitSnapshot>? added, List<string>? removed, List<UnitDelta>? changed)
DiffAllFieldUnits(GameState prev, GameState next)
{
var prevById = new Dictionary<string, CardInstance>();
var nextById = new Dictionary<string, CardInstance>();
var prevById = new Dictionary<string, (CardInstance unit, string ownerId)>();
var nextById = new Dictionary<string, (CardInstance unit, string ownerId)>();
foreach (var ps in prev.Players.Values)
foreach (var u in ps.Field)
prevById[u.InstanceId] = u;
prevById[u.InstanceId] = (u, ps.AccountId);
foreach (var ps in next.Players.Values)
foreach (var u in ps.Field)
nextById[u.InstanceId] = u;
nextById[u.InstanceId] = (u, ps.AccountId);
List<CardInstanceDto>? added = null;
List<string>? removed = null;
List<UnitDelta>? changed = null;
List<UnitSnapshot>? added = null;
List<string>? removed = null;
List<UnitDelta>? changed = null;
foreach (var (id, nextUnit) in nextById)
foreach (var (id, nextEntry) in nextById)
{
if (!prevById.TryGetValue(id, out var prevUnit))
if (!prevById.TryGetValue(id, out var prevEntry))
{
added ??= new List<CardInstanceDto>();
added.Add(GameEngine.ToCardDto(nextUnit));
added ??= new List<UnitSnapshot>();
added.Add(new UnitSnapshot(nextEntry.ownerId, GameEngine.ToCardDto(nextEntry.unit)));
}
else
{
var delta = DiffUnit(prevUnit, nextUnit);
var delta = DiffUnit(prevEntry.unit, nextEntry.unit);
if (delta != null)
{
changed ??= new List<UnitDelta>();
@@ -340,6 +287,78 @@ internal static class GameStateDiffer
DiscardCount : discardChanged ? next.Discard.Count : null);
}
private static Dictionary<string, UnitDelta>? DiffArchByAccount(GameState prev, GameState next)
{
Dictionary<string, UnitDelta>? result = null;
foreach (var (accountId, nextPlayer) in next.Players)
{
if (!prev.Players.TryGetValue(accountId, out var prevPlayer))
continue;
if (prevPlayer.ArchSpirit != null && nextPlayer.ArchSpirit != null)
{
var d = DiffUnit(prevPlayer.ArchSpirit, nextPlayer.ArchSpirit);
if (d != null)
{
result ??= new Dictionary<string, UnitDelta>();
result[accountId] = d;
}
}
}
return result;
}
private static Dictionary<string, PlayerStatsDelta>? DiffStatsByAccount(GameState prev, GameState next)
{
Dictionary<string, PlayerStatsDelta>? result = null;
foreach (var (accountId, nextPlayer) in next.Players)
{
if (!prev.Players.TryGetValue(accountId, out var prevPlayer))
continue;
var d = DiffPlayerStats(prevPlayer, nextPlayer);
if (d != null)
{
result ??= new Dictionary<string, PlayerStatsDelta>();
result[accountId] = d;
}
}
return result;
}
private static Dictionary<string, PublicCountsDelta>? DiffPublicCountsByAccount(
GameState prev,
GameState next,
string? viewerAccountId)
{
Dictionary<string, PublicCountsDelta>? result = null;
foreach (var (accountId, nextPlayer) in next.Players)
{
if (viewerAccountId != null && accountId == viewerAccountId)
continue;
if (!prev.Players.TryGetValue(accountId, out var prevPlayer))
continue;
var deck = prevPlayer.Deck.Count != nextPlayer.Deck.Count ? nextPlayer.Deck.Count : (int?)null;
var hand = prevPlayer.Hand.Count != nextPlayer.Hand.Count ? nextPlayer.Hand.Count : (int?)null;
var discard = prevPlayer.Discard.Count != nextPlayer.Discard.Count ? nextPlayer.Discard.Count : (int?)null;
if (deck != null || hand != null || discard != null)
{
result ??= new Dictionary<string, PublicCountsDelta>();
result[accountId] = new PublicCountsDelta(deck, hand, discard);
}
}
return result;
}
private static GameMetaDelta? DiffMeta(GameState prev, GameState next)
{
bool phaseChanged = prev.Phase != next.Phase;
+22 -45
View File
@@ -155,53 +155,35 @@ internal abstract class GameHandlerBase
CancellationToken ct,
string? prevStateJson = null)
{
var p1Id = session.PlayerOneAccountId.ToString();
var p2Id = session.PlayerTwoAccountId.ToString();
if (prevStateJson != null)
{
var prevState = GameEngine.Deserialize(prevStateJson);
var allIds = GetAllPlayerIds(session);
var d1 = GameStateDiffer.ComputeDelta(prevState, state, p1Id);
var d2 = GameStateDiffer.ComputeDelta(prevState, state, p2Id);
// Safety fallback: if the differ produces an empty delta (all content fields null),
// the client would advance its stateVersion but see no visual changes. Fall back to
// a full state_update so clients always reflect the correct post-action state.
// This guards against any unknown runtime edge case where ComputeDelta returns nothing.
static bool IsEmpty(GameStateDelta d) =>
d.MetaDelta == null &&
d.ChangedTiles == null &&
d.AddedUnits == null &&
d.RemovedUnitIds == null &&
d.ChangedUnits == null &&
d.HandAdded == null &&
d.HandRemovedIds == null &&
d.DiscardAdded == null &&
d.OpponentHandCount == null &&
d.OpponentDeckCount == null &&
d.OwnArchSpiritDelta == null &&
d.OpponentArchSpiritDelta == null &&
d.OwnStatsDelta == null &&
d.OpponentStatsDelta == null;
d.MetaDelta == null &&
d.ChangedTiles == null &&
d.UnitsAdded == null &&
d.UnitsRemoved == null &&
d.UnitsChanged == null &&
d.ArchSpiritByAccount == null &&
d.PlayerStatsByAccount == null &&
d.PublicCountsByAccount == null &&
d.PrivateByViewer == null;
var deltas = allIds.ToDictionary(
pid => pid,
pid => GameStateDiffer.ComputeDelta(prevState, state, pid));
var tasks = new List<Task>();
// Additional players (seats 3+): always receive full-state updates
// (the delta system only computes P1/P2 perspective deltas).
var addlIds = GetAllPlayerIds(session).Skip(2).ToList();
if (IsEmpty(d1) || IsEmpty(d2))
if (deltas.Values.Any(IsEmpty))
{
// At least one player's delta is empty — fall back to full state for both.
tasks.Add(clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p1Id))), ct));
tasks.Add(clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, p2Id))), ct));
foreach (var pid in allIds)
tasks.Add(clientPush.PushAsync(pid,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, pid))), ct));
// Spectators also get a full push when the delta is suspicious.
var regFull = SpectatorRegistryService.Instance;
if (regFull != null)
{
@@ -218,10 +200,9 @@ internal abstract class GameHandlerBase
}
else
{
tasks.Add(clientPush.PushAsync(p1Id,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(d1)), ct));
tasks.Add(clientPush.PushAsync(p2Id,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(d2)), ct));
foreach (var (pid, delta) in deltas)
tasks.Add(clientPush.PushAsync(pid,
ServerMessage.Push("game.state_delta", new GameStateDeltaPush(delta)), ct));
var registry = SpectatorRegistryService.Instance;
if (registry != null)
@@ -236,10 +217,6 @@ internal abstract class GameHandlerBase
}
}
}
foreach (var aid in addlIds)
tasks.Add(clientPush.PushAsync(aid,
ServerMessage.Push("game.state_update",
new GameStateUpdatePush(GameEngine.ToDto(state, aid))), ct));
await Task.WhenAll(tasks);
}