Add Ability-flow.md: end-to-end ability system reference

Documents the full ability lifecycle — data models, all four ability types
(Active/Passive/Aura/Triggered), ActionGroup resolution, target resolution,
effect execution, interactive pause states, cost handling, duration tracking,
network message flow, and client-side targeting with line numbers throughout.

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:
dingo
2026-05-20 11:59:19 -04:00
co-authored by Claude Happy
parent 150a20b0ab
commit 4e3c197442
+904
View File
@@ -0,0 +1,904 @@
# Ability System — End-to-End Flow Reference
This document maps the full lifecycle of abilities in SOR, from data definition through server processing to client targeting and visual feedback. Line numbers reference the codebase as of 2026-05-20.
---
## Table of Contents
1. [Ability Data Model](#1-ability-data-model)
2. [Ability Types](#2-ability-types)
3. [Server Entry Points by Ability Type](#3-server-entry-points-by-ability-type)
4. [Active Ability Flow](#4-active-ability-flow)
5. [Triggered Ability Flow](#5-triggered-ability-flow)
6. [Passive Ability Flow](#6-passive-ability-flow)
7. [Aura Ability Flow](#7-aura-ability-flow)
8. [Ruin Ability Flow](#8-ruin-ability-flow)
9. [ActionGroup Resolution](#9-actiongroup-resolution)
10. [Target Resolution](#10-target-resolution)
11. [Effect Execution](#11-effect-execution)
12. [Interactive Pause States](#12-interactive-pause-states)
13. [Cost Handling](#13-cost-handling)
14. [Duration and Effect Tracking](#14-duration-and-effect-tracking)
15. [Condition System](#15-condition-system)
16. [Filter System](#16-filter-system)
17. [Trigger System](#17-trigger-system)
18. [Network Message Flow](#18-network-message-flow)
19. [Client-Side Targeting](#19-client-side-targeting)
20. [Client Visual Effects](#20-client-visual-effects)
21. [Resume Paths (Paused Abilities)](#21-resume-paths-paused-abilities)
22. [Key Cross-File Connections](#22-key-cross-file-connections)
---
## 1. Ability Data Model
### `AbilityDefinition`
**File:** `Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs` lines 23–126
Root object stored as JSONB in `CardDefinition.AbilitiesJson` (array). All abilities on a card are parsed from this array at runtime.
```csharp
// AbilityDefinition.cs line 23
public class AbilityDefinition
{
public AbilityType Type { get; init; } // Active | Passive | Aura | Triggered
public ActionGroup? ActionGroup { get; init; } // line 31 — recursive AND/OR/XOR tree
public Action[]? Actions { get; init; } // line 35 — legacy flat list (backward compat)
public CostGroup? CostGroup { get; init; } // line 42 — AND/OR/XOR cost tree
public CostEntry[]? Cost { get; init; } // line 46 — legacy flat costs
public AbilityRange? Range { get; init; } // line 47 — min/max/LOS/linear constraints
public int UsesPerTurn { get; init; } // line 49 — default 1
public int? AuraRange { get; init; } // line 52 — radius for Aura type
public bool ClearOnLeave { get; init; } // line 58 — revert on leaving aura range
public DurationModel? LingerDuration { get; init; } // line 63 — override when leaving
public Action[]? OnEnterAuraActions { get; init; } // line 69 — fires per unit entering aura
public Action[]? OnLeaveAuraActions { get; init; } // line 74 — fires per unit leaving aura
public TriggerEvent? TriggerEvent { get; init; } // line 78 — which event fires this ability
public int? TriggerLimitPerTurn { get; init; } // line 84 — max fires per turn
public int? TriggerLimitPerGame { get; init; } // line 90 — max fires per game
public string[]? SourceZoneGate { get; init; } // line 98 — zones source must be in (null = battlefield)
public string Name { get; init; } // line 104
public string Description { get; init; } // line 110
public DurationModel? Duration { get; init; } // line 119 — ability-level duration override
public AbilityAnimationDefinition? Animation { get; init; } // line 125 — client VFX metadata
}
```
### `AbilityType` enum
**File:** `Models/AbilityDefinition.cs` lines 5–13
```csharp
public enum AbilityType { Active, Passive, Aura, Triggered }
```
### `Action`
**File:** `Server/src/SOR.Game/Abilities/Models/Action.cs` lines 82–95
Atomic targeting + effect unit. All effects in an action share the same target and duration.
```csharp
public class Action
{
public TargetSelector Target { get; init; }
public Condition[]? Conditions { get; init; } // Subject=="Target" → per-target filter; else → gate whole action
public Effect[] Effects { get; init; }
public DurationModel? Duration { get; init; }
public ChooseOne? ChooseOne { get; init; } // when set, replaces Effects with branch selection
}
```
### `TargetSelector`
**File:** `Models/Action.cs` lines 57–71
```csharp
public class TargetSelector
{
public string Scope { get; init; } // Hand | Deck | Discard | Battlefield | Player | AnyZone
public string Type { get; init; } // Unit | ArchSpirit | Spirit | SpiritToken | Ruin | Tile | Card | Player
public string Ownership { get; init; } // Self | ExactSelf | Owner | Ally | Enemy | Any | Random | Target
public string? Chooser { get; init; } // Self | Opponent | Ally | Random — who picks from valid pool
public TargetCount Count { get; init; } // { N, UpTo, All }
public Filter[]? Filters { get; init; }
}
```
### `ActionGroup`
**File:** `Models/Action.cs` lines 135–148
Recursive group allowing branching ability structures.
```csharp
public class ActionGroup
{
public string Logic { get; init; } // And | Or | Xor
public string? ChooserRole { get; init; } // Self | Opponent | Random (for Or/Xor)
public ActionGroup[]? Groups { get; init; } // nested sub-groups
public Action[]? Actions { get; init; } // leaf actions
}
```
### `AbilityRange`
**File:** `Models/Action.cs` lines 231–245
```csharp
public class AbilityRange
{
public int Min { get; init; }
public int Max { get; init; }
public bool RequiresLos { get; init; } // line-of-sight check via LineOfSight.HasLos
public bool LinearOnly { get; init; } // only cardinal/diagonal straight lines
}
```
### `CostEntry` / `CostGroup`
**File:** `Models/Action.cs` lines 186–227
`CostType` values: `SpiritPoints`, `SacrificeTokens`, `DiscardFromHand`, `MillTopOfDeck`, `MillBottomOfDeck`, `SendSpiritFromBattlefieldToDiscard`, `DealDamageToOwnArchSpirit`, `DealDamageToOwnSpirit`
`CostPickMode`: `Random`, `SelfPick`, `EnemySeePick`, `EnemyRandomPick`, `EnemyPick`
---
## 2. Ability Types
| Type | Activation | Cost | Usage Tracking |
|---|---|---|---|
| `Active` | Player manually activates; checks `IsExhausted`, `CanUseAbility`, `AbilityUsesThisTurn` | SP / ST / card costs paid on activation | `AbilityUsesThisTurn` dictionary keyed by `abilityIndex` |
| `Passive` | Applied automatically when unit enters battlefield; reverted on leave | None | `ActiveEffects` with `WhileSourceOnBattlefield` duration |
| `Aura` | Always-on; re-evaluated on unit move/enter/leave events | None | `ActiveEffects` tracks buffs; `ClearOnLeave` / `LingerDuration` govern expiry |
| `Triggered` | Fires inline when matching `TriggerEvent` occurs via `FireTrigger()` | None | `_triggerCountsPerTurn` / `_triggerCountsPerGame` static dicts keyed by `(instanceId, abilityName, turn)` |
---
## 3. Server Entry Points by Ability Type
| Ability Type | Entry Point | File | Line |
|---|---|---|---|
| Active | `AbilitySystem.ActivateAbility()` | `AbilitySystem.cs` | 85 |
| Active (card effect) | `AbilitySystem.FireCardEffects()` | `AbilitySystem.cs` | 160 |
| Triggered | `AbilitySystem.FireTrigger()` | `AbilitySystem.cs` | 256 |
| Ruin | `AbilitySystem.FireRuinAbilities()` | `AbilitySystem.cs` | 458 |
| Passive (enter) | `AbilitySystem.ApplyPassivesForSource()` | `AbilitySystem.cs` | 5090 |
| Passive (new target) | `AbilitySystem.ApplyPassivesToNewTarget()` | `AbilitySystem.cs` | 5116 |
| Passive (leave) | `AbilitySystem.RevokePassivesForSource()` | `AbilitySystem.cs` | 5142 |
| Aura (enter) | `AbilitySystem.EvaluateAurasOnEnter()` | `AbilitySystem.cs` | 5276 |
| Aura (leave) | `AbilitySystem.EvaluateAurasOnLeave()` | `AbilitySystem.cs` | 5369 |
| Aura (move) | `AbilitySystem.EvaluateAuraTransitions()` | `AbilitySystem.cs` | 5221 |
---
## 4. Active Ability Flow
**Handler:** `Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs` line 35
**Engine:** `AbilitySystem.ActivateAbility()` — `AbilitySystem.cs` line 85
### Step-by-step
```
Client → "game.activate_ability" { SourceInstanceId, AbilityIndex, Targets[] }
```
1. **Locate source** — find unit on `player.Field` or `player.ArchSpirit` (line 90–102)
2. **Validate IsExhausted** — unit must not be exhausted (line 104)
3. **Validate CanUseAbility** — flag must be true (line 107)
4. **Parse abilities** — `ParseAbilities(source.AbilitiesJson)` (line 110)
5. **Bounds check** — `abilityIndex` within array range (line 113)
6. **Type check** — `def.Type == AbilityType.Active` (line 116)
7. **DisabledAbilities check** — ability must not be in `source.DisabledAbilities` (line 119)
8. **UsesPerTurn enforcement** — compare `AbilityUsesThisTurn[abilityIndex]` vs `def.UsesPerTurn` (line 122)
9. **Build AbilityContext** — `new AbilityContext(state, actorId, source)` (line 128)
10. **`ValidateSourceActivationConditions()`** — non-Target conditions gate activation (line 131)
11. **`PreValidateClientTileTargets()`** — validate tile picks before paying cost (lines 203–249)
12. **Increment AbilityUsesThisTurn** — `AbilityUsesThisTurn[abilityIndex]++` (line 138)
13. **`GetEffectiveActions()`** — resolve ActionGroup or fall back to legacy Actions; returns `null` when paused for OR/XOR pick (line 141)
14. **`PayCostGroup()` / `PayCosts()`** — pay ability cost; may pause for interactive cost pick (line 144)
15. **`ExecuteActions()`** — full execution pipeline (line 152)
### After execution
```
→ SaveStateAsync() + PushStateToPlayersAsync()
→ PushPendingPromptsAsync() (GameHandlerBase.cs line 400)
→ Server broadcasts "game.activate_ability.ack" { GameStateDto }
```
If `ability.Animation?.AssetUrl` is null/empty, `GameActivateAbilityHandler` (lines 63–88) computes `AbilityPlaceholderVisualPush` with `TargetMode` and broadcasts `"game.visual.ability_placeholder"`.
---
## 5. Triggered Ability Flow
**Entry:** `AbilitySystem.FireTrigger(GameState state, TriggerOccurrence occurrence)` — `AbilitySystem.cs` line 256
`FireTrigger` is called inline by game engine methods whenever a relevant game event occurs (unit death, damage dealt, card channeled, etc.).
### Per-card, per-ability loop
```
For each player → For each card on battlefield (+ SourceZoneGate zones):
```
1. **`CanUseAbility == false`** → skip (line 270)
2. **`TriggerMatches()`** — match event kind, ownership constraints, filters (line 275)
3. **Ruin double-fire guard** — skip source Ruin on `RuinActivation` (lines 303–309)
4. **`ActivationConditions` check** (line 312)
5. **TriggerLimitPerTurn** — dict key: `(instanceId, abilityName, turnNumber)` (line 318)
6. **TriggerLimitPerGame** — dict key: `(instanceId, abilityName)` (line 330)
7. **`GetEffectiveActions()`** — resolve ActionGroup (line 340)
8. **`ActionNeedsClientTargets()`** — if true, store `PendingTriggeredTarget` and return immediately (lines 350–360)
9. **`ExecuteActions()`** — direct execution for auto-resolved abilities (line 365)
10. **`PendingDeferredEffects`** processing — apply `ApplyOnEventEffect` deferreds (lines 387–435)
### `TriggerOccurrence`
**File:** `AbilityContext.cs` line 119
```csharp
public record TriggerOccurrence(
TriggerEventKind Kind,
string ActorId, // unit/player that caused the event
object? Data, // event-specific payload
string? UnitType,
CardType? CardType
);
```
### `TriggerEventKind` enum
**File:** `AbilityContext.cs` line 84 — 24 values mirroring the Trigger model types.
---
## 6. Passive Ability Flow
### On unit enter battlefield
```
EvaluateAurasOnEnter() (line 5276)
ApplyPassivesForSource() (line 5090) ← all passive abilities from new unit → all existing units
ApplyPassivesToNewTarget() (line 5116) ← all existing units' passives → new unit only
```
**`ApplyPassivesForSource()`** — line 5090:
- Executes all `AbilityType.Passive` abilities from the source against all battlefield units
- Duration: `WhileSourceOnBattlefield` (or `def.Duration` if overridden)
**`ApplyPassivesToNewTarget()`** — line 5116:
- All other battlefield units' passives applied with `restrictTargets = [newUnit]`
### On unit leave battlefield
**`RevokePassivesForSource()`** — line 5142:
- Finds all `WhileSourceOnBattlefield` effects where `SourceInstanceId` matches the departing unit
- Calls `ApplyReversal()` for each tracked effect
### Re-evaluation (conditional passives)
**`ReEvaluateConditionalPassives()`** — line 5173:
- Full revoke-then-reapply for units with `ActivationConditions` on their passives
- Called after: unit moves, affinity changes, ability activations — anything that could invalidate conditions
---
## 7. Aura Ability Flow
### On unit move
**`EvaluateAuraTransitions()`** — line 5221:
- Part 1: stationary aura sources — compare moving unit's old vs. new position against each aura source's radius
- Part 2: moving unit's own auras — compare each stationary unit against old vs. new aura radius
- Calls `FireAuraTransition(wasIn, isIn)` for each state change
### On unit enter battlefield
**`EvaluateAurasOnEnter()`** — line 5276:
- Check all existing aura sources: is new unit within range? → `FireAuraTransition(false, true)`
- Check new unit's own auras: is each existing unit within range? → `FireAuraTransition(false, true)`
### On unit leave battlefield
**`EvaluateAurasOnLeave()`** — line 5369:
- Before removal: fire `FireAuraTransition(wasIn: true, isIn: false)` for all in-range aura sources
### `ApplyAuraEffects()` — line 5416
Executes aura's action list on a target unit with `WhileSourceOnBattlefield` duration (or `def.Duration`). `restrictTargets` = the entering unit only.
### `ClearOnLeave` / `LingerDuration`
- `ClearOnLeave == true` (default): aura effects reverted immediately when unit leaves range
- `LingerDuration`: instead of immediate revoke, the tracked effect's duration is switched to `LingerDuration`
### `ReapplyAurasAtTurnStart()` — line 5326
- Strips stale tracked effects for active-player units **without** reversal (stats already reset by turn-start)
- Re-applies fresh aura effects for all currently in-range units
---
## 8. Ruin Ability Flow
**`FireRuinAbilities()`** — `AbilitySystem.cs` line 458
Called at start of each turn. Steps:
1. For each Ruin with an occupant (Spirit / ArchSpirit / SpiritToken):
- Find all eligible `OnRuinActivationTrigger` abilities on the occupant
- Pick **one at random** from eligible abilities
- Execute that ability via `ExecuteActions()`
2. `FireTrigger(TriggerEventKind.RuinActivation)` — notify observer cards of the ruin activation
The double-fire guard in `FireTrigger` (lines 303–309) prevents the source Ruin from re-triggering its own activation.
---
## 9. ActionGroup Resolution
**`GetEffectiveActions()`** — `AbilitySystem.cs` line 981 (entry point)
Resolves the `ActionGroup` tree into a flat list of `Action` objects. Returns `null` when paused waiting for player input.
```
GetEffectiveActions()
→ if def.ActionGroup != null: ResolveActionGroup(def.ActionGroup, ctx)
→ else: return def.Actions (legacy flat list)
```
**`ResolveActionGroup()`** — line 999:
```
AND group:
→ flatten all leaf Actions from each child
→ recurse into nested ActionGroups
→ return combined list
OR/XOR + Random chooser:
→ server picks one child at random
→ return that child's actions
OR/XOR + Self/Opponent chooser:
→ store PendingActionGroupPick on GameState
→ return null (execution paused)
```
**`ResumeActionGroupPick()`** — line 1081:
- Called by `GameActionGroupPickHandler` when player responds
- Validates player choice index; retrieves chosen group's actions
- Continues `ExecuteActions()` with resolved action list
---
## 10. Target Resolution
**`ResolveTargets()`** — `AbilitySystem.cs` line 1924
Converts `TargetSelector` + client-provided target IDs into a concrete list of `TargetRef` objects.
### Player targets (line 1928)
Direct ownership lookup — `Owner`, `Enemy`, or `Target` (relay from prior action's resolved target).
### Tile targets (line 1940)
- `All == true` → enumerate entire board
- Otherwise → client-provided coordinates
### Unit targets (line 1950+)
```
BuildCandidates() (line 2125) → expand by TargetScope, filter by TargetType
↓
Apply ExactSelf restriction
↓
Apply restrictTargets (passive/aura re-evaluation path)
↓
Apply Filter[] (per-filter evaluation)
↓
Random chooser path → server selects random from candidates
↓
Client-provided IDs → validate each against candidates
↓
FilterTargetsByAbilityRange() (line 2067) → Manhattan distance + LinearOnly + LOS
↓
Count enforcement → exactly N, up-to N, or all
```
**`BuildCandidates()`** — line 2125:
- Expands by `TargetScope` across owner IDs (Self / Ally / Enemy / Any)
- Filters by `TargetType` (Unit / ArchSpirit / Spirit / SpiritToken / Ruin)
**`FilterTargetsByAbilityRange()`** — line 2067:
- Manhattan distance check: `source.Coord.ManhattanDistance(target.Coord)` within `[Min, Max]`
- `LinearOnly`: validates target lies on same row, column, or diagonal
- `RequiresLos`: calls `LineOfSight.HasLos(source.Coord, target.Coord, board)`
**`IsTargetInAbilityRange()`** — line 2083:
- Per-target check used for individual validation
---
## 11. Effect Execution
**`ExecuteActions()`** — `AbilitySystem.cs` line 1659 (private)
```
_sequenceDepth++
for each action in actions:
ExecuteSingleAction(action, ctx)
if state.HasPendingInteraction() → break immediately
_sequenceDepth--
if _sequenceDepth == 0: ExpireEndOfSequenceEffects()
```
**`ExecuteSingleAction()`** — line 1691 (private):
```
1. Handle ChooseOne (random/opponent-pause/client-index)
2. Evaluate source-level Conditions (Subject != "Target")
3. Detect Opponent/Ally Chooser with no client targets → store PendingTargetPick, return
4. ResolveTargets() → build candidate list
5. Per-target: filter Conditions where Subject == "Target"
6. For each effect in action.Effects:
ExecuteEffect(effect, target, duration, ctx)
if HasPendingInteraction() → stop
```
**`ExecuteEffect()`** dispatches on `effect` type. The complete switch covers 60+ effect subtypes defined in `Models/Effects.cs`.
### Effect categories
| Category | Examples | Lines in Effects.cs |
|---|---|---|
| Stat modification | `ModifyHealthEffect`, `ModifyDefenseEffect`, `ModifyDamageEffect`, `ModifyMPEffect` | 139–151 |
| Flag modification (unit) | `SetCanMove`, `SetCanAttack`, `SetCanDefend`, `SetCanBeAttacked`, `SetCanUseAbility` | 155–165 |
| Flag modification (player) | `SetCanDrawCards`, `SetAccumulatesSP`, `SetCanChannelSpirit`, `SetCanAscendArchSpirit` | 166–177 |
| Ability modification | `AddAbilityEffect`, `RemoveAbilityEffect`, `EnableAbilityEffect`, `DisableAbilityEffect` | 182–185 |
| Genus / SP / ST | `AddGenusEffect`, `ModifySPEffect`, `ModifySTEffect`, `ModifySPAccumulationEffect` | 189–197 |
| Tile modification | `SetBaseAffinity1Effect`, `PushAffinityEffect`, `PushFinalAffinityEffect` | 201–204 |
| Zone / card operations | `DrawCardsEffect`, `DiscardCardsEffect`, `ReturnToHandEffect`, `SearchDeckEffect`, `PlaceOnDeckEffect` | 208–232 |
| Combat / damage | `DealDamageEffect`, `HealEffect`, `DOTEffect`, `HOTEffect`, `PreventDeathEffect`, `PreventNextDamageEffect` | 236–256 |
| Displacement | `PushUnitEffect`, `PullUnitEffect`, `DisplaceUnitEffect`, `RepositionUnitEffect` | 260–288 |
| Control / token / summoning | `TakeControlEffect`, `SummonTokenEffect`, `CloneSpiritAsTokenEffect`, `DestroyTokenEffect` | 292–330 |
| Misc / complex | `ApplyOnEventEffect`, `StackDeckEffect`, `SkipTurnEffect`, `ChangeAttackTypeEffect`, `RelocateRuinEffect` | 334–458 |
---
## 12. Interactive Pause States
All pause states are fields on `GameState` (`GameState.cs` lines 94–169).
**`HasPendingInteraction()`** — `GameState.cs` line 161: returns `true` if any pending field is non-null. Checked at every iteration of `ExecuteActions()` and `ExecuteSingleAction()` — stops execution immediately when set.
| Pending State | File | Cause | Resume Handler |
|---|---|---|---|
| `PendingTriggeredTarget` | `Models/PendingTriggeredTarget.cs` | Triggered ability needs client target picks | `GameTriggeredTargetHandler` |
| `PendingTargetPick` | `Models/PendingTargetPick.cs` | Opponent/Ally chooser needs to pick targets | `GameTargetPickHandler` |
| `PendingActionGroupPick` | `Models/PendingActionGroupPick.cs` | OR/XOR ActionGroup needs player choice | `GameActionGroupPickHandler` |
| `PendingBranchPick` | `Models/PendingBranchPick.cs` | ChooseOne branch selection | `GameBranchPickHandler` |
| `PendingCostPick` | `Models/PendingCostPick.cs` | Interactive cost selection | `GameCostPickHandler` |
| `PendingCostGroupPick` | `Models/PendingCostGroupPick.cs` | OR/XOR cost group choice | `GameCostGroupPickHandler` |
| `PendingTilePick` | `Models/PendingTilePick.cs` | Tile destination pick | `GameTilePickHandler` |
| `PendingPlayerPick` | `Models/PendingPlayerPick.cs` | Player selection | `GamePlayerPickHandler` |
| `PendingRevealChoicePick` | `Models/PendingRevealChoicePick.cs` | StackDeck ordering | `GameRevealChoicePickHandler` |
---
## 13. Cost Handling
**`PayCostGroup()`** — `AbilitySystem.cs` — handles AND/OR/XOR cost trees; may pause via `PendingCostGroupPick`.
**`PayCosts()`** — handles flat `CostEntry[]`; may pause via `PendingCostPick` when `CostPickMode` requires player input.
### CostType behaviors
| CostType | What happens |
|---|---|
| `SpiritPoints` | Deduct SP from activating player |
| `SacrificeTokens` | Remove spirit tokens from battlefield |
| `DiscardFromHand` | Player discards N cards from hand |
| `MillTopOfDeck` | Remove N cards from top of deck |
| `MillBottomOfDeck` | Remove N cards from bottom of deck |
| `SendSpiritFromBattlefieldToDiscard` | Move spirit to discard zone |
| `DealDamageToOwnArchSpirit` | Deal N damage to own ArchSpirit |
| `DealDamageToOwnSpirit` | Deal N damage to own spirit |
### CostPickMode
| Mode | Who selects |
|---|---|
| `Random` | Server picks randomly |
| `SelfPick` | Activating player picks |
| `EnemySeePick` | Enemy picks (activating player can see) |
| `EnemyRandomPick` | Enemy picks randomly |
| `EnemyPick` | Enemy picks (blind) |
---
## 14. Duration and Effect Tracking
### `DurationType` enum
**File:** `Models/DurationModel.cs` lines 7–29
| Value | When the effect expires |
|---|---|
| `Instant` | Never tracked; applied once, not tracked |
| `UntilEndOfTurn` | End of current turn |
| `UntilStartOfOwnerTurn` | Start of the affected unit's owner's turn |
| `UntilStartOfSourceOwnerTurn` | Start of the ability source owner's turn |
| `ForNTurns` | After N full turns |
| `UntilEndOfSequence` | When `_sequenceDepth` returns to 0 |
| `WhileCondition` | While a named condition evaluates true |
| `WhileSourceOnBattlefield` | While the source unit is on the battlefield |
| `PermanentInMatch` | Never expires during the match |
### `TrackEffect()` — `AbilitySystem.cs` line 4764
Stores reversal as an `ActiveEffect` in `state.ActiveEffects`:
- `SourceInstanceId`, `TargetRef`, `EffectJson` (reversal effect), `DurationJson` (TrackedDuration)
- No-op for `Instant` or `PermanentInMatch` (not tracked)
### `TrackTick()` — line 4792
Stores DOT/HOT as an `ActiveEffect` with `IsTick = true`. Ticks fire on each turn boundary.
### `ApplyReversal()` — line 5038
Calls `ExecuteEffect(reversalEffect, target, duration: null, ctx)` to undo the tracked effect.
### `ExpireEndOfSequenceEffects()` — line 5008
Runs when `_sequenceDepth` reaches 0 — cleans up all `UntilEndOfSequence` tracked effects.
### `LabelFromReversal()` — line 4821
Generates human-readable display labels (e.g. `"ATK +2"`, `"Rooted"`) shown on the client's active effects HUD.
---
## 15. Condition System
**File:** `Server/src/SOR.Game/Abilities/Models/Conditions.cs`
Abstract base `Condition` with `Subject` property (`"Self"` or `"Target"`) — line 68–76.
Conditions with `Subject == "Target"` are evaluated per-target in `ExecuteSingleAction()`. All others gate the entire action.
### Composite
`AndCondition`, `OrCondition`, `XorCondition`, `NotCondition`
### Unit conditions
`HealthBelowCondition`, `HealthAboveCondition`, `DefenseIsCondition`, `HasGenusCondition`, `HasAbilityCondition`, `IsOnTileWithAffinityCondition`, `IsAdjacentToCondition`, `WithinRangeOfCondition`, `MovementTypeIsCondition`, `DestinationTileAffinityIsCondition`, `PreviousTileAffinityIsCondition`, `MovedFromOrIntoAffinityCondition`, `IsAdjacentToTileWithAffinityCondition`, `IsOnOrAdjacentToTileWithAffinityCondition`, `IsCurrentlyMovingCondition`
### Player conditions
`SPAtLeastCondition`, `SPAtMostCondition`, `STAtLeast/AtMostCondition`, `HandSizeAtLeast/AtMostCondition`, `DeckSizeAtLeastCondition`, `DiscardSizeAtLeastCondition`
### Tile conditions
`TileAffinityMatchesCondition`, `TileIsOccupiedCondition`, `TileIsUnoccupiedCondition`
### Turn / timing conditions
`IsOwnTurnCondition`, `IsOpponentTurnCondition`, `IsAllyTurnCondition`, `IsActivePlayerTurnCondition`
### Battlefield conditions
`UnitCountOnBattlefieldCondition`, `CardInZoneCondition`, `ControlledTileCountWithAffinityCondition`
### Extended unit conditions
`UnitTypeIsCondition`, `OwnershipIsCondition`, `IsThisCardCondition`, `UnitPropertyCompareCondition`, `PlayerPropertyCompareCondition`, `HandContainsCountCondition`, `CardDefinitionCountInZoneCondition`, `IsInRangeOfUnitCondition`, `TileOccupantCondition`, `SurroundingTileCondition`, `SPAccumulationCompareCondition`, `CostOfCardsInHandCondition`
---
## 16. Filter System
**File:** `Server/src/SOR.Game/Abilities/Models/Filters.cs`
Abstract base `Filter` — line 42. Used in `TargetSelector.Filters`, `CostEntry.Filters`, and many effect fields (e.g. `RepositionUnitEffect.TileFilters`).
### Unit / card filters
`GenusContainsFilter`, `AffinityMatchesFilter`, `HealthBelowFilter`, `HealthAboveFilter`, `DamageRangeFilter`, `DefenseRangeFilter`, `MPRangeFilter`, `HasFlagFilter`, `TierIsFilter`, `IsAdjacentToSourceFilter`, `CardTypeIsFilter`, `CardSPCostRangeFilter`, `CardSTCostRangeFilter`, `WithinRangeFilter`, `IsSelfFilter`, `IsExactSelfFilter`, `IsAdjacentToUnitMatchingFilter`, `IsAdjacentToTileMatchingFilter`
### Tile filters
`TileAffinityMatchesFilter`, `TileIsOccupiedFilter`, `TileIsUnoccupiedFilter`, `TileWithinRangeFilter`, `TileIsAdjacentToUnitFilter`, `TileIsOnPlayerSideFilter`, `TileIsInArchSpiritChannelRangeFilter`
### Generic filters
`OwnershipFilter`, `UnitPropertyFilter` (PropertyName + Comparator + Value), `TileOccupancyFilter` (UnitType + Ownership + nested UnitFilters)
---
## 17. Trigger System
**File:** `Server/src/SOR.Game/Abilities/Models/Triggers.cs`
Abstract base `TriggerEvent` — line 64. All matched via `TriggerMatches()` in `AbilitySystem.cs`.
### Trigger categories
| Category | Trigger Types |
|---|---|
| Turn phase | `OnTurnStartTrigger`, `OnTurnEndTrigger` |
| Channeling | `OnChanneledTrigger` (CardType, Ownership, CardDefinitionId) |
| ArchSpirit tiers | `OnAscendTrigger`, `OnTransitionTrigger` |
| Unit actions | `OnUnitMoveTrigger`, `OnUnitAttackTrigger`, `OnUnitAbilityActivatedTrigger`, `OnUnitMPSpentTrigger` |
| Damage | `OnDamageDealtTrigger`, `OnDamagePreventedTrigger`, `OnHealedTrigger`, `BeforeUnitDeathTrigger`, `BeforeDamageAppliedTrigger` |
| Unit lifecycle | `OnUnitEnterBattlefieldTrigger`, `OnUnitLeaveBattlefieldTrigger`, `OnUnitDeathTrigger`, `OnUnitSentToDiscardTrigger`, `OnSpiritSacrificedTrigger`, `OnTokenSummonedTrigger` |
| State changes | `OnStatModifiedTrigger`, `OnAbilityAddedTrigger`, `OnAbilityRemovedTrigger`, `OnGenusChangedTrigger` |
| Ruin | `OnRuinActivationTrigger`, `OnUnitOccupyRuinTrigger` |
| Tile | `OnTileAffinityChangedTrigger` |
| Resources | `OnSPGainedTrigger`, `OnSPSpentTrigger`, `OnSTGainedTrigger`, `OnSTSpentTrigger` |
| Card zone | `OnCardDrawnTrigger`, `OnCardDiscardedTrigger`, `OnCardReturnedToHandTrigger`, `OnCardReturnedToDeckTrigger`, `OnDeckShuffledTrigger`, `OnCardsRevealedTrigger` |
| Effect lifecycle | `OnTargetedByAbilityTrigger`, `OnEffectAppliedTrigger`, `OnEnterAuraRangeTrigger`, `OnLeaveAuraRangeTrigger` |
---
## 18. Network Message Flow
### Active ability activation
```
Client → server: "game.activate_ability"
Payload: { SessionId, SourceInstanceId, AbilityIndex, Targets[] }
GameActivateAbilityHandler.HandleAsync() (GameActivateAbilityHandler.cs line 35)
→ GameEngine.ActivateAbility()
→ AbilitySystem.ActivateAbility() (AbilitySystem.cs line 85)
→ [execute or pause with Pending* field]
→ SaveStateAsync() + PushStateToPlayersAsync()
→ PushPendingPromptsAsync() (GameHandlerBase.cs line 400)
Server → client: "game.activate_ability.ack"
Payload: { GameStateDto }
Optional: "game.visual.ability_placeholder" (when no custom animation asset)
Payload: { SourceId, TargetMode, TargetCoords, AffinityColor }
```
### Triggered ability needing targets
```
Server → client: "game.ability.triggered_target_request"
Payload: { RequestId, SourceInstanceId, AbilityName, ActionJson, RangeJson }
Client → server: "game.triggered_target"
Payload: { SessionId, RequestId, Targets[] }
GameTriggeredTargetHandler.HandleAsync() (GameTriggeredTargetHandler.cs line 37)
→ AbilitySystem.ResumeTriggeredAbility() (AbilitySystem.cs line 1874)
Server → client: "game.triggered_target.ack" + full state push
```
### Interactive prompts pushed by `PushPendingPromptsAsync()` — `GameHandlerBase.cs` line 400
| Pending State | Message sent to client |
|---|---|
| `PendingTriggeredTarget` | `"game.ability.triggered_target_request"` |
| `PendingCostPick` | `"game.ability.cost_pick_request"` |
| `PendingCostGroupPick` | `"game.ability.cost_group_pick_request"` |
| `PendingActionGroupPick` | `"game.ability.action_group_pick_request"` |
| `PendingBranchPick` | `"game.ability.branch_pick_request"` |
| `PendingTargetPick` | `"game.ability.target_pick_request"` |
| `PendingTilePick` | `"game.ability.tile_pick_request"` |
| `PendingPlayerPick` | `"game.ability.player_pick_request"` |
| `PendingRevealChoicePick` | `"game.ability.reveal_choice_pick_request"` |
---
## 19. Client-Side Targeting
**File:** `Client/origin-client/scenes/game/components/selection/ability_targeting.gd`
### State variables (lines 30–56)
```gdscript
var ability_unit_id # source unit ID
var ability_idx # ability index on source unit
var ability_def # normalized action array from parsed JSON
var ability_range # { min, max, linearonly, requireslos }
var ability_targets # collected AbilityTarget dicts to send to server
var ability_cur_action_idx # current action index being targeted
var is_triggered_target # triggered ability path
var triggered_request_id
var is_target_pick # server-driven target pick path
var is_tile_pick
var pending_req_id
```
### Key methods
**`show_ability_panel(unit_id, unit)`** — line 74:
- Parses `abilitiesJson`, collects Active abilities
- Adds ArchSpirit actions (Sacrifice / Ascend / Transition) if applicable
- Builds `PanelContainer` with buttons; checks `abilityUsesThisTurn` vs `usesPerTurn` to grey out exhausted abilities
**`start_ability_targeting()`** — line 261:
Entry point after user clicks an ability button. Walks actions sequentially:
```
for each action in ability_def.actions:
if ChooseOne → show_branch_panel()
elif scope in ["Player","Hand","Deck","Discard","AnyZone"] → show_player_panel()
elif ownership in [Self, ExactSelf, Random, Target] or All==true → skip, advance
else → board selection mode:
highlight_ability_targets(action)
wait for user click
```
**`highlight_ability_targets(action)`** — line 326:
```
Tile type:
for each tile on board:
check TileFilter (incl. SummonToken.tileFilter)
check range, LOS
→ emit highlight_add_requested
Unit type:
collect enemy/friendly units
filter by: type, ownership, filter[], range, LOS
→ emit highlights
```
**`is_valid_board_target(coord, unit_id)`** — line 407:
- Validates a specific click against the current action's constraints
- Checks: type match, ownership, filters, range (Manhattan + LinearOnly + LOS), count limits
**`send_ability()`** — line 679:
- Triggered path → `Game.send_triggered_target_response(rid, targets)`
- Target pick path → `Game.send_target_pick_response(rid, targets)`
- Card play → `Game.send_play_card_with_targets(card_id, targets)`
- Normal ability → `Game.send_activate_ability(unit_id, idx, targets)`
**`on_triggered_target_request(req)`** — line 699:
- Handles server push for triggered abilities needing targets
- Normalizes action JSON; calls `start_ability_targeting()`
**`get_ability_actions(ab)`** — line 856:
- Extracts flat action list from legacy `actions` or `actiongroup`
- Flattens AND groups via `flatten_and_group()`
**`normalize_keys(value)`** — line 841:
- Recursively lowercases all Dictionary keys
- Handles case inconsistencies from server JSON serialization
### Client targeting flow
```
Player clicks unit
→ show_ability_panel() display ability buttons with availability
Player clicks ability button
→ start_ability_targeting() walk actions, determine target mode
For board-targeted actions:
→ highlight_ability_targets() highlight valid cells
Player clicks a cell/unit
→ is_valid_board_target() validate click
→ collect into ability_targets
→ advance to next action or send_ability()
For zone-targeted actions:
→ show_player_panel() show hand/deck/discard UI
Player selects card
→ collect into ability_targets
→ advance to next action or send_ability()
send_ability()
→ Game.send_activate_ability(unit_id, idx, targets)
→ server processes; state pushed back
```
---
## 20. Client Visual Effects
**File:** `Client/origin-client/scenes/game/components/effects/ability_placeholder_fx.gd`
Triggered when server sends `"game.visual.ability_placeholder"` (no custom animation asset present).
Dispatches by `targetMode` field:
| targetMode | Effect |
|---|---|
| `"Self"` / `"None"` | `_play_self_burst()` — expanding rings + radial motes at source position |
| `"Unit"` | `_spawn_projectile()` — orb travels from source to target unit's body position |
| `"Tile"` | `_spawn_projectile()` — orb travels to tile world coordinate |
| `"PlayerZone"` | `_spawn_projectile()` — orb travels to target player's ArchSpirit |
Visual details:
- Uses affinity color from `GameConstants.AFFINITY_COLORS`
- Uses player team color for differentiation
- All meshes created procedurally: `SphereMesh` orbs, `TorusMesh` rings
- Materials: emissive `StandardMaterial3D`
---
## 21. Resume Paths (Paused Abilities)
When `HasPendingInteraction()` is true, execution is suspended. The corresponding handler resumes it after client responds.
| Handler File | Server Resume Method | Line | Resumes |
|---|---|---|---|
| `GameTriggeredTargetHandler.cs` | `ResumeTriggeredAbility()` | 1874 | `PendingTriggeredTarget` |
| `GameTargetPickHandler.cs` | `ResumeTargetPick()` | 1610 | `PendingTargetPick` |
| `GameActionGroupPickHandler.cs` | `ResumeActionGroupPick()` | 1081 | `PendingActionGroupPick` |
| `GameBranchPickHandler.cs` | `ResumeBranchPick()` | 933 | `PendingBranchPick` |
| `GameCostPickHandler.cs` | `ResumeCostPick()` | 822 | `PendingCostPick` |
| `GameCostGroupPickHandler.cs` | `ResumeCostGroupPick()` | 686 | `PendingCostGroupPick` |
| `GameTilePickHandler.cs` | `ResumeTilePick()` | 1280 | `PendingTilePick` |
| `GamePlayerPickHandler.cs` | `ResumePlayerPick()` | 1434 | `PendingPlayerPick` |
| `GameRevealChoicePickHandler.cs` | `ResumeRevealChoicePick()` | 1199 | `PendingRevealChoicePick` |
All resume methods follow the same pattern:
1. Validate the `RequestId` matches the stored pending state
2. Validate player identity (only the correct player can respond)
3. Apply the player's choice to `AbilityContext` / `GameState`
4. Clear the `Pending*` field
5. Re-enter `ExecuteActions()` with remaining actions
---
## 22. Key Cross-File Connections
```
GameActivateAbilityHandler (Handlers/)
→ GameEngine.ActivateAbility()
→ AbilitySystem.ActivateAbility() (AbilitySystem.cs:85)
AbilitySystem.ActivateAbility()
→ ValidateSourceActivationConditions()
→ PreValidateClientTileTargets()
→ GetEffectiveActions() → ResolveActionGroup()
→ PayCostGroup() / PayCosts()
→ ExecuteActions()
→ ExecuteSingleAction()
→ ResolveTargets()
→ BuildCandidates()
→ FilterTargetsByAbilityRange()
→ ExecuteEffect() (per effect type)
→ TrackEffect() (non-instant/non-permanent)
GameHandlerBase.PushPendingPromptsAsync()
← called after EVERY state mutation
→ pushes interactive prompts to clients for all Pending* fields
GameState.HasPendingInteraction()
← checked at every loop iteration in ExecuteActions()
→ stops execution when any Pending* field is set
Passive/Aura enter sequence (always in this order):
EvaluateAurasOnEnter() (AbilitySystem.cs:5276)
ApplyPassivesForSource() (AbilitySystem.cs:5090)
ApplyPassivesToNewTarget()(AbilitySystem.cs:5116)
ActiveEffects list on GameState
← persistence layer for all non-Instant, non-Permanent tracked effects
← decremented/expired during EndTurn processing
AbilityContext (AbilityContext.cs)
← shared runtime carrier throughout entire execution chain
Fields: State, ActorId, Source, ResolvedTargets,
EventData, ContinuationActions, ActivationRange
```
---
## File Index
| File | Role |
|---|---|
| `Server/src/SOR.Game/Abilities/AbilitySystem.cs` | Core engine — all ability parsing, execution, targeting, effect application (~5500+ lines) |
| `Server/src/SOR.Game/Abilities/AbilityContext.cs` | Runtime context; `TriggerEventData`; `TriggerEventKind` enum |
| `Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs` | Top-level data model |
| `Server/src/SOR.Game/Abilities/Models/Action.cs` | `Action`, `TargetSelector`, `ActionGroup`, `CostEntry`, `CostGroup`, `AbilityRange`, `ValueExpr` |
| `Server/src/SOR.Game/Abilities/Models/Effects.cs` | All 60+ concrete `Effect` subclasses |
| `Server/src/SOR.Game/Abilities/Models/Conditions.cs` | All `Condition` subclasses (~35 types) |
| `Server/src/SOR.Game/Abilities/Models/Triggers.cs` | All `TriggerEvent` subclasses (~40 types) |
| `Server/src/SOR.Game/Abilities/Models/Filters.cs` | All `Filter` subclasses (~25 types) |
| `Server/src/SOR.Game/Abilities/Models/DurationModel.cs` | `DurationType` enum + `DurationModel` class |
| `Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs` | JSON polymorphic deserializer for `Effect` |
| `Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs` | `game.activate_ability` message handler |
| `Server/src/SOR.Game/Handlers/GameTriggeredTargetHandler.cs` | `game.triggered_target` message handler |
| `Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs` | `game.target_pick` message handler |
| `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` | Shared handler infrastructure + `PushPendingPromptsAsync` |
| `Server/src/SOR.Game/GameState.cs` | `GameState` (all pending pause fields), `PlayerState`, `CardInstance` |
| `Client/origin-client/scenes/game/components/selection/ability_targeting.gd` | Full client targeting UI state machine |
| `Client/origin-client/scenes/game/components/effects/ability_placeholder_fx.gd` | VFX for abilities without custom animations |
| `Client/origin-client/scenes/collection/components/ability_row.gd` | UI row for displaying ability info in collection |