# BPC_DeathHandlingSystem — Actor Component (Death Orchestrator)

**File:** [`Content/Framework/Save/BPC_DeathHandlingSystem`](Content/Framework/Save/BPC_DeathHandlingSystem.uasset)

**Purpose:** The single authority for the player death flow. Determines the death outcome (standard respawn, game over, or alt death space), manages the death animation/camera sequence, coordinates corpse persistence, tracks run history, and triggers respawn. Sits on the Player Controller alongside four sub-systems that each handle one death-related concern.

**Depends On:** [`SS_SaveManager`](35_SS_SaveManager.md), [`BP_Checkpoint`](BP_Checkpoint.md), [`BPC_HealthSystem`](../02-player/08_BPC_HealthSystem.md), [`GM_CoreGameMode`](../01-core/05_GM_CoreGameMode.md), [`BPC_AltDeathSpaceSystem`](BPC_AltDeathSpaceSystem.md), [`BPC_PersistentCorpseSystem`](BPC_PersistentCorpseSystem.md), [`BPC_PlayerRespawnSystem`](BPC_PlayerRespawnSystem.md), [`BPC_RunHistoryTracker`](BPC_RunHistoryTracker.md)
**Used By:** Player Controller (spawned by `GM_CoreGameMode`)

---

## Enums

```cpp
// E_DeathOutcome — Determined by game rules + player state at death moment
E_DeathOutcome
{
  StandardRespawn,   // Normal death at a checkpoint — full respawn
  GameOver,          // No respawn possible — screen shows game over / main menu
  AltDeathSpace      // Player enters the limbo / between-world death space
}

// E_DeathAnimationStage — Controls the death anim sequence timeline
E_DeathAnimationStage
{
  PreDeath,          // Brief pause before death anim (player can see the killer)
  DeathAnim,         // Death animation playing (screen fade, camera pull back)
  PostDeath,         // Screen fully dark, system state being evaluated
  RespawnTransition  // Fade-up to respawn location
}
```

---

## Structs

```cpp
// S_DeathContext — Captured at the moment of death for all sub-systems
S_DeathContext
{
  DeathLocation:      Vector       // World location where health hit 0
  KillerTag:          GameplayTag  // What caused the death (DamageType.Tag)
  bIsInHidingSpot:    Bool         // Was the player hiding when killed?
  bWasFearCritical:   Bool         // Was stress/fear at critical level?
  DeathTimestamp:     FDateTime    // UTC timestamp
  DeathCount:         Integer      // Running total (from BPC_PlayerMetricsTracker)
  CurrentCheckpoint:  GameplayTag  // Most recent checkpoint at death
  bHasAltDeathSpace:  Bool         // Can this death use alt death space?
}

// S_DeathOutcomeRules — Configurable rules for determining death outcome
S_DeathOutcomeRules
{
  bEnableAltDeathSpace:      Bool    // Master toggle for alt death space feature
  MaxStandardDeaths:         Integer // After X standard deaths, force GameOver
  MaxAltDeathSpaceEntrances: Integer // After Y alt space entrances, force GameOver
  AltDeathSpaceCheckpoint:   GameplayTag  // Which checkpoint to respawn to after alt space
  bGameOverOnBossDeath:      Bool    // Boss kills always trigger game over
  bGameOverInNarrativeClimax:Bool    // Death at narrative climax = game over
}
```

---

## Core Component Variables (BPC_DeathHandlingSystem)

| Name | Type | Description |
|------|------|-------------|
| `DeathContext` | `S_DeathContext` | Captured at death moment; used by all sub-systems |
| `OutcomeRules` | `S_DeathOutcomeRules` | Configurable rules for outcome determination |
| `CurrentOutcome` | `E_DeathOutcome` | The determined death outcome |
| `AnimStage` | `E_DeathAnimationStage` | Current stage of the death animation sequence |
| `bIsDying` | Bool | True from death trigger until full respawn |
| `bIsRespawning` | Bool | True during the respawn process |
| `ActiveAltDeathSpaceSystem` | BPC_AltDeathSpaceSystem | Reference to sub-system component (must be on same actor) |
| `ActiveCorpseSystem` | BPC_PersistentCorpseSystem | Reference to sub-system component |
| `ActiveRespawnSystem` | BPC_PlayerRespawnSystem | Reference to sub-system component |
| `ActiveRunHistory` | BPC_RunHistoryTracker | Reference to sub-system component |

---

## Core Functions (BPC_DeathHandlingSystem)

| Name | Inputs | Outputs | Description |
|------|--------|---------|-------------|
| `OnPlayerDeath` | KillerTag: GameplayTag, DamageAmount: Float | — | Entry point — called by BPC_HealthSystem when HP reaches 0 |
| `DetermineDeathOutcome` | Context: S_DeathContext | E_DeathOutcome | Evaluates rules to decide StandardRespawn / GameOver / AltDeathSpace |
| `ExecuteDeathSequence` | Outcome: E_DeathOutcome | — | Drives the full death animation timeline |
| `ExecuteStandardRespawn` | Context: S_DeathContext | — | Saves death state, runs respawn via BPC_PlayerRespawnSystem |
| `ExecuteGameOver` | Context: S_DeathContext | — | Saves run history, triggers game over UI, disables input |
| `ExecuteAltDeathSequence` | Context: S_DeathContext | — | Spawns corpse, enters alt death space via BPC_AltDeathSpaceSystem |
| `AbortDeathSequence` | — | — | Cancels death flow (for debug / dev cheats) |

---

## Blueprint Flow Diagram

```mermaid
flowchart TD
    A[BPC_HealthSystem: HP = 0] --> B[Capture S_DeathContext]
    B --> C[Broadcast OnPlayerDeath]
    C --> D[BPC_DeathHandlingSystem.OnPlayerDeath]
    D --> E[DetermineDeathOutcome]
    
    E --> F{Outcome?}
    
    F -->|StandardRespawn| G[DeathAnimStage = DeathAnim]
    G --> H[Spawn corpse via BPC_PersistentCorpseSystem]
    H --> I[SS_SaveManager.SaveDeathState]
    I --> J[DeathAnimStage = PostDeath]
    J --> K[Delay RespawnDelay seconds]
    K --> L[BPC_PlayerRespawnSystem.RespawnPlayer]
    L --> M[DeathAnimStage = RespawnTransition]
    M --> N[Fade in at checkpoint location]
    N --> O[ApplyRespawnState]
    O --> P[DeathAnimStage = null]
    P --> Q[Broadcast OnRespawnCompleted]
    
    F -->|AltDeathSpace| R[DeathAnimStage = DeathAnim]
    R --> S[Spawn corpse via BPC_PersistentCorpseSystem]
    S --> T[SS_SaveManager.SaveDeathState]
    T --> U[BPC_AltDeathSpaceSystem.EnterAltDeathSpace]
    U --> V[Set exit portal to current checkpoint]
    V --> W[DeathAnimStage = null]
    W --> X[Player wanders alt space]
    X --> Y{Exit condition met?}
    Y -->|Optional: find exit portal| Z[BPC_AltDeathSpaceSystem.ExitAltDeathSpace]
    Y -->|Timer expired| AA[BPC_AltDeathSpaceSystem.ExitAltDeathSpace]
    Z --> AB[Respawn at exit portal transform]
    AA --> AB
    AB --> AC[ApplyRespawnState]
    AC --> AD[Broadcast OnRespawnCompleted]
    
    F -->|GameOver| AE[DeathAnimStage = PostDeath]
    AE --> AF[BPC_RunHistoryTracker.EndRun]
    AF --> AG[Disable player input]
    AG --> AH[Show Game Over screen]
    AH --> AI[Offer: Load / Main Menu / Quit]
```

---

## Communication Matrix

| Target System | Method | Why |
|---------------|--------|-----|
| `BPC_HealthSystem` | Dispatcher bind (HP reached 0) | Receives death trigger |
| `SS_SaveManager` | Direct call `SaveDeathState` / `LoadDeathState` | Saves/loads death state for continuity |
| `BP_Checkpoint` | Direct call `GetRespawnTransform` | Gets respawn location |
| `BP_Checkpoint` | Direct call `OnPlayerDeath` / `OnPlayerRespawn` | Notifies checkpoint system of death cycle |
| `GM_CoreGameMode` | Dispatcher `OnPlayerDeath` / `OnRespawnCompleted` | Game mode tracks death flow for game phase |
| `GS_CoreGameState` | Direct set `CurrentGamePhase` = GameOver | Game state reflects game over condition |
| `PC_PlayerController` | SetIgnoreMoveInput / SetIgnoreLookInput | Disable input during death sequence |
| `WBP_GameOverScreen` | Dispatcher via GM or direct | Show game over UI |
| `WBP_DeathScreen` | Dispatcher `OnPlayerDeath` | Show death animation overlay |
| `WBP_RunSummary` | Function `GetRunSummary` | Display death recap on game over |
| `BPC_PlayerMetricsTracker` | Read `DeathCount` | Include in death context |
| `I_Persistable` corpse actors | Register/unregister with `SS_SaveManager` | Corpse persistence |

---

## Reuse Notes

- All five sub-systems (DeathHandling, AltDeathSpace, Corpse, Respawn, RunHistory) sit on the same actor — the Player Controller
- The death outcome determination (`S_DeathOutcomeRules`) can be swapped per-level or per-chapter via `DA_LevelConfig`
- Corpse persistence across saves requires the corpse actor to implement `I_Persistable`
- Alt death space levels are loaded via `UGameplayStatics::LoadStreamLevel` and must be in the persistent level's Streaming Levels list
- Run history is session-only and NOT serialised — it resets on game restart
- `AbortDeathSequence` is useful for debug cheats: `GodMode` or `RespawnNow` console commands
- For multiplayer, the server must be the authority: all death trigger logic should run on the server via `HasAuthority()`