docs(plan): add NewCard + Ability System revamp implementation plan

Phase breakdown covering: ability model expansion (cost groups, 12 new
conditions, 15 new effects, trigger enrichments, filter additions),
DB migration, mobile-first card editor revamp, visual node-canvas
ability builder, and engine update work items.

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-04-19 11:05:56 -04:00
co-authored by Claude Happy
parent 8f3911e881
commit f31aa1f477
+448
View File
@@ -0,0 +1,448 @@
# NewCard + Ability System Revamp — Implementation Plan
> **Status:** Planning
> **Target branch:** `feature/newcard-ability-revamp`
> **Files to delete before starting:** `AbilityBuilderR2-Draft.razor`, `AbilityBuilderR3.razor`
---
## Overview
Three parallel workstreams that feed into each other:
1. **Ability Model Expansion** — fill gaps in C# domain models and JSON schema so the engine can represent every ability described in the spec.
2. **Card Editor Revamp** — replace the current tabbed form with a mobile-friendly, type-contextual wizard.
3. **Visual Ability Builder** — replace the raw-JSON / form-based `AbilityBuilder.razor` with a drag-and-drop node canvas.
Database migrations sit between 1 and 2/3 and must land first.
---
## Phase 0 — Cleanup
| # | Task | File(s) |
|---|------|---------|
| 0.1 | Delete draft razor pages | `AbilityBuilderR2-Draft.razor`, `AbilityBuilderR3.razor` |
| 0.2 | Verify no router references remain to deleted pages | `NavMenu.razor`, routing scan |
| 0.3 | Create feature branch `feature/newcard-ability-revamp` | git |
---
## Phase 1 — Ability Model Expansion (C# + JSON Schema)
### 1.1 — Cost Groups (AND / OR / XOR)
**Current state:** `AbilityDefinition.Cost` is `CostEntry[]` — all entries are paid simultaneously (implicit AND).
**Gap:** The spec requires OR/XOR cost groups so players can choose between payment options (e.g. *pay 2 SP + discard 3 cards* **OR** *pay 6 SP + 1 ST*).
**Changes to `Action.cs`:**
```
CostGroup {
LogicOp: And | Or | Xor
Entries: CostEntry[] // leaf costs
Groups: CostGroup[] // nested groups
// For Or/Xor: ChooserRole Self | Opponent | Random
ChooserRole: string = "Self"
}
```
Replace `AbilityDefinition.Cost: CostEntry[]?` → `AbilityDefinition.CostGroup: CostGroup?`
Keep `CostEntry[]` as the leaf node inside `CostGroup`.
`CostEntry` gains no changes (already has `PickMode` for interactive pick).
### 1.2 — Condition Additions
**Gap vs spec (new conditions to add to `Conditions.cs`):**
| New Condition | Purpose |
|---|---|
| `UnitTypeIsCondition` | `Spirit \| ArchSpirit \| SpiritToken` |
| `OwnershipIsCondition` | Is unit owned by Self / Ally / Opponent? |
| `IsThisCardCondition` | Subject == the source card instance (ExactSelf already partially covered by `TargetOwnership.ExactSelf` but needed as a standalone Condition) |
| `UnitPropertyCompareCondition` | Generic: `PropertyName` + `Comparator` + `ValueExpr` — covers Damage/Defense/HP/MP comparisons not covered by existing typed conditions |
| `PlayerPropertyCompareCondition` | Generic player resource compare: SP, ST, SPAccumulation, HandSize, DeckSize, DiscardSize + `Comparator` + `ValueExpr` |
| `HandContainsCountCondition` | N cards of type/affinity in hand ≥/≤/=/etc |
| `CardDefinitionCountInZoneCondition` | X copies of this definition in Battlefield/Hand/Deck/Discard of Any/Ally/Opponent/Self |
| `IsInRangeOfUnitCondition` | Source is within [Min,Max] of a unit matching `UnitType` + `Ownership` + optional property filters |
| `TileOccupantCondition` | Tile (subject is tile) occupied by unit matching type, ownership, properties |
| `SurroundingTileCondition` | At least N surrounding tiles within [Min,Max] match affinity/occupancy filters |
| `SPAccumulationCompareCondition` | Compares SP-accumulation-per-turn against value |
| `CostOfCardsInHandCondition` | Aggregate cost (by type, affinity) in hand meets comparator |
**Existing composites (AND/OR/XOR/NOT) already exist — no change needed.**
### 1.3 — Trigger Event Additions / Enrichments
Most trigger types already exist. The following enrichments are needed:
| Trigger | Gap | Fix |
|---|---|---|
| All unit-event triggers (`OnUnitMove`, `OnUnitAttack`, etc.) | Subject filter only does ownership string; spec requires "unit with N properties ≥/≤/= Y" | Add `Filter[]? UnitFilters` to each (already present on some) |
| `OnChanneledTrigger` | Missing `DefinitionId` (specific card) filter | Add `Guid? CardDefinitionId` optional field |
| `OnRuinActivationTrigger` | Missing occupant filter | Add `Filter[]? OccupantFilters` |
| `OnUnitOccupyRuinTrigger` | Missing occupant filter | Add `Filter[]? OccupantFilters` |
| `OnCardReturnedToDeckTrigger` | Missing `ResetStatsToDefinition` observation flag | Add `bool? ResetStats` (for UI display only) |
| `OnDamageDealtTrigger` / `OnHealedTrigger` / etc. | Already have amount compare via event data; verify `AmountComparator` & `Amount` fields present | Audit & add if missing |
### 1.4 — Effect Additions
**New effects to add to `Effects.cs`:**
| Effect | Category | Notes |
|---|---|---|
| `CloneSpiritAsTokenEffect` | §5.11 Token | Clone source Spirit to SpiritToken; `DestinationScope` = NeighborTile \| RandomInChannelRange \| TargetTile |
| `AscendFromZoneEffect` | §5.1 ArchSpirit | `Zone`: Hand \| Deck \| Discard; `IgnoreCost: bool` — unified replacement for future AscendFrom* variants |
| `TransitionFromZoneEffect` | §5.1 ArchSpirit | Same pattern as Ascend |
| `ModifyChannelRangeEffect` | §5.1 ArchSpirit | Min/Max delta (replaces missing `ModChannelRange`) |
| `RelocateRuinEffect` | §5.13 Ruin | Move Ruin to target tile |
| `ActivateRuinAbilityEffect` | §5.13 Ruin | `AbilityRef` or `Random: bool`; `ChooseAllTargets: bool` |
| `DisableRuinForDurationEffect` | §5.13 Ruin | `Duration: DurationModel` |
| `ChannelCardFromZoneEffect` | §5.7 Zone | Unified ChannelCard with `Zone`, `UnderControlOf`, `IgnoreChannelCost`, `IgnoreTurnConstraint`, `IgnoreChannelRange`, `IgnoreAffinity`, `KeepInZone`, `TargetTile`, `InOwnChannelRange`, `InTargetChannelRange` flags |
| `ModifySacrificeTokenReturnEffect` | §5.10 Control | Override ST returned on Spirit sacrifice |
| `DestroyTokenEffect` | §5.11 Token | Destroy a SpiritToken |
| `SkipTurnEffect` | §5.5 Player | Target player skips their next turn |
| `ModifyCardsDrawnThisTurnEffect` | §5.5 Player | Delta for current-turn draw; complements existing `ModifyCardsDrawnPerTurnEffect` |
| `StackDeckEffect` | §5.7 Zone | Reorder top N cards of deck |
| `SearchAndPlaceEffect` | §5.7 Zone | Composite search → put cards into Hand/Deck/Discard with shuffle option |
| `ChangeAttackTypeEffect` | §5.9 Unit | Change Melee↔Ranged etc. |
| `ObstructMovementTypeEffect` | §5.9 Unit | Act as obstacle for given movement type |
| `PreventNextDamageEffect` | already exists — needs `Times` field | Add `int Times = 1` |
| `PreventDeathEffect` | already exists — needs `DamageTakenSetToHP` + `DamageIgnored` | Add opt fields |
**Consolidation note:** `ChannelCardEffect` in current `Effects.cs` is minimal. `ChannelCardFromZoneEffect` will supersede it; the old type stays for backwards compatibility but is marked `[Obsolete]` and the builder will not emit it.
### 1.5 — Filter Additions (`Filters.cs` audit)
Review `Filters.cs` to ensure these filter types exist (add if missing):
- `CardTypeFilter` — filter Hand/Deck/Discard cards by `CardType`
- `AffinityFilter` — filter by card affinity
- `CostRangeFilter` — filter by SP/ST cost range
- `GenusFilter` — filter by genus tag
- `OwnershipFilter` — filter by unit ownership
- `UnitPropertyFilter` — generic property comparator on a unit
- `TileAffinityFilter` — filter tiles by Base1, Base2, Resolved affinity
- `TileOccupancyFilter` — filter tiles by occupant type/ownership/properties
- `RangeFilter` — target must be within [Min,Max] tiles of source
- `OccupancyTypeFilter` — tile occupied by Spirit/ArchSpirit/SpiritToken/Ruin
### 1.6 — `AbilityDefinition` additions
```csharp
// Passive / Aura
public string? Name { get; set; } // already exists ✓
public string? Description { get; set; } // already exists ✓
// Aura
// AuraRange, ClearOnLeave, LingerDuration already exist ✓
// Add: OnEnterActions / OnLeaveActions for per-unit aura entry/exit effects
public Action[]? OnEnterAuraActions { get; set; }
public Action[]? OnLeaveAuraActions { get; set; }
// Triggered
// TriggerLimitPerTurn, TriggerLimitPerGame, SourceZoneGate already exist ✓
// Active — cost group (replaces Cost array)
public CostGroup? CostGroup { get; set; } // NEW — replaces Cost
// Keep Cost for migration read; mark [Obsolete()] + reader falls back on parse
```
---
## Phase 2 — Database Migration
| # | Migration | Notes |
|---|---|---|
| 2.1 | Add `CardType.SpiritToken` enum value | Engine already conceptually has tokens; needs to be a proper DB-storable `CardType` so custom token definitions can be persisted |
| 2.2 | Deprecate `EffectsJson` column | `AbilitySystem` already reads both; complete the read fallback in code so all writes go to `AbilitiesJson`. Schedule a `UPDATE cards SET abilities_json = effects_json WHERE abilities_json IS NULL` data migration. |
| 2.3 | Add `CardDefinition.RequiresLos` note | Field already exists (`RequiresLos: bool?`) — only a UI gap (see Phase 3) |
| 2.4 | Rename / alias `OtherCostsJson` → managed by `CostGroup` on `AbilityDefinition` | No DB column change needed; `OtherCostsJson` on CardDefinition was for card-level channel costs — confirm not duplicated with ability cost and document |
**Schema version**: bump `DefinitionVersion` trigger covers all card changes automatically.
**EF migration file**: `Migrations/20260420_AbilityRevamp.cs`
---
## Phase 3 — Card Editor Revamp (`CardEditor.razor`)
### Design Principles
- Mobile-first: single-column by default, two-column on md+
- Type-contextual: sections and fields appear/disappear based on `CardType`
- Progressive disclosure: collapse optional sections, expand on demand
- No separate "Stats" tab for non-unit cards (Repentance/Instinct only show what they need)
### 3.1 — Step 1: Core Info (all card types)
Fields always shown:
- Name
- Card Type (select) — changing type rerenders the rest of the form reactively
- Affinity
- Description (art description textarea)
- SP Cost / ST Cost
### 3.2 — Step 2: Type-Specific Stats
**If `CardType == ArchSpirit`:**
- Min/Max Channel Range
- Tier (1–5)
- Previous Tier search autocomplete (ArchSpirit 1 tier lower) — already implemented, keep
**If `CardType` is `ArchSpirit | Spirit | SpiritToken`:**
*Combat section:*
- Attack Type (None / Melee / Ranged)
- If Ranged: Min/Max Attack Range
- Damage, Health Points, Defense
*Movement section:*
- Movement Type (None / Walk / Fly / …)
- Movement Points
*Capability flags (checkbox grid):*
- CanAttack / CanDefend / CanBeAttacked / CanBeBlocked
- CanMove / CanBeObstructed / CanUseAbility / RequiresLOS
- CanBeSacrificed (Spirit + SpiritToken only)
*Genus Tags:*
- Typeahead + free create, already implemented — keep
**If `CardType == Terramorpha`:**
- TerramorphaMode
**If `CardType == Repentance | Instinct`:**
- RequiresLOS checkbox (currently missing from UI for these types)
### 3.3 — Step 3: Abilities
See Phase 4. The "Abilities" tab becomes the visual builder embedded in the same page.
Rules per CardType:
| CardType | Allowed Ability Types |
|---|---|
| Spirit, ArchSpirit, SpiritToken, Ruin | Active, Triggered, Aura, Passive |
| Instinct, Repentance | Active, Triggered |
| Terramorpha | Active, Triggered |
Auto-name rule: if `CardType == Repentance | Instinct`, the first ability's Name is locked to the card Name.
### 3.4 — Step 4: Assets
No change from current implementation. Already well-structured.
### 3.5 — Implementation Notes
- Replace tab array `["Basic", "Stats", "Abilities", "Assets"]` with a collapsible-section layout (Bootstrap accordion or manual open/close) so all sections are visible on scroll on mobile.
- Each section has a sticky header showing completion status (green check if required fields filled).
- Keep existing CDN picker modal unchanged.
---
## Phase 4 — Visual Ability Builder
### 4.1 — Architecture
The builder is a self-contained Blazor component `AbilityBuilder.razor` that:
- Accepts `AbilitiesJson` string (in) + `AbilitiesJsonChanged` callback (out) — **same interface as today** so `CardEditor.razor` needs zero changes for the swap.
- Internally maintains a `List<AbilityDraft>` that compiles to JSON on every meaningful change.
- The canvas is rendered in a `<div>` with CSS `position:relative`/`overflow:auto` and nodes are `position:absolute` — no WebGL, no external JS canvas library, pure CSS+Blazor drag.
### 4.2 — Node Types
Each ability is its own independent mini-canvas. The top-level layout shows a card per ability with a mini node graph inside.
```
┌─────────────────────────────────────────┐
│ [Active] "Strike" [×] │
│ ┌──────┐ ┌──────────┐ ┌──────────┐ │
│ │ Cost │→ │ Condition│→ │ Action │ │
│ └──────┘ └──────────┘ └──────────┘ │
│ │ │
│ ┌──────────┐ │
│ │ Effect │ │
│ └──────────┘ │
└─────────────────────────────────────────┘
```
Node palette (left drawer, collapsible):
- **Trigger** (Triggered abilities): event picker
- **Cost** (Active only): CostGroup builder (AND/OR/XOR nesting)
- **Condition**: condition group builder (AND/OR/XOR already supported in model)
- **Action**: target selector + effect list
- **Effect**: specific effect type with its parameters
### 4.3 — Node Design
Each node is a `<div class="ability-node ability-node--{type}">` with:
- Header bar (color-coded by node type, drag handle)
- Body (type-specific form fields)
- Input port (left) / Output port (right) — `<div class="node-port">`
Connection lines are SVG `<path>` elements rendered in an overlay `<svg>` sibling.
Drag mechanics:
- `onmousedown` on header stores `(nodeId, offsetX, offsetY)` in component state
- `onmousemove` on canvas updates node position
- `onmouseup` clears drag state
- Touch equivalent: `ontouchstart/move/end` for mobile
Zoom + pan:
- Canvas wraps in a `<div>` with CSS `transform: scale(zoom) translate(panX, panY)`
- Pinch-to-zoom via JS interop (`wheel` event, touch distance delta)
- Small JS file: `ability-builder.js` (zoom/pan math, port hit-test for connection dragging)
### 4.4 — Panels
**Left panel — Ability List + Node Palette:**
- List of all abilities on this card; click to focus that ability's canvas
- "Add Ability" button → opens "Choose Type" modal
- Node palette grouped: Trigger / Cost / Condition / Action / Effect
**Center — Canvas:**
- One ability's node graph at a time
- Nodes draggable; connections drawn as bezier SVG paths
- Clicking a node selects it and opens the right panel
**Right panel — Property Inspector:**
- Dynamic form for the selected node's properties
- Rendered via a big `@switch (selectedNode.Type)` block
- Inline add/remove for list-valued properties (e.g. CostEntry items within a CostGroup)
**Bottom bar — JSON Preview (collapsible):**
- Read-only `<textarea>` showing compiled JSON for the current ability
- Useful for debugging; not for direct editing in this tool
### 4.5 — Ability Type–Specific Canvases
**Active ability canvas layout (left → right flow):**
```
[AbilityMeta] → [CostGroup?] → [ActivationCondition?] → [Action 1..N]
↓
[Effect 1..N]
```
**Triggered ability canvas:**
```
[AbilityMeta] → [TriggerEvent] → [TriggerCondition?] → [Action 1..N]
↓
[Effect 1..N]
```
**Passive / Aura ability canvas:**
```
[AbilityMeta] → [ActivationCondition?] → [Action 1..N (applied while active)]
```
For Aura: `[AuraRange]` node sits between Meta and Condition.
`[OnEnterActions]` and `[OnLeaveActions]` are separate branches.
### 4.6 — CostGroup Sub-Builder (nested in Cost node)
A recursive component `<CostGroupEditor>` renders:
- `LogicOp` selector: AND | OR | XOR
- For OR/XOR: `ChooserRole` selector: Self | Opponent | Random
- List of leaf `CostEntry` rows (each row: Type + Amount + optional PickMode + optional Filters)
- "Add Cost" + "Add Group" buttons for nesting
### 4.7 — Condition Group Sub-Builder
Uses existing `AndCondition / OrCondition / XorCondition / NotCondition` model.
Recursive `<ConditionGroupEditor>` component:
- Top-level `LogicOp` selector
- Each child is either a leaf condition (type + parameters) or a nested group
### 4.8 — Action Builder (inside Action node)
- `TargetSelector` form: Scope → Type → Ownership → Count (N / UpTo / All) → Filters
- Duration picker
- `Conditions[]` (same `<ConditionGroupEditor>`)
- `Effects[]` list — each effect is an effect-type picker + inline parameter form
- `ChooseOne?` toggle — when enabled, effects list becomes a branch list, each branch having its own action list
### 4.9 — Effect Sub-Forms
Each effect type (`DealDamage`, `Heal`, `ModifyStat`, `ChannelCard`, etc.) gets a compact form panel inside the Effect node. The panel is selected via `@switch` on `effect.$type`.
`ValueExpr` fields render as a two-mode control: **Fixed** (number input) | **Ref** (string input with `${}` hint), toggled by a small button.
### 4.10 — Mobile Considerations
- On narrow screens (`< 768px`) left and right panels collapse into a bottom sheet
- Canvas fills full width; node size increases slightly for touch targets
- "Add node" FAB (floating action button) opens the node palette as a modal bottom sheet
- Long-press on a node = select; drag from node header
---
## Phase 5 — AbilitySystem.cs Engine Updates
These changes make the engine process the new schema. Each item is independent of Phase 3/4 and can be developed in parallel with the UI work.
| # | Change | Notes |
|---|---|---|
| 5.1 | Read `CostGroup` from `AbilityDefinition`; resolve OR/XOR cost paths, send client pick request | Interactive OR/XOR costs require client round-trip; add `PendingCostGroupPick` alongside existing `PendingCostPick` |
| 5.2 | Implement `CloneSpiritAsTokenEffect` | Use existing SummonToken infrastructure; source stats copied from Spirit target |
| 5.3 | Implement `AscendFromZoneEffect` / `TransitionFromZoneEffect` | Reuse ArchSpirit tier logic; zone lookup before ascend |
| 5.4 | Implement `ModifyChannelRangeEffect` | Apply delta to unit's current channel range runtime state |
| 5.5 | Implement `RelocateRuinEffect` / `ActivateRuinAbilityEffect` / `DisableRuinForDurationEffect` | New Ruin manipulation actions |
| 5.6 | Implement `ChannelCardFromZoneEffect` with all flags | Deprecate minimal `ChannelCardEffect`; engine dispatches new version |
| 5.7 | Implement new Condition types (§1.2) | Evaluator `switch` in `ConditionEvaluator.cs` |
| 5.8 | Implement new Filter types (§1.5) | Filter resolver in `FilterResolver.cs` |
| 5.9 | Implement `OnEnterAuraActions` / `OnLeaveAuraActions` | Fire when a unit enters/leaves aura range |
| 5.10 | `SkipTurnEffect` / `ChangeAttackTypeEffect` / `ObstructMovementTypeEffect` | Runtime flag application |
| 5.11 | `UnitFilters` on all enriched TriggerEvent types (§1.3) | Trigger evaluation: after ownership check, apply unit filters |
| 5.12 | Handle `SpiritToken` as a full CardType in channeling + combat paths | Currently tokens are runtime-only; custom token definitions via `CardDefinition` now possible |
---
## Phased Delivery Order
```
Phase 0 (cleanup)
↓
Phase 1 (model expansion — no DB change, pure C#)
↓
Phase 2 (DB migration)
↓
Phase 3 (Card Editor revamp) ← depends on Phase 2
Phase 4 (Visual Ability Builder) ← depends on Phase 1
↓
Phase 5 (Engine updates) ← depends on Phase 1 + Phase 2
```
Phases 3 and 4 can be developed concurrently once Phase 2 is done.
Phase 5 sub-items are independently mergeable after Phase 1 lands.
---
## Files Created / Modified Summary
| File | Action |
|------|--------|
| `SOR.Game/Abilities/Models/Action.cs` | Add `CostGroup`, `CostGroupLogicOp` |
| `SOR.Game/Abilities/Models/Conditions.cs` | Add 12 new condition types (§1.2) |
| `SOR.Game/Abilities/Models/Triggers.cs` | Enrich existing triggers with `UnitFilters`, occupant filters (§1.3) |
| `SOR.Game/Abilities/Models/Effects.cs` | Add 15 new effect types (§1.4) |
| `SOR.Game/Abilities/Models/Filters.cs` | Add 9 new filter types (§1.5) |
| `SOR.Game/Abilities/Models/AbilityDefinition.cs` | Add `CostGroup`, `OnEnterAuraActions`, `OnLeaveAuraActions` |
| `SOR.Database/Entities/Catalog/CardDefinition.cs` | Document `EffectsJson` deprecation; no column add needed |
| `SOR.Database/Enums/CardType.cs` | Add `SpiritToken` value |
| `SOR.Database/Migrations/` | New EF migration for SpiritToken enum |
| `SOR.Admin/Components/Pages/Cards/CardEditor.razor` | Revamp to accordion/wizard layout (Phase 3) |
| `SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor` | Replace with visual node builder (Phase 4) |
| `SOR.Admin/wwwroot/js/ability-builder.js` | New: zoom/pan/connection drag JS interop |
| `SOR.Game/Abilities/AbilitySystem.cs` | Phase 5 engine updates (iterative sub-PRs) |
| **DELETE** `AbilityBuilderR2-Draft.razor` | Phase 0 |
| **DELETE** `AbilityBuilderR3.razor` | Phase 0 |
---
## Open Questions / Decisions Needed
1. **SpiritToken CardType:** Custom token definitions stored as full `CardDefinition` rows (can be queried, versioned) vs inline JSONB blob in the ability's `SummonTokenEffect.TokenDefJson`. The spec says "Custom Token (configured same as new Card from this prompt)" which implies full CardDefinition. Recommend: add `CardType.SpiritToken` + allow token CardDefinitions; `SummonTokenEffect` gains `CardDefinitionId?` alongside existing `TokenDefJson` for inline.
2. **OR/XOR cost client protocol:** When an OR/XOR cost group is presented, the client must indicate which branch was chosen before the server can validate and deduct. Needs a new `PendingCostGroupPick` message type in the game protocol — this is a larger client-change surface than the existing cost flow. Confirm scope boundary (Phase 5.1).
3. **Drag-and-drop library vs custom:** Pure CSS/Blazor drag is feasible for a bounded canvas but adds ~200 lines of drag-state management. If there is an appetite to pull in a lightweight JS library (e.g. `interact.js` ~50KB), the interop layer becomes simpler. Recommend custom approach first; library swap is isolated.
4. **Backwards compatibility of `EffectsJson`:** Cards currently using `EffectsJson` (Repentance, Instinct, Terramorpha) will be dual-read during the migration window. Define a cutover date or keep the fallback permanently (low cost to keep).
5. **ChooseOne actor:** Currently `ChooseOne` is always resolved by the controlling player. The spec mentions Opponent-chooses and Random-chooses variants. `ChooseOne` needs a `ChooserRole` field (matches `CostGroup` pattern) — add in Phase 1.4 alongside the effect additions.