# Ruin-flow.md — End-to-End Ruin & Ability System Reference > All line numbers and snippets reflect the state of the codebase as of May 2026. --- ## Table of Contents 1. [What Is a Ruin?](#1-what-is-a-ruin) 2. [Data Model](#2-data-model) 3. [Ability Definition Schema](#3-ability-definition-schema) 4. [Ruin-Specific Trigger Events](#4-ruin-specific-trigger-events) 5. [Client: Channeling a Ruin](#5-client-channeling-a-ruin) 6. [Server: Channeling a Ruin (`ChannelCard`)](#6-server-channeling-a-ruin-channelcard) 7. [Board Operations: PlaceRuin / RemoveRuin](#7-board-operations-placeruin--removeruin) 8. [Turn-Start Activation: `FireRuinAbilities`](#8-turn-start-activation-fireruinabilities) 9. [Activation Order & Priority Rules](#9-activation-order--priority-rules) 10. [Ruin-Specific Effects](#10-ruin-specific-effects) 11. [Observer Triggers: `RuinActivation` & `UnitOccupyRuin`](#11-observer-triggers-ruinactivation--unitoccupyruin) 12. [Double-Fire Guard (6-D)](#12-double-fire-guard-6-d) 13. [Network: Tile Deltas & DTOs](#13-network-tile-deltas--dtos) 14. [Client: Rendering & Inspection](#14-client-rendering--inspection) 15. [Client: Ruins Are Not Selectable Units](#15-client-ruins-are-not-selectable-units) 16. [End-to-End Sequence Diagram](#16-end-to-end-sequence-diagram) 17. [File & Class Summary](#17-file--class-summary) 18. [Failure Modes & Error Paths](#18-failure-modes--error-paths) 19. [Randomness & Determinism](#19-randomness--determinism) 20. [Disable Duration: Turn-Boundary Example](#20-disable-duration-turn-boundary-example) 21. [See Also](#21-see-also) --- ## 1. What Is a Ruin? A **Ruin** is a `CardType.Ruin` card (defined in `CardEnums.cs:5`) that is placed on the board and activates passively at the **start of every turn** if a Spirit, ArchSpirit, or SpiritToken occupies the same tile. Key distinctions from unit cards: - Ruins **do not block tile occupancy** — units freely share their tile. - Ruins are **not selectable** as attack targets or movement neighbors. - Ruins have **no player interaction after placement** — they fire automatically each turn. - Placement is **random** (server-chosen); the player has no tile choice. --- ## 2. Data Model ### 2.1 Card Definition (database) ``` Server/src/SOR.Database/Entities/Catalog/CardDefinition.cs ``` | Column | Type | Notes | |--------|------|-------| | `Id` | Guid | Unique per card definition | | `CardType` | enum | `"Ruin"` | | `Name`, `Description` | string | Display | | `SpCost`, `StCost` | int | Channeling cost | | `Affinity` | string? | If set, restricts valid placement tiles | | **`AbilitiesJson`** | JSONB | Array of `AbilityDefinition` — the abilities the Ruin executes | | `IsPublished` | bool | Controls deck-builder visibility | ### 2.2 Tile (board state) ``` Server/src/SOR.Game/Grid/Tile.cs ``` ```csharp // Lines 37-44 public string? RuinId { get; set; } // InstanceId of Ruin on this tile, or null public string? RuinOwner { get; set; } // AccountId of owner /// Turn number after which this tile's Ruin re-enables. 0 = not disabled. /// Set by DisableRuinForDurationEffect; checked in FireRuinAbilities. public int RuinDisabledUntilTurn { get; set; } ``` ### 2.3 FieldCard (in-game instance) ``` Server/src/SOR.Game/GameState.cs — PlayerState.Field ``` Ruins live in `PlayerState.Field` as `FieldCard` instances (same collection as units) with: - `CardType = "Ruin"` - `Position` (Coord?) — set on placement, never changes unless `RelocateRuinEffect` fires - `AbilitiesJson` — inherited from `CardDefinition`; may be mutated by effects --- ## 3. Ability Definition Schema ``` Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs ``` ```csharp public sealed class AbilityDefinition { public AbilityType Type; // Triggered (for Ruin activation) public Condition[]? ActivationConditions; // Optional; all must pass to be eligible public ActionGroup? ActionGroup; // Logical grouping (AND/OR/XOR) public Action[] Actions; // Flat array (backwards-compat) // Triggered-only: public TriggerEvent? TriggerEvent; // OnRuinActivationTrigger for Ruin abilities public int? TriggerLimitPerTurn; public int? TriggerLimitPerGame; public string[]? SourceZoneGate; // Display/anim: public string? Name; public string? Description; public DurationModel? Duration; public AbilityAnimationDefinition? Animation; } ``` Ruin abilities must have: - `Type == AbilityType.Triggered` - `TriggerEvent` of type `OnRuinActivationTrigger` (JSON `$type: "OnRuinActivation"`) --- ## 4. Ruin-Specific Trigger Events ``` Server/src/SOR.Game/Abilities/Models/Triggers.cs — Lines 42-161 ``` ### `OnRuinActivationTrigger` (line 147) ```csharp // §8.8 Ruin — registered as PolyType "OnRuinActivation" (line 43) public sealed class OnRuinActivationTrigger : TriggerEvent { public string RuinOwnership { get; set; } = "Any"; // "Mine", "Enemy", "Any" public string? OccupantOwnership { get; set; } // filter by occupant owner public Filter[]? OccupantFilters { get; set; } // additional occupant filters } ``` - **Used by:** Ruin card abilities that should execute when the Ruin activates at turn start. - **Also used by:** Observer cards on *other* cards that want to react when *any* Ruin fires. ### `OnUnitOccupyRuinTrigger` (line 155) ```csharp // §8.8 Ruin — registered as PolyType "OnUnitOccupyRuin" (line 44) public sealed class OnUnitOccupyRuinTrigger : TriggerEvent { public string UnitOwnership { get; set; } = "Any"; public Filter? Filter { get; set; } public Filter[]? OccupantFilters { get; set; } } ``` - **Fires when:** A unit moves onto a tile that already has a Ruin. - **Does NOT** auto-activate the Ruin — only notifies observer cards. --- ## 5. Client: Channeling a Ruin ### 5.1 Card click in hand (`game_screen.gd:654`) ```gdscript # game_screen.gd — line 654 if card.get("cardType", "") == "Ruin": _sel_ctrl.channel_ruin(card) return ``` Ruin cards bypass the normal tile-highlight flow and go straight to `channel_ruin`. ### 5.2 `channel_ruin` — pre-flight check (`selection_controller.gd:515`) ```gdscript # selection_controller.gd — lines 515-538 func channel_ruin(card: Dictionary) -> void: var card_affinity: String = card.get("affinity", "") var board: Dictionary = Game.get_board() var has_valid: bool = false for tile: Dictionary in board.get("tiles", []): var ruin_id_v: Variant = tile.get("ruinId", null) var ruin_id: String = "" if ruin_id_v == null else str(ruin_id_v) if not ruin_id.is_empty() and ruin_id != "null": continue # tile already has a Ruin if card_affinity != "" and not _tile_matches_channel_affinity(tile, card_affinity): continue # affinity mismatch has_valid = true break if not has_valid: # Show "No valid tile available" error dialog ... return _confirm_channel_ruin(card) ``` ### 5.3 Confirmation dialog (`selection_controller.gd:541`) ```gdscript # lines 541-552 func _confirm_channel_ruin(card: Dictionary) -> void: var dlg: ConfirmationDialog = ConfirmationDialog.new() dlg.title = "Channel Ruin" dlg.dialog_text = "Ruin placement is random.\nContinue?" dlg.ok_button_text = "Channel" ... dlg.confirmed.connect(func() -> void: Game.send_play_card(card.get("instanceId", ""), 0, 0) # no tile targets dlg.queue_free()) ``` ### 5.4 No tile targeting ```gdscript # tile_target_resolver.gd — lines 66-67 "Repentance", "Instinct", "Ruin": pass # No tile target — server handles placement for Ruins ``` The client sends **zero tile targets**. The server is authoritative for placement. --- ## 6. Server: Channeling a Ruin (`ChannelCard`) ``` Server/src/SOR.Game/GameEngine.cs — lines 262-440 ``` ### 6.1 Gate checks (lines 284-294) ```csharp // GameEngine.cs if (card.CardType == "Ruin" && !player.CanChannelRuin) throw new GameException("CANNOT_CHANNEL_RUIN"); // line 293-294 ``` `player.CanChannelRuin` can be toggled false by `SetCanChannelRuinEffect`. ### 6.2 Ruin branch (lines 413-440) ```csharp else if (card.CardType == "Ruin") { // Place on a random tile matching the Ruin's affinity (may already be occupied). var hasAffinity = Enum.TryParse(card.Affinity, out var ruinAffinity); var validTiles = board.Tiles.Values .Where(t => (!hasAffinity || AffinitySystem.IsAffinityValid(t, ruinAffinity)) && t.RuinId == null) // 6-C: never overwrite an existing Ruin .ToList(); if (validTiles.Count == 0) throw new GameException("NO_VALID_RUIN_TILE"); // line 421 var ruinCoord = validTiles[Random.Shared.Next(validTiles.Count)].Coord; // line 423 player.Hand.Remove(card); player.CurrentSp -= card.SpCost; player.CurrentSt -= card.StCost; var ruinField = ToFieldCard(card, ruinCoord); player.Field.Add(ruinField); board.PlaceRuin(ruinCoord, ruinField.InstanceId, actorId); // line 431 AbilitySystem.FireTrigger(state, new TriggerOccurrence // line 433 { Kind = TriggerEventKind.Channeled, ActorId = actorId, CardType = "Ruin", Data = new TriggerEventData { SourceId = ruinField.InstanceId }, }); } ``` **Step-by-step:** 1. Parse affinity from card; `hasAffinity = false` if card has no affinity. 2. Collect all tiles where `AffinitySystem.IsAffinityValid(tile, ruinAffinity)` is true (skipped entirely if no affinity) **AND** `tile.RuinId == null`. 3. Throw `NO_VALID_RUIN_TILE` if empty. 4. Pick one at random — fully server-authoritative. 5. Remove card from hand, deduct SP/ST. 6. Create `FieldCard`, add to `player.Field`, call `board.PlaceRuin`. 7. Fire `TriggerEventKind.Channeled` — observer cards (e.g., "when I channel a Ruin…") can react here. --- ## 7. Board Operations: `PlaceRuin` / `RemoveRuin` ``` Server/src/SOR.Game/Grid/Board.cs — lines 164-178 ``` ```csharp /// Place a Ruin on a tile. Does not check occupancy — Ruins share tiles with units. public void PlaceRuin(Coord c, string instanceId, string ownerAccountId) // line 165 { var tile = GetTile(c) ?? throw new GameException($"TILE_OUT_OF_BOUNDS:{c}"); tile.RuinId = instanceId; tile.RuinOwner = ownerAccountId; } public void RemoveRuin(string instanceId) // line 172 { var tile = Tiles.Values.FirstOrDefault(t => t.RuinId == instanceId); if (tile is null) return; tile.RuinId = null; tile.RuinOwner = null; } ``` **No occupancy check** — a Ruin is placed without regard to whether a unit is already on the tile. --- ## 8. Turn-Start Activation: `FireRuinAbilities` ``` Server/src/SOR.Game/Abilities/AbilitySystem.cs — lines 458-512 ``` ### 8.1 When it's called ```csharp // GameEngine.cs — line 1070 AbilitySystem.FireRuinAbilities(state); ``` Called near the **end of `StartTurn()`**, after: - MP/Defense reset - Aura re-evaluation - `OnTurnStart` triggers ### 8.2 Full implementation ```csharp // AbilitySystem.cs — lines 458-512 public static GameState FireRuinAbilities(GameState state) { foreach (var (ownerId, player) in state.Players) { var ruins = player.Field .OfType() .Where(c => c.CardType == "Ruin" && c.Position.HasValue) .ToList(); foreach (var ruin in ruins) { var tile = state.Board?.GetTile(ruin.Position!.Value); if (tile?.OccupantId is null) continue; // skip: no unit on tile // Skip if this ruin is disabled by DisableRuinForDurationEffect. if (tile.RuinDisabledUntilTurn > 0 && state.TurnNumber <= tile.RuinDisabledUntilTurn) continue; // Only fires if a Spirit or ArchSpirit is on the tile. var occupantType = FindUnitType(state, tile.OccupantId); if (occupantType is not ("Spirit" or "ArchSpirit" or "SpiritToken")) continue; var abilities = ParseAbilities(ruin.AbilitiesJson); var ctx = new AbilityContext { State = state, ActorId = ownerId, Source = ruin }; var eligible = abilities .Where(a => a.Type == AbilityType.Triggered && a.TriggerEvent is OnRuinActivationTrigger) .Where(a => a.ActivationConditions is not { Length: > 0 } || a.ActivationConditions.All(c => EvaluateCondition(c, ctx, ruin))) .ToList(); if (eligible.Count == 0) continue; // Select exactly one ability at random. var chosen = eligible[Random.Shared.Next(eligible.Count)]; // line 493 var chosenActions = GetEffectiveActions(chosen, ctx, abilityIndex: 0, chosen.Range, chosen.Duration); if (chosenActions is not null) ExecuteActions(chosenActions, ctx, clientTargets: null); // Notify observer cards that the ruin activated. FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.RuinActivation, ActorId = ownerId, Data = new TriggerEventData { SourceId = ruin.InstanceId, TargetId = tile.OccupantId, }, }); } } return state; } ``` ### 8.3 Helper: `FindUnitType` (lines 514-523) ```csharp private static string? FindUnitType(GameState state, string instanceId) { foreach (var player in state.Players.Values) { var c = player.Field.FirstOrDefault(x => x.InstanceId == instanceId) ?? player.ArchSpirit as CardInstance; if (c?.InstanceId == instanceId) return c.CardType; } return null; } ``` --- ## 9. Activation Order & Priority Rules | Rule | Detail | |------|--------| | **Per-player, per-ruin** | Outer loop: players; inner loop: ruins in `player.Field` list order. | | **Prerequisite 1: occupant** | Tile must have `OccupantId != null`. | | **Prerequisite 2: not disabled** | `tile.RuinDisabledUntilTurn == 0` or `turnNumber > disabledUntilTurn`. | | **Prerequisite 3: occupant type** | Occupant must be `"Spirit"`, `"ArchSpirit"`, or `"SpiritToken"`. | | **Ability filter** | Only abilities with `Type == Triggered` + `TriggerEvent is OnRuinActivationTrigger`. | | **Condition gating** | All `ActivationConditions` must pass (empty = always eligible). | | **Exactly one ability fires** | `Random.Shared.Next(eligible.Count)` — if multiple abilities are eligible, one is chosen at random. | | **No per-turn limit checked here** | `FireRuinAbilities` doesn't check `TriggerLimitPerTurn`; the limit applies when other cards trigger `OnRuinActivation` via `FireTrigger`. | | **Non-deterministic** | Both tile selection (`ChannelCard:423`) and ability selection (`FireRuinAbilities:493`) use `Random.Shared.Next()` — see §19. | | **Observer notification last** | `FireTrigger(RuinActivation)` is called *after* the chosen ability executes. | | **Ruin order** | `player.Field` insertion order (i.e., channeling order). No explicit priority number. | --- ## 10. Ruin-Specific Effects ``` Server/src/SOR.Game/Abilities/Models/Effects.cs — Lines 334-357 Server/src/SOR.Game/Abilities/AbilitySystem.cs — Lines 3040-3093 ``` ### 10.1 `RelocateRuinEffect` (Effects.cs:337 / executed at AbilitySystem.cs:3041) ```csharp // Effects.cs public sealed class RelocateRuinEffect : Effect { } ``` ```csharp // AbilitySystem.cs — lines 3041-3053 case RelocateRuinEffect when target is Coord destCoord: { if (ctx.Source is not FieldCard ruinFc || ctx.State.Board is null) break; var board = ctx.State.Board; var ruinTile = board.Tiles.Values.FirstOrDefault(t => t.RuinId == ruinFc.InstanceId); if (ruinTile is null) break; var destTile = board.GetTile(destCoord); if (destTile is null || destTile.RuinId is not null) break; // dest must be ruin-free board.RemoveRuin(ruinFc.InstanceId); board.PlaceRuin(destCoord, ruinFc.InstanceId, ctx.ActorId); ruinFc.Position = destCoord; break; } ``` Moves a Ruin to a new tile. Destination must be in-bounds and ruin-free. ### 10.2 `ActivateRuinAbilityEffect` (Effects.cs:345 / executed at AbilitySystem.cs:3055) ```csharp // Effects.cs — lines 345-351 public sealed class ActivateRuinAbilityEffect : Effect { public string? AbilityRef; // If set, activate ability by Name public bool Random = true; // If true (default), pick random eligible ability public bool ChooseAllTargets; // Auto-resolve all targets without player interaction } ``` ```csharp // AbilitySystem.cs — lines 3055-3075 case ActivateRuinAbilityEffect arAe when target is FieldCard ruinCard && ruinCard.CardType == "Ruin": { var ruinOwner = FindCardOwner(ctx.State, ruinCard.InstanceId); if (ruinOwner is null) break; var ruinCtx = new AbilityContext { State = ctx.State, ActorId = ruinOwner.AccountId, Source = ruinCard }; var ruinAbilities = ParseAbilities(ruinCard.AbilitiesJson); var eligible = ruinAbilities .Where(a => a.Type == AbilityType.Triggered && a.TriggerEvent is OnRuinActivationTrigger) .Where(a => a.ActivationConditions is not { Length: > 0 } || a.ActivationConditions.All(c => EvaluateCondition(c, ruinCtx, ruinCard))) .ToList(); if (eligible.Count == 0) break; AbilityDefinition chosen; if (!arAe.Random && arAe.AbilityRef is not null) chosen = eligible.FirstOrDefault(a => a.Name == arAe.AbilityRef) ?? eligible[Random.Shared.Next(eligible.Count)]; else chosen = eligible[Random.Shared.Next(eligible.Count)]; var chosenActs = GetEffectiveActions(chosen, ruinCtx, 0, chosen.Range, chosen.Duration); if (chosenActs is not null) ExecuteActions(chosenActs, ruinCtx, clientTargets: null); break; } ``` Programmatically activates a Ruin's ability from another card's effect. Same eligibility logic as `FireRuinAbilities`. Can target a specific ability by `AbilityRef` name or pick randomly. ### 10.3 `DisableRuinForDurationEffect` (Effects.cs:354 / executed at AbilitySystem.cs:3077) ```csharp // Effects.cs — lines 354-357 public sealed class DisableRuinForDurationEffect : Effect { public DurationModel Duration = DurationModel.EndOfTurn; } ``` ```csharp // AbilitySystem.cs — lines 3077-3093 case DisableRuinForDurationEffect drfd when target is FieldCard ruinDis && ruinDis.CardType == "Ruin": { if (ruinDis.Position.HasValue && ctx.State.Board is not null) { var ruinDisTile = ctx.State.Board.GetTile(ruinDis.Position.Value); if (ruinDisTile is not null) { int disableTurns = drfd.Duration.Type switch { DurationType.ForNTurns => drfd.Duration.N ?? 1, _ => 1, }; ruinDisTile.RuinDisabledUntilTurn = ctx.State.TurnNumber + disableTurns; // line 3089 } } break; } ``` Sets `tile.RuinDisabledUntilTurn`. `FireRuinAbilities` checks this at line 473 and skips the ruin if still within the disable window. ### 10.4 `SetCanChannelRuinEffect` ``` Server/src/SOR.Game/Abilities/Models/Effects.cs — line 174 ``` Gates whether a player can channel new Ruins at all. Checked in `ChannelCard` at `GameEngine.cs:293`. --- ## 11. Observer Triggers: `RuinActivation` & `UnitOccupyRuin` ### 11.1 `RuinActivation` — fired from `FireRuinAbilities` (line 499) After the chosen ability executes, `FireTrigger` broadcasts `TriggerEventKind.RuinActivation` so **other** cards (not the source Ruin itself — see §12) can react: ```csharp FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.RuinActivation, ActorId = ownerId, Data = new TriggerEventData { SourceId = ruin.InstanceId, TargetId = tile.OccupantId }, }); ``` Observer cards use `OnRuinActivationTrigger` with `RuinOwnership = "Any"` (or `"Mine"` / `"Enemy"`) to react. ### 11.2 `UnitOccupyRuin` — fired from `GameEngine.MoveUnit` (line 671) ```csharp // GameEngine.cs — lines 667-677 // Fire UnitOccupyRuin if the destination tile has a Ruin. var destTileAfterMove = board.GetTile(targetPos); if (destTileAfterMove?.RuinId is not null) { AbilitySystem.FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.UnitOccupyRuin, ActorId = actorId, Data = new TriggerEventData { SourceId = unitInstanceId, TargetId = destTileAfterMove.RuinId }, }); } ``` Fires mid-turn whenever a unit steps onto a Ruin tile. Does **not** activate the Ruin itself — it is purely a notification hook for observer cards using `OnUnitOccupyRuinTrigger`. --- ## 12. Double-Fire Guard (6-D) ``` Server/src/SOR.Game/Abilities/AbilitySystem.cs — lines 303-309 ``` ```csharp // 6-D: Prevent double-firing the source Ruin's own OnRuinActivation abilities. // FireRuinAbilities already executed one chosen ability directly; the subsequent // FireTrigger call is only for observer cards. Skip the source Ruin itself. if (occurrence.Kind == TriggerEventKind.RuinActivation && def.TriggerEvent is OnRuinActivationTrigger && card.InstanceId == occurrence.Data?.SourceId) continue; ``` **Why this exists:** `FireRuinAbilities` deliberately calls `FireTrigger(RuinActivation)` after executing the ability so observer cards can react. Without this guard, `FireTrigger`'s own scan would find the source Ruin again and execute its `OnRuinActivation` abilities a second time. The guard skips the source Ruin when processing the broadcast, so only *other* cards react. --- ## 13. Network: Tile Deltas & DTOs ``` Server/src/SOR.Game/GameMessages.cs ``` ### Full tile state (sent on game join / reconnect) ```csharp // GameMessages.cs — lines 745-753 public sealed record TileDto( CoordDto Coord, string Base1, string Base2, string ResolvedAffinity, string? OccupantId, string? OccupantOwner, string? RuinId, // ← Ruin instance ID or null string? RuinOwner); // ← owner account ID or null ``` ### Incremental delta (pushed after any state change) ```csharp // GameMessages.cs — lines 525-536 public sealed record TileDelta( int X, int Y, ... string? OccupantOwner, string? RuinId, // ← new RuinId, or null if cleared bool RuinCleared, // ← true when Ruin was removed from tile string? RuinOwner); ``` The server pushes `TileDelta` to all viewers whenever a tile's ruin state changes (placement, relocation, removal). --- ## 14. Client: Rendering & Inspection ``` Client/origin-client/scenes/game/components/hud/tile_drawer.gd ``` ### Variables declared (lines 18-31) ```gdscript var tile_drawer_ruin_labels: Array = [] # 2 label nodes for Name + Owner var tile_drawer_ruin_section: Dictionary = {} # collapsible "Ruin Details" section var tile_drawer_ruin_effects_section: Dictionary = {} # collapsible "Active Effects" section var tile_drawer_ruin_effects_labels: Array = [] ``` ### Section creation (lines 91-92) ```gdscript tile_drawer_ruin_section = create_tile_drawer_section(vbox, "Ruin Details", false) tile_drawer_ruin_effects_section = create_scrollable_section(vbox, "Active Effects") ``` ### Label slots (line 98) ```gdscript tile_drawer_ruin_labels = create_detail_labels(tile_drawer_ruin_section["content"], 2) # Slot 0: "Ruin: " # Slot 1: "Owner: " ``` ### Population on tile click (lines 419-426) ```gdscript var ruin_id_value: Variant = tile_data.get("ruinId", "") var ruin_id: String = "" if ruin_id_value == null else str(ruin_id_value) var ruin_owner_id: String = str(tile_data.get("ruinOwner", "")) if ruin_id_value != null and not ruin_id.is_empty() and ruin_id != "null": var ruin_lines: Array = ["Ruin: %s" % ruin_id, "Owner: %s" % Game.get_display_name(ruin_owner_id)] var ruin_tooltips: Array = ["", ""] set_tile_drawer_lines(tile_drawer_ruin_section, tile_drawer_ruin_labels, ruin_lines, ruin_tooltips) set_effects_section(ruin_id, tile_drawer_ruin_effects_section, tile_drawer_ruin_effects_labels) else: set_tile_drawer_lines(tile_drawer_ruin_section, tile_drawer_ruin_labels, []) clear_effects_section(tile_drawer_ruin_effects_section, tile_drawer_ruin_effects_labels) ``` Active effects targeting the Ruin (by its `instanceId`) are fetched and displayed in the scrollable effects section via `append_active_effect_lines` (line 316). --- ## 15. Client: Ruins Are Not Selectable Units ``` Client/origin-client/scenes/game/components/units/unit_registry.gd — lines 61-105 Client/origin-client/scenes/game/components/selection/selection_controller.gd — lines 94-178 Client/origin-client/scenes/game/components/board/tile_target_resolver.gd — lines 173-300 ``` ### `is_ruin_unit` / `is_ruin_instance` (unit_registry.gd:64-73) ```gdscript func is_ruin_unit(unit: Dictionary) -> bool: return str(unit.get("cardType", "")).to_lower() == "ruin" func is_ruin_instance(iid: String) -> bool: if iid.is_empty(): return false var unit: Dictionary = Game.get_unit_by_id(iid) return not unit.is_empty() and is_ruin_unit(unit) ``` ### Ruins excluded from: | Location | Line | What's excluded | |----------|------|----------------| | `unit_registry.gd:40` | `rebuild_ownership` | Ruins not added to friendly/enemy unit ID maps | | `unit_registry.gd:100` | `all_board_units()` | Ruins excluded from the "all board units" array | | `selection_controller.gd:99` | `select_unit` | Clicking a Ruin unit does nothing (returns early) | | `selection_controller.gd:176` | board click occupant resolution | Ruin occupant not treated as selectable unit | | `tile_target_resolver.gd:176` | `valid_attack_targets` | Ruins are never valid attack targets | | `tile_target_resolver.gd:300` | ArchSpirit movement targets | Ruins skipped when computing ArchSpirit range | --- ## 16. End-to-End Sequence Diagram ``` PLAYER CLIENT SERVER BOARD/STATE │ │ │ │ │ clicks Ruin │ │ │ │──────────────>│ │ │ │ │ channel_ruin(card) │ │ │ │ [pre-flight: any valid tile?] │ │ │ [no → AcceptDialog "No valid tile"] │ │ │ [yes → _confirm_channel_ruin(card)] │ │ │ ConfirmationDialog shown │ │ │ clicks Channel │ │ │ │──────────────>│ │ │ │ │ send_play_card(iid,0,0) ─────────────────────────>│ │ │ │ ChannelCard() │ │ │ │ ├─ validate CanChannelRuin│ │ │ │ ├─ filter valid tiles │ │ │ │ │ (affinity + no RuinId) │ │ │ │ ├─ pick random tile │ │ │ │ ├─ deduct SP/ST │ │ │ │ ├─ create FieldCard ─────>│ player.Field.Add │ │ │ ├─ board.PlaceRuin ──────>│ tile.RuinId = iid │ │ │ └─ FireTrigger(Channeled)─>│ observer cards react │ │<── TileDelta(RuinId) ───│ │ │ │ tile_drawer updates │ │ │ │ │ │ ╔═══════════════╪═════════════════════════╪══════════════════════════╪══╗ ║ NEXT TURN START ║ ╚═══════════════╪═════════════════════════╪══════════════════════════╪══╝ │ │ │ StartTurn() │ │ │ │ ├─ MP/Def reset │ │ │ │ ├─ Auras re-eval │ │ │ │ ├─ OnTurnStart triggers │ │ │ │ └─ FireRuinAbilities() │ │ │ │ for each ruin: │ │ │ │ ├─ check tile.OccupantId != null │ │ │ ├─ check not disabled │ │ │ │ ├─ check occupant type = Spirit/ArchSpirit/SpiritToken │ │ │ ├─ filter eligible abilities (OnRuinActivation + conditions) │ │ │ ├─ pick ONE at random │ │ │ │ ├─ ExecuteActions() ───>│ effects applied │ │ │ └─ FireTrigger(RuinActivation) │ │ │ (source Ruin skipped by 6-D guard) │ │ │ observer cards react │ │ │<── GameStateDelta ──────│ │ │ │ animations / HUD update │ │ │ │ │ │ ╔═══════════════╪═════════════════════════╪══════════════════════════╪══╗ ║ UNIT MOVES ONTO RUIN TILE (mid-turn) ║ ╚═══════════════╪═════════════════════════╪══════════════════════════╪══╝ │ │ │ MoveUnit() │ │ │ │ ├─ move unit │ │ │ │ ├─ FireTrigger(UnitMoved)│ │ │ │ └─ if destTile.RuinId != null: │ │ │ FireTrigger(UnitOccupyRuin) │ │ │ (observer cards only — ruin doesn't auto-fire) │ │<── GameStateDelta ──────│ │ ``` --- ## 17. File & Class Summary ### Server | File | Key Items | |------|-----------| | `SOR.Database/Entities/Catalog/CardDefinition.cs` | `CardDefinition` — `AbilitiesJson` JSONB column | | `SOR.Database/Enums/CardEnums.cs:5` | `CardType.Ruin` enum value | | `SOR.Game/Grid/Tile.cs:37-44` | `RuinId`, `RuinOwner`, `RuinDisabledUntilTurn` | | `SOR.Game/Grid/Board.cs:165-178` | `PlaceRuin()`, `RemoveRuin()` | | `SOR.Game/GameEngine.cs:262` | `ChannelCard()` — full channeling logic | | `SOR.Game/GameEngine.cs:413-440` | Ruin branch of `ChannelCard` | | `SOR.Game/GameEngine.cs:1070` | `FireRuinAbilities(state)` call site | | `SOR.Game/GameEngine.cs:667-677` | `UnitOccupyRuin` trigger firing on move | | `SOR.Game/GameMessages.cs:525-536` | `TileDelta` — `RuinId`, `RuinCleared`, `RuinOwner` | | `SOR.Game/GameMessages.cs:745-753` | `TileDto` — `RuinId`, `RuinOwner` | | `SOR.Game/Abilities/AbilitySystem.cs:458-512` | `FireRuinAbilities()` | | `SOR.Game/Abilities/AbilitySystem.cs:303-309` | 6-D double-fire guard | | `SOR.Game/Abilities/AbilitySystem.cs:3041-3093` | Effect execution: `RelocateRuin`, `ActivateRuinAbility`, `DisableRuinForDuration` | | `SOR.Game/Abilities/Models/AbilityDefinition.cs` | `AbilityDefinition` — full ability schema | | `SOR.Game/Abilities/Models/Triggers.cs:147-161` | `OnRuinActivationTrigger`, `OnUnitOccupyRuinTrigger` | | `SOR.Game/Abilities/Models/Effects.cs:337-357` | `RelocateRuinEffect`, `ActivateRuinAbilityEffect`, `DisableRuinForDurationEffect` | | `SOR.Game/Abilities/Models/Effects.cs:174` | `SetCanChannelRuinEffect` | ### Client (GDScript) | File | Key Items | |------|-----------| | `scenes/game/game_screen.gd:654-656` | Route Ruin card click to `_sel_ctrl.channel_ruin()` | | `scenes/game/components/selection/selection_controller.gd:515-556` | `channel_ruin()` pre-flight check; `_confirm_channel_ruin()` dialog; `send_play_card` | | `scenes/game/components/board/tile_target_resolver.gd:66-67` | `"Ruin": pass` — no tile target computed | | `scenes/game/components/board/tile_target_resolver.gd:176,300` | Ruins excluded from attack targets and ArchSpirit range | | `scenes/game/components/units/unit_registry.gd:64-105` | `is_ruin_unit()`, `is_ruin_instance()`, `all_board_units()` (excludes ruins) | | `scenes/game/components/selection/selection_controller.gd:99,176` | Ruins not selectable; not resolved as unit on board click | | `scenes/game/components/hud/tile_drawer.gd:18-31` | Ruin section variable declarations | | `scenes/game/components/hud/tile_drawer.gd:91-98` | Ruin section/label creation | | `scenes/game/components/hud/tile_drawer.gd:419-426` | Populate ruin details + active effects on tile inspection | --- ## 18. Failure Modes & Error Paths | Failure | Where detected | Error / behaviour | |---------|---------------|-------------------| | **No valid tile for affinity** | `GameEngine.cs:421` | `throw new GameException("NO_VALID_RUIN_TILE")` — propagated to client as an error response; card stays in hand, no cost deducted | | **Player flag blocks channeling** | `GameEngine.cs:293` | `throw new GameException("CANNOT_CHANNEL_RUIN")` — same recovery path as above | | **`AbilitiesJson` is null or empty string** | `AbilitySystem.cs — ParseAbilities()` | Returns an empty `AbilityDefinition[]`; `eligible.Count == 0` causes the Ruin to silently skip activation that turn | | **`AbilitiesJson` is malformed JSON** | `ParseAbilities()` | `JsonSerializer.Deserialize` throws; uncaught exception surfaces as a 500 / session fault — treat as a data-authoring bug | | **No `OnRuinActivationTrigger` ability defined** | `FireRuinAbilities:490` | `eligible.Count == 0 → continue` — Ruin sits on board forever without ever firing | | **All abilities fail `ActivationConditions`** | `FireRuinAbilities:488` | Same as above — Ruin present, no activation | | **`RelocateRuinEffect` — destination out of bounds** | `AbilitySystem.cs:3047` | `board.GetTile(destCoord)` returns null → `break`; relocation silently no-ops | | **`RelocateRuinEffect` — destination already has a Ruin** | `AbilitySystem.cs:3048` | `destTile.RuinId is not null → break`; relocation silently no-ops | | **`ActivateRuinAbilityEffect` — no owner found** | `AbilitySystem.cs:3058` | `ruinOwner is null → break`; effect silently no-ops | | **`DisableRuinForDurationEffect` — ruin not on board** | `AbilitySystem.cs:3079` | `ruinDis.Position.HasValue` is false → `break`; no-op | | **Client: no valid tile (pre-flight)** | `selection_controller.gd:529` | Shows "No valid tile available" `AcceptDialog`; never sends `send_play_card` | --- ## 19. Randomness & Determinism Both random choices in the Ruin system use `Random.Shared.Next()` (the process-wide shared `System.Random` instance): | Choice | Location | Notes | |--------|----------|-------| | Tile placement | `GameEngine.cs:423` — `validTiles[Random.Shared.Next(...)]` | Chosen from all affinity-matching, ruin-free tiles | | Ability selection | `AbilitySystem.cs:493` — `eligible[Random.Shared.Next(...)]` | Chosen from eligible `OnRuinActivation` abilities; also used inside `ActivateRuinAbilityEffect` at line 3071 | **`Random.Shared` is not seeded and not reproducible between runs.** Consequences for testing: - **Deterministic replay tests are not possible** without replacing `Random.Shared` or injecting a seeded `Random` instance. - **QA scripted tests** that verify Ruin placement or ability selection must either mock the random source, accept any valid outcome, or repeat the scenario enough times to cover all branches statistically. - **Balance analysis** that counts per-ability activation rates should aggregate across many games, not assume round-robin behaviour. --- ## 20. Disable Duration: Turn-Boundary Example `DisableRuinForDurationEffect` sets: ```csharp tile.RuinDisabledUntilTurn = ctx.State.TurnNumber + disableTurns; // AbilitySystem.cs:3089 ``` `FireRuinAbilities` skips a Ruin when: ```csharp tile.RuinDisabledUntilTurn > 0 && state.TurnNumber <= tile.RuinDisabledUntilTurn // line 473 ``` **Example — `ForNTurns: 2`, effect fires on Turn 5:** | Turn | `RuinDisabledUntilTurn` | `TurnNumber <= 7`? | Ruin fires? | |------|-------------------------|--------------------|-------------| | 5 (effect fires) | set to **7** (5 + 2) | — | No (effect fires this turn, activation already skipped or not yet reached) | | 6 | 7 | 6 ≤ 7 → true | **Skipped** | | 7 | 7 | 7 ≤ 7 → true | **Skipped** | | 8 | 7 | 8 ≤ 7 → false | **Fires normally** | The Ruin is **disabled on turns 6 and 7**, and **re-enables on turn 8**. The disable window is inclusive on both ends. --- ## 21. See Also - **[Ability-flow.md](Ability-flow.md)** — Deep dive into triggered ability execution, `FireTrigger` pipeline, condition evaluation, cost payment, and target resolution. Ruin abilities go through the same `ExecuteActions` path documented there. - **[Delta-Sync-flow.md](Delta-Sync-flow.md)** — How `GameStateDelta` / `TileDelta` are assembled and pushed to clients after every state mutation, including the `RuinId` / `RuinCleared` fields documented in §13 above.