# BPC_ContextualTraversalSystem — Contextual Traversal System

**Parent Class:** `ActorComponent`
**Category:** Interaction
**Target UE Version:** 5.5–5.7
**Build Phase:** 2 — Interaction

---

## 1. Overview

`BPC_ContextualTraversalSystem` handles player traversal of environmental obstacles — vaulting, climbing, squeezing through gaps, sliding under obstacles. Uses motion warping and root motion for smooth traversal animations triggered by context-aware detection.

---

## 2. Enums

### `E_TraversalType`

| Value | Description |
|-------|-------------|
| `Vault` | Vault over low obstacles |
| `Mantle` | Climb up onto ledges |
| `Slide` | Slide under low barriers |
| `Squeeze` | Squeeze through narrow gaps |
| `LedgeGrab` | Grab and hang from ledges |

### `E_TraversalHeight`

| Value | Description |
|-------|-------------|
| `Low` | Below knee height (step up) |
| `Medium` | Waist height (vault) |
| `High` | Chest height (mantle) |

---

## 3. Variables

| Variable | Type | Description |
|----------|------|-------------|
| `DetectionRange` | `float` | Max distance to detect traversable surfaces |
| `DetectionHalfAngle` | `float` | Cone angle for forward detection |
| `VaultHeightThreshold` | `float` | Max height for vault vs mantle decision |
| `TraversalSpeed` | `float` | Speed multiplier during traversal anim |
| `bIsTraversing` | `bool` | Currently playing traversal animation |
| `CurrentTraversalType` | `E_TraversalType` | Active traversal type |
| `MotionWarpingTarget` | `FVector` | Target location for motion warping |
| `TraversalCooldown` | `float` | Min time between traversals |

---

## 4. Functions

| Function | Description |
|----------|-------------|
| `DetectTraversableObstacle` | Performs forward trace to detect vault/mantle points |
| `AttemptTraversal` | Initiates traversal to detected point. Returns bool |
| `ExecuteTraversal` | Plays traversal montage with motion warping |
| `OnTraversalComplete` | Callback when montage finishes |
| `CancelTraversal` | Interrupts traversal (damage/player input) |
| `IsTraversing` | Returns `bIsTraversing` |

---

## 5. Event Dispatchers

| Dispatcher | Payload | Description |
|------------|---------|-------------|
| `OnTraversalStarted` | `E_TraversalType Type`, `FVector Target` | Traversal animation begins |
| `OnTraversalComplete` | `E_TraversalType Type` | Player reaches target position |
| `OnTraversalFailed` | `FText Reason` | Traversal attempt blocked |

---

## 6. Dependencies & Communication

| System | Relationship |
|--------|--------------|
| `BPC_MovementStateSystem` | Movement mode override during traversal |
| `BPC_CameraStateLayer` | Camera FOV adjustment during traversal |
| `BPC_StressSystem` | Stress modifier for close-call traversals |

---

## 7. Reuse Notes
- Uses UE5 Motion Warping for accurate target placement
- Detection uses capsule trace at player height ranges

---

## 8. Manual Implementation Guide

### 8.1 Class Setup
1. Create Blueprint Class: Parent = `ActorComponent`, Name = `BPC_ContextualTraversalSystem`
2. Add to Player Character
3. Enable `Motion Warping` plugin in Project Settings

### 8.2 Variable Initialization (BeginPlay)
```
Event BeginPlay
  ├─ Set bIsTraversing = false
  ├─ Set DetectionRange = 200.0  (cm)
  ├─ Set DetectionHalfAngle = 45.0  (degrees)
  ├─ Set VaultHeightThreshold = 120.0  (waist height in cm)
  ├─ Set TraversalSpeed = 1.0
  ├─ Set TraversalCooldown = 0.5
  ├─ Get Owner → Get Component by Class (BPC_MovementStateSystem) → Cache reference
  ├─ Get Owner → Find Component by Class (BPC_CameraStateLayer) → Cache reference
  └─ Get Owner → Cast to Character → Get CharacterMovement → Cache CMC reference
```

### 8.3 Function Implementations

#### `DetectTraversableObstacle()` → `Hit Result, TraversalType, Height`

```
[Function: DetectTraversableObstacle] (Pure)
  Step 1: Get Owner → Get Actor Location and Forward Vector
  Step 2: Three capsule traces at different heights:
    Trace A (Low: half-height = 30cm):
      Start: OwnerLocation + UpVector * 30
      End: Start + ForwardVector * DetectionRange
      Trace Channel: WorldStatic
    Trace B (Medium: half-height = 60cm):
      Same but offset by 60cm vertically
    Trace C (High: half-height = 90cm):
      Same but offset by 90cm vertically

  Step 3: For each trace that hits:
    Get Hit Actor → Get Hit Location → Get Hit Normal
    Calculate obstacle top: trace down from above obstacle to find top edge
    ObstacleHeight = topHit.Location.Z - bottomHit.Location.Z

  Step 4: Classify by height:
    ObstacleHeight <= 40cm → E_TraversalHeight::Low (step up)
    ObstacleHeight <= VaultHeightThreshold → E_TraversalHeight::Medium (vault)
    ObstacleHeight > VaultHeightThreshold → E_TraversalHeight::High (mantle)

  Step 5: Check clearance above obstacle (trace upward from top)
    If ceiling too low → cannot mantle → return invalid

  Step 6: Determine traversal type:
    - Low + no obstacle: just step (automatic)
    - Medium + clearance: Vault
    - High + ledge: Mantle
    - Narrow gap (sides): Squeeze
    - Low barrier with gap: Slide

  Step 7: Calculate landing position:
    Forward trace from obstacle top to find landing spot
    Set MotionWarpingTarget = landingPosition

  Step 8: Return HitResult, TraversalType, TraversalHeight struct
```

**Nodes:** `Line Trace by Channel` (x5+), `Break Hit Result`, `Get Hit Location`, `Get Hit Normal`, `Vector Up/Down/Forward`, `Make Vector`, `Branch`, `Switch on E_TraversalHeight`

#### `AttemptTraversal(TraversalType, TargetLocation)` → `Boolean`

```
[Function: AttemptTraversal]
  Step 1: Branch on bIsTraversing → If true, return false
  Step 2: Branch on CooldownActive → If cooldown timer active, return false
  Step 3: Query BPC_StateManager → IsActionPermitted("Action.Traverse")
    False → Fire OnTraversalFailed("Blocked by state"), return false

  Step 4: Set bIsTraversing = true
  Step 5: Set CurrentTraversalType = TraversalType
  Step 6: Notify BPC_MovementStateSystem → SetMovementMode(Vaulting, Forced)
  Step 7: Disable player input (optional — depends on traversal type)
  Step 8: Fire OnTraversalStarted(TraversalType, TargetLocation)

  Step 9: Call ExecuteTraversal(TraversalType, TargetLocation)
  Step 10: Return true
```

#### `ExecuteTraversal(Type, Target)` → `void`

```
[Function: ExecuteTraversal]
  Step 1: Switch on Type:
    Case Vault:
      - Play Montage: AM_Vault (from Animation Blueprint)
      - Add Motion Warping Target: "VaultTarget" → Target location
      - Root motion in montage moves character to Target
    Case Mantle:
      - Play Montage: AM_Mantle
      - Add Motion Warping Target: "MantleTop" → ledge top
      - Add Motion Warping Target: "MantleLand" → landing position
    Case Slide:
      - Play Montage: AM_Slide
      - Set capsule half-height to crouch height temporarily
      - Add Motion Warping Target: "SlideTarget"
    Case Squeeze:
      - Play Montage: AM_Squeeze
      - Add Motion Warping Target: "SqueezeTarget"
    Case LedgeGrab:
      - Play Montage: AM_LedgeGrab
      - Disable gravity temporarily
      - Attach to ledge point

  Step 2: On Montage Completed or Blending Out:
    Call OnTraversalComplete()
```

**Nodes:** `Play Montage`, `Add or Update Motion Warping Target` (name + location), `Set Capsule Half Height`, `On Completed` delegate

#### `OnTraversalComplete()` → `void`

```
[Function: OnTraversalComplete]
  Step 1: Set bIsTraversing = false
  Step 2: Restore capsule half-height (if modified)
  Step 3: Re-enable player input (if disabled)
  Step 4: Notify BPC_MovementStateSystem → restore previous movement mode
  Step 5: Start TraversalCooldown timer → set bCanTraverse = false
    On timer end → bCanTraverse = true
  Step 6: Fire OnTraversalComplete(CurrentTraversalType)
```

#### `CancelTraversal()` → `void`

```
[Function: CancelTraversal]
  Step 1: Branch on bIsTraversing → If false, return
  Step 2: Stop Montage (AM currently playing)
  Step 3: Set bIsTraversing = false
  Step 4: Restore movement mode, input, capsule height
  Step 5: Fire OnTraversalFailed("Cancelled")
```

### 8.4 Event Dispatcher Bindings

| Bind to Dispatcher | Custom Event | Logic |
|-------------------|-------------|-------|
| `IA_Jump` (Pressed near obstacle) | `OnTraversalInput` | Call DetectTraversableObstacle → if valid: AttemptTraversal |
| `BPC_MovementStateSystem.OnMovementModeChanged` | `CheckTraversalState` | If in Vaulting mode and bIsTraversing false → force cancel |

### 8.5 Blueprint Build Checklist
- [ ] Enable Motion Warping plugin
- [ ] Create BPC_ContextualTraversalSystem, add to Player Character
- [ ] Add all variables with defaults
- [ ] Create traversal montages: AM_Vault, AM_Mantle, AM_Slide, AM_Squeeze, AM_LedgeGrab
- [ ] Add Motion Warping notifies in montages at key frames
- [ ] Implement DetectTraversableObstacle with multi-height capsule traces
- [ ] Implement AttemptTraversal with state/cooldown checks
- [ ] Implement ExecuteTraversal with type-switch and motion warping targets
- [ ] Implement OnTraversalComplete cleanup
- [ ] Bind IA_Jump for traversal input
- [ ] Test: vault over low wall, mantle onto ledge, slide under barrier