# 05 — Save/Load, Persistence & Death Loop Systems (Systems 35-43)

**Category Purpose:** These 9 systems handle everything related to game state persistence — saving and loading player progress, checkpoint management, the death/respawn loop, the alternate death space (void/purgatory mechanic), persistent corpses, world state recording, run history tracking, and the `I_Persistable` interface contract that all saveable actors implement.

---

## System Index

| # | System | Asset Type | Role |
|---|--------|-----------|------|
| 35 | `SS_SaveManager` | Subsystem | Save/load subsystem; slot management, serializer, manifest |
| 36 | `I_Persistable` | Interface | Persistence contract for any actor that saves state |
| 37 | `BP_Checkpoint` | Actor | Checkpoint actor; respawn point, activation, save-on-touch |
| 38 | `BPC_AltDeathSpaceSystem` | Component | Alternate death/void space; enter, explore, find exit |
| 39 | `BPC_DeathHandlingSystem` | Component | Death orchestrator; outcome determination, animation, respawn |
| 40 | `BPC_PersistentCorpseSystem` | Component | Corpse persistence across death/respawn/level transitions |
| 41 | `BPC_PersistentWorldStateRecorder` | Component | Records world state changes (doors, items, enemies) for save |
| 42 | `BPC_PlayerRespawnSystem` | Component | Respawn logic; checkpoint resolution, state restoration |
| 43 | `BPC_RunHistoryTracker` | Component | Run/session history; death count, time, checkpoint progression |

---

## Category Data Flow — The Death Loop

```
┌──────────────────────────────────────────────────────────────────┐
│                        DEATH & PERSISTENCE                       │
│                                                                  │
│  BPC_HealthSystem.OnDeath                                         │
│      ↓                                                           │
│  BPC_DeathHandlingSystem (death orchestrator)                    │
│      │  Determines outcome: Alt Death Space? Normal Respawn?      │
│      ├─► Alt Death Space:                                        │
│      │     BPC_AltDeathSpaceSystem.Enter()                       │
│      │     Player explores void/purgatory                         │
│      │     Find exit → RestorePreviousState()                     │
│      │                                                           │
│      └─► Normal Respawn:                                         │
│            GM_CoreGameMode.HandlePlayerDead()                     │
│            SS_SaveManager.LoadCheckpoint()                        │
│            BPC_PlayerRespawnSystem.Respawn()                      │
│                                                                  │
│  SS_SaveManager (persistence subsystem)                          │
│      │  Manages save slots, serialization, manifest              │
│      ├─► OnSave: iterates all I_Persistable actors               │
│      ├─► OnLoad: restores actor states from save file            │
│      │                                                           │
│      │  Coordinates with:                                        │
│      ├─► BPC_PersistentWorldStateRecorder (world changes)        │
│      ├─► BPC_PersistentCorpseSystem (corpse data)               │
│      └─► BP_Checkpoint (save-on-touch activation)                │
│                                                                  │
│  BPC_RunHistoryTracker (session stats)                           │
│      │  Tracks: death count, play time, checkpoint progression   │
│      └─► Persists across sessions for meta-progression           │
└──────────────────────────────────────────────────────────────────┘
```

---

## 35 — SS_SaveManager: Save/Load Subsystem

**What It Does:** The central save/load authority as a GameInstanceSubsystem. Manages save slots (create, load, delete, list), handles serialization of all `I_Persistable` actors, maintains a save slot manifest, and coordinates with platform save services.

**How It Works Internally:**

**Save Protocol:**
1. Save triggered (manual, auto-save, checkpoint)
2. Iterates all actors implementing `I_Persistable` in the world
3. Each actor returns its state via `OnSave()` as a GameplayTagContainer
4. Serializes all actor states + global data (chapter, play time, objectives) to save file
5. Updates slot manifest with timestamp, screenshot, play time

**Load Protocol:**
1. Load slot selected
2. Deserializes save file
3. Loads correct level/chapter
4. Iterates `I_Persistable` actors, calls `OnLoad(SaveData)` on each
5. Restores global state (chapter, objectives, inventory)
6. Player placed at appropriate spawn point

**Slot Management:**
- Multiple save slots with metadata (timestamp, play time, chapter name, thumbnail)
- Auto-save slot separate from manual slots
- Slot manifest tracks all available saves

---

## 36 — I_Persistable: Persistence Interface

**What It Does:** The contract that any actor must implement to be saveable. The save system scans the world for `I_Persistable` implementors and calls these functions.

**Key Functions:**
- `OnSave()` → returns actor state as GameplayTagContainer for serialization
- `OnLoad(SaveData)` → restores actor state from saved data
- `GetSaveTag()` → returns unique GameplayTag identifying this actor for lookup
- `NeedsSave()` → whether this actor has unsaved changes

**Implementation:** Doors (save locked/open state), chests (looted/not), enemies (alive/dead/position), items (collected/not), narrative triggers (fired/not), checkpoints (active/not).

---

## 37 — BP_Checkpoint: Checkpoint Actor

**What It Does:** A world-placed actor that serves as a respawn point. On player touch or interaction, becomes the active checkpoint. Triggers auto-save. Overrides previous checkpoint.

**Features:**
- Activates on overlap or interaction
- Stores checkpoint transform (player respawn location/rotation)
- Triggers `SS_SaveManager.AutoSave()` on activation
- Visual states: inactive (dim), active (glowing), previous (faded)
- One checkpoint active at a time
- Save-on-touch: automatic save reduces lost progress

---

## 38 — BPC_AltDeathSpaceSystem: Alternate Death Space

**What It Does:** Implements the "void space" or "purgatory" mechanic — when the player dies in specific circumstances, instead of a standard respawn, they enter an alternate death dimension. They must explore this space, find an exit, and return to the main world.

**State Machine:**
1. `Enter()` — player dies, teleports to death space level
2. Player explores void environment (puzzle, narrative, combat)
3. `FindExit()` — player discovers exit point
4. `Exit()` — teleports back to main world at respawn point
5. Fires `RestorePreviousState()` — pops back from force stack

**Features:**
- Separate level or sub-level for death space
- Unique atmosphere, enemies, and narrative content
- Exit conditions configurable (time, puzzle solve, item find)
- Multiple death space variants possible
- Coordinates with `BPC_DeathHandlingSystem` for entry conditions

---

## 39 — BPC_DeathHandlingSystem: Death Orchestrator

**What It Does:** Listens for `BPC_HealthSystem.OnDeath` and determines what happens next. The central death logic router — decides between alt death space, checkpoint respawn, permadeath, or game over.

**Flow:**
1. Binds to `OnDeath` dispatcher
2. Determines death context: enemy killed? environmental? scripted?
3. Checks `BPC_DeathCauseTracker` for specific death cause
4. Evaluates conditions:
   - Should alt death space trigger? (configurable chance / specific enemies)
   - Is this permadeath mode? → wipe save
   - Normal death? → checkpoint respawn
5. Routes to appropriate system: `BPC_AltDeathSpaceSystem.Enter()` or `GM_CoreGameMode.HandlePlayerDead()`
6. Plays death animation, screen effects
7. Logs death to `BPC_RunHistoryTracker`

---

## 40 — BPC_PersistentCorpseSystem: Corpse Persistence

**What It Does:** When the player dies, their previous body becomes a persistent corpse in the world. On respawn, the old body remains as a lootable container with the player's previous inventory. Corpses persist across deaths and level transitions.

**Features:**
- Spawns corpse actor at death location with player's appearance
- Contains `BPC_ContainerInventory` with player's previous items
- Corpse persists across respawns (doesn't disappear)
- Configurable corpse limit (oldest despawns when max reached)
- Companions can loot player corpse (co-op)

---

## 41-43: Supporting Systems

- **41 BPC_PersistentWorldStateRecorder:** Records every world state change (door opened, item collected, enemy killed) to a change log for save/load. On load, replays changes to restore exact world state.
- **42 BPC_PlayerRespawnSystem:** Loads checkpoint data, places player at checkpoint transform, restores health/stamina/inventory from save state, applies brief invincibility.
- **43 BPC_RunHistoryTracker:** Tracks per-session stats: death count, play time, checkpoints reached, enemies killed, items collected. Persists for meta-progression (achievements, difficulty scaling).

---

## Common Implementation Patterns in This Category

1. **Force Stack Pattern:** Death and alt death space push state onto a stack; `RestorePreviousState()` pops back. Enables nested state changes (death → void → return).
2. **Interface-Based Persistence:** Save system doesn't know about doors or enemies — it only calls `I_Persistable.OnSave()` / `OnLoad()`. Any new saveable type just implements the interface.
3. **Save Tag Uniqueness:** Each saveable actor has a unique GameplayTag for identity. The save file maps tag → serialized state.
4. **Checkpoint Cascade:** Checkpoints are linear — activating a new one overrides the previous. Auto-save on activation prevents progress loss.
5. **Corpse as Container:** Corpses reuse `BPC_ContainerInventory` — no special corpse inventory code needed.

---

*Developer Reference v1.0 — 05 Save/Load Systems. Companion to docs/blueprints/05-saveload/ specs.*

---

## Multiplayer Networking

### Category Authority Map
| System | Authority | Notes |
|--------|-----------|-------|
| `SS_SaveManager` | Server triggers save/load | Clients receive restored state via GS_CoreGameState replication |
| `BP_Checkpoint` | Server validates activation | Active checkpoint replicates to all |
| `BPC_DeathHandlingSystem` | Server determines death outcome | Death animation multicast; respawn is server-driven |
| `BPC_PlayerRespawnSystem` | Server executes respawn | Client receives respawn state via replication |
| `BPC_PersistentCorpseSystem` | Server spawns corpse actor | Corpse replicated to all clients |
| `BPC_PersistentWorldStateRecorder` | Server records changes | State changes replicated via individual actor RepNotify |
| `BPC_RunHistoryTracker` | Server tracks; snapshot replicates | For scoreboard display |

### Key Multiplayer Considerations
- **Save/Load is server-coordinated.** Only server triggers save/load. Clients receive restored state via GS_CoreGameState and actor replication.
- **Death is server-authoritative.** Runs on server, determines outcome, multicasts death events.
- **Alt Death Space** (separate level): server calls `ClientTravel` for all clients.
- **Corpses** are replicated actors — all clients see them.
