Skip to content

Combat, Rules Engine & Stealth Runtime Deep Dive ​

Elthoria separates deterministic Pathfinder 1e combat math (elthoria-rules-engine), framework-free encounter & stealth state machines (elthoria-gameplay-runtime), and idempotent, GM-scoped MCP/REST execution (CombatMcpTools, CombatActionMcpTools, StealthNpcMcpTools). Neither rules evaluation nor geometry ever depends on LLM prose.

TIP

Looking for the plain-English Game Master overview of running combat? Read How Combat, Movement & Stealth Work.


Module & Runtime Architecture ​

text
┌──────────────────────────────────────────────────────────────────────────────┐
│  MCP / REST Host Layer (`CombatMcpTools`, `CombatActionMcpTools`,            │
│                         `StealthNpcMcpTools`, `TacticalBoardMcpTools`)       │
│  • Campaign-scoped isolation (no cross-campaign tracker or stealth leaks)    │
│  • GM-only visibility gates (`playerSafe: false`) + idempotency receipts     │
└─────────────────────────┬──────────────────────────────┬─────────────────────┘
                          │                              │
                          ▼                              ▼
┌─────────────────────────────────────────┐ ┌──────────────────────────────────┐
│  `elthoria-gameplay-runtime`            │ │  `elthoria-rules-engine`         │
│  (Framework-free state machines)        │ │  (Pure PF1e rules & tactics)     │
│                                         │ │                                  │
│  • InitiativeRuntime                    │ │  • ActionEconomyTracker          │
│    (InitiativeStore, InitiativeRoster,  │ │  • CombatResolutionService       │
│     D20Roller, RoundAdvanceListener)    │ │  • NpcMeleeRoutine / Profile     │
│  • TimedEffectPolicy (round countdowns) │ │  • CombatManeuverService (11)    │
│  • StealthRuntime                       │ │  • GrappleStateMachine           │
│    (StealthStateStore, StealthRules,    │ │  • DamageApplicationService      │
│     per-character detection maps)       │ │  • DeathDyingService (5 states)  │
│  • SquarePerceptionGeometry             │ │  • SquareMovementGeometry        │
│    (exact integer supercover LOS)       │ │  • Encumbrance / Size / ASF /    │
│                                         │ │    Metamagic / SpellSlots / XP   │
│                                         │ │  • CombatTacticalDecisionService │
│                                         │ │    (Nested QBAF + QeSemantics)   │
└─────────────────────────────────────────┘ └──────────────────────────────────┘

1. Initiative & Timed Effects (elthoria-gameplay-runtime) ​

  • InitiativeRuntime:
    • Completely decoupled from Spring/JPA/HTTP behind explicit ports: InitiativeStore, InitiativeRoster, D20Roller, and RoundAdvanceListener.
    • Enforces strict campaign scoping (store.requireCampaign(gameId, true)), bounded rosters (MAX_ENTRIES = 10_000, MAX_TURNS = 100), and reload-stable deterministic ordering (totalInitiative DESC, id ASC).
    • Supports multi-turn creatures (Map<ActorKey, Integer> turns), mid-combat additions/removals, explicit initiative overrides, and forward/backward stepping (next_turn / previous_turn).
  • TimedEffectPolicy:
    • Pure per-round countdown policy invoked via RoundAdvanceListener: null represents permanent/legacy effects; positive counters decrement (next = max(0, remaining - 1)) and report expired = (next == 0).

2. Pathfinder 1e Action Economy & Combat Resolution (elthoria-rules-engine) ​

Action Economy (ActionEconomyTracker, ActionType) ​

Tracks per-turn PF1e action budgets cleanly:

  • STANDARD, MOVE (a second move automatically consumes the standard slot), FULL_ROUND (consumes standard + move), SWIFT & IMMEDIATE (shared swift budget; off-turn immediate use sets immediateUsedLastTurn, consuming the next turn's swift action), FREE, NOT_AN_ACTION, and 5-foot step (canFiveFootStep() requires !fiveFootStepUsed && !moveUsed && !fullRoundUsed).

Attack & Full-Attack Resolution (CombatResolutionService, NpcMeleeRoutine) ​

  • CombatResolutionService (gated by RuleToggleProvider):
    • Single strike resolveAttack(attackBonus, targetAC, critRange, critMultiplier, diceCount, dieSides, damageBonus): natural 1 auto-miss, natural 20 auto-hit, critical threat when hit && d20 >= critRange, strict RNG roll order (primary d20 → base damage → confirmation d20 → extra crit damage dice), and full-attack iteration across main-hand iteratives + off-hand attacks.
  • NpcMeleeRoutine & NpcMeleeProfile:
    • Strictly validates and parses bounded statblock melee lines (up to 20 strikes, verified against persisted Definitions) so iterative bonuses, critical ranges (20, 19-20, 18-20), multipliers (x2..x4), and damage terms are never silently dropped on import.

Combat Maneuvers & Grappling (CombatManeuverService, GrappleStateMachine) ​

  • CombatManeuverService: Resolves d20 + CMB vs CMD (natural 20 auto-success, natural 1 auto-fail) across all 11 PF1e maneuvers: BULL_RUSH, DIRTY_TRICK, DISARM, DRAG, GRAPPLE, OVERRUN, REPOSITION, STEAL, SUNDER, TRIP, FEINT.
  • GrappleStateMachine: Explicit 4-state transition machine:
    text
    FREE ──(grapple CMB)──► GRAPPLED ──(maintain + pin)──► PINNED ──(maintain + tie up)──► TIED_UP
      ▲                        │                              │                               │
      └────(CMB/Esc. Artist)───┴──────(CMB/Esc. Artist)───────┴──(DC 20 Esc. Art / DC 26 STR)─┘

Damage Pipeline & Death/Dying (DamageApplicationService, DeathDyingService) ​

  • DamageApplicationService: Processes multi-component DamagePackets — first applying typed energy resistances (max(0, raw - resistance)), then physical Damage Reduction (DR N/bypass, parsed via regex e.g. DR 5/cold iron and silver, DR 10/magic, DR 15/—) unless bypassed by attackProperties, returning detailed audit logs.
  • DeathDyingService: Evaluates the 5 PF1e HPStates:
    • HEALTHY (HP > 0), DISABLED (HP == 0), DYING (-CON < HP < 0, loses 1 HP/round + DC 20 CON check d20 + conMod >= 20 to stabilize), STABLE (unconscious, no bleed), and DEAD (HP <= -CON).
  • Supporting rules modules in elthoria-rules-engine: EncumbranceService (carry capacity + armor/load speed), SizeModifierService, ArcaneSpellFailureService, MetamagicEngine, SpellSlotsTable, ClassFeatureTable, FeatPrerequisiteValidator, and XPLevelingService.

3. Exact Square Movement & Line-of-Sight Geometry ​

Both grid geometry engines are pure, bounded, integer-exact, and never infer terrain from ASCII glyphs:

Ground Movement (SquareMovementGeometry) ​

  • Enforces grid bounds (1..512, area <= 65,536), path length (2..201), adjacency, explicit traversable and occupied sets, and positive 5-ft multiple allowances (<= 1,000 ft).
  • PF1e 5-10-5 alternating diagonals: Accepts priorDiagonalParity (0 → 5 ft, 1 → 10 ft) and advances alternation on every physical diagonal step without resetting on cardinal moves or terrain transitions.
  • Difficult terrain (square-single-cell-ground.v2): Entering a cell in difficultCells costs 10 ft cardinally or 15 ft diagonally (origin is not charged).

Perception & Line-of-Sight (SquarePerceptionGeometry) ​

  • Computes exact PF1e square distance (max(dx, dy) + min(dx, dy) / 2) * feetPerCell.
  • Uses an exact integer separating-axis supercover test (|2·Δx·(y - y₀) - 2·Δy·(x - x₀)| <= |Δx| + |Δy|) with zero floating-point tolerances: any opaque cell touching the centre-to-centre segment — including shared edges and exact corner touches (no diagonal corner peeking) — blocks sight, returning a deterministically sorted List<Cell> of all blockers.

4. AI Stealth State Machine (StealthRuntime) ​

  • Strictly campaign-scoped by (gameId, npcId) behind StealthStateStore and replayable D20Roller.
  • Manages physical visibility (hidden, visible, invisible, greater_invis), active Stealth checks (applying PF1e MOVING_INVIS_BONUS / STATIONARY_INVIS_BONUS, INVISIBLE_MIN_DC, and INVISIBLE_MISS_CHANCE), queued vs. executed round moves (plan_stealth_moves → execute_stealth_move), and per-character detection maps (detectedByCharacterIds, partyDetectionStatus) evaluated against SquarePerceptionGeometry.

5. Tactical Action Advisor (CombatTacticalDecisionService) ​

Uses Kompile's nested QBAF under smooth Quadratic-Energy (QeSemantics) gradual argumentation (recommend_combat_action):

text
  lowConfidence  ──(attack)──► impact   ──(support)──► action (CLAIM)
  weakEvidence   ──(attack)──► fit      ──(support)──► action (CLAIM)
  riskMitigation ──(attack)──► exposure ──(attack)───► action (CLAIM)
  resourceMitig. ──(attack)──► cost     ──(attack)───► action (CLAIM)
  • Inputs: TacticalCandidate (expectedDamage, controlValue, successProbability, exposureRisk, resourceCost, targetThreat, allyProtection, evidenceConfidence) + TacticalContext (aggression, protectiveness, riskTolerance, resourceAbundance) + optional learned kind weights (QbafWeightLearner).
  • Never bypasses PF1e legality — it ranks legal candidates and emits an explainable per-argument rationale (semantics=qe, impact=..., fit=..., confidence=..., exposure=..., cost=...).

6. GM-Only Safety & Idempotency Contracts ​

BoundaryEnforcement
GM-only snapshotsget_tactical_board, get_combat_command_state, and execute_combat_command carry audience: GM / playerSafe: false — never expose raw payloads to player views
Board edits vs. legal combat movesapply_tactical_board_command (expected_revision, command_id) performs GM setup/placement and configure-movement (square-single-cell-ground.v1 / .v2); execute_combat_command (adjudicate_npc_move, adjudicate_pc_move, adjudicate_npc_melee) enforces legal rules with idempotency receipts
Living-world bridgeCombat deaths or status changes propagate immediately into the living world via report_world_event (NPC_DEATH / PARTY_MEMBER_DEATH, immediateApplied = true) so world reactions run deterministically on the next weekly tick

Built on the upstream Kompile harness. Released under the MIT License.