# Deterministic ECS Enemy Brains, Encounter Directors & Telegraphed Bosses in Pulse

> Data-oriented Pulse ECS enemy perception, orbit steering, attack-token encounter pacing, and multi-phase telegraphed boss state machines verified with headless pulse_run invariants.

- **Canonical page:** https://gamecrew.ai/techniques/pulse/enemy-npc-ai-directors
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Pulse
- **Category:** ai
- **Tags:** `ai`, `enemy`, `npc`, `ecs`, `telegraph`, `combat`, `attack-tokens`, `director`, `boss`, `deterministic`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Pulse's fixed-tick ECS architecture excels at **deterministic, data-oriented enemy and boss AI** where perception, token allocation, movement steering, and combat hit windows execute in explicit system order (`after: "input"`, `before: "physics"`):
1. **Explicit ECS Components over Hidden Closures**: Store enemy phase (`0 = patrol, 1 = strafe, 2 = telegraph, 3 = strike, 4 = recover`), `phase_timer_s`, and `has_token` in declared Pulse components so snapshots, replays, and `pulse_run` invariants inspect exact state!
2. **Encounter Token Director Resource/Singleton**: Cap simultaneous `telegraph`/`strike` holders (`max_tokens = 2`) in a dedicated pass before movement steering so crowds flank in opposite directions (`orbit_sign = +1 / -1`) rather than overlapping on the player.
3. **Multi-Layered Boss Telegraphs**: Combine `ProceduralMotion` pitch/lean changes, emissive color shift, `vfx("ring" | "spark", ...)`, and `sfxAt("telegraph", pos)` at the start of phase `2` (`telegraph`) so every strike reads clearly in `pulse_look` captures.

## Mathematical & Algorithmic Core

- **Planar Strafe Orbit**: Given $\Delta \mathbf{p}_{xz} = (x_p - x_e, z_p - z_e)$ and $d = \max(10^{-4}, \|\Delta \mathbf{p}_{xz}\|)$, radial $\hat{\mathbf{r}} = \Delta \mathbf{p}_{xz} / d$, tangent $\hat{\mathbf{t}} = (-s \hat{r}_z, s \hat{r}_x)$, radial pull $w_r = \mathrm{clamp}((d - r_{\text{pref}}) / r_{\text{pref}}, -1, 1)$, desired horizontal velocity $\mathbf{v}_{xz} = v_{\text{move}} \cdot \mathrm{normalize}(w_r \hat{\mathbf{r}} + 0.75 \hat{\mathbf{t}})$.
- **Deterministic Tie-Breaking**: Alternate `orbit_sign` from entity spawn index (`+1` / `-1`) and never call `Math.random()` inside fixed-tick systems.

## Engine Implementation

### 1. Contract Declarations (`pulse_declare`)

Declare clean ECS contracts before implementing the AI system:
- `"component EnemyBrain { phase: int=0, timer_s: num=0.0, orbit_sign: num=1.0, has_token: bool=false, sight_range: num=14.0, move_speed: num=4.2 }"`
- `"component EncounterDirector { max_tokens: int=2, active_tokens: int=0 }"`
- `"event EnemyTelegraph { attacker: entity, x: num, z: num }"`

### 2. Deterministic Token Pacing & Telegraphed Steering System (`systems/enemy_ai.ts`)

```ts
import { emit, query, sfxAt, system, vfx } from "pulse";
import { EncounterDirector, EnemyBrain, EnemyTelegraph, PlayerTag } from "../contracts/ai";

const PATROL = 0;
const STRAFE = 1;
const TELEGRAPH = 2;
const STRIKE = 3;
const RECOVER = 4;

export const enemyAiSystem = system("enemy_ai", { before: "physics" }, (dt) => {
  const players = [...query(PlayerTag)];
  if (players.length === 0) return;
  const player = players[0];
  const px = player.pos[0];
  const pz = player.pos[2];

  const directors = [...query(EncounterDirector)];
  const director = directors[0]?.get(EncounterDirector);

  let activeHolders = 0;
  for (const e of query(EnemyBrain)) {
    const b = e.get(EnemyBrain);
    if (b.has_token && (b.phase === TELEGRAPH || b.phase === STRIKE)) {
      activeHolders++;
    } else {
      b.has_token = false;
    }
  }
  if (director) director.active_tokens = activeHolders;
  const maxTokens = director ? director.max_tokens : 2;

  for (const e of query(EnemyBrain)) {
    const b = e.get(EnemyBrain);
    const dx = px - e.pos[0];
    const dz = pz - e.pos[2];
    const dist = Math.hypot(dx, dz);
    const sees = dist <= b.sight_range;

    switch (b.phase) {
      case PATROL: {
        if (sees) b.phase = STRAFE;
        e.vel[0] = 0.0;
        e.vel[2] = 0.0;
        break;
      }
      case STRAFE: {
        if (!sees) {
          b.phase = PATROL;
          e.vel[0] = 0.0;
          e.vel[2] = 0.0;
          break;
        }
        if (dist <= 3.6 && activeHolders < maxTokens) {
          b.phase = TELEGRAPH;
          b.timer_s = 0.45;
          b.has_token = true;
          activeHolders++;
          if (director) director.active_tokens = activeHolders;
          sfxAt("telegraph", e.pos);
          vfx("spark", e.pos);
          emit(EnemyTelegraph, { attacker: e, x: e.pos[0], z: e.pos[2] });
          e.vel[0] = 0.0;
          e.vel[2] = 0.0;
          break;
        }
        const safeDist = Math.max(1e-4, dist);
        const rx = dx / safeDist;
        const rz = dz / safeDist;
        const tx = -rz * b.orbit_sign;
        const tz = rx * b.orbit_sign;
        const rw = Math.max(-1.0, Math.min(1.0, (safeDist - 4.2) / 4.2));
        const gx = rx * rw + tx * 0.75;
        const gz = rz * rw + tz * 0.75;
        const glen = Math.max(1e-4, Math.hypot(gx, gz));
        e.vel[0] = (gx / glen) * b.move_speed;
        e.vel[2] = (gz / glen) * b.move_speed;
        break;
      }
      case TELEGRAPH: {
        e.vel[0] = 0.0;
        e.vel[2] = 0.0;
        b.timer_s -= dt;
        if (b.timer_s <= 0.0) {
          b.phase = STRIKE;
          b.timer_s = 0.22;
          sfxAt("strike", e.pos);
        }
        break;
      }
      case STRIKE: {
        const safeDist = Math.max(1e-4, dist);
        e.vel[0] = (dx / safeDist) * b.move_speed * 1.65;
        e.vel[2] = (dz / safeDist) * b.move_speed * 1.65;
        b.timer_s -= dt;
        if (b.timer_s <= 0.0) {
          b.has_token = false;
          b.phase = RECOVER;
          b.timer_s = 0.65;
        }
        break;
      }
      case RECOVER: {
        e.vel[0] = 0.0;
        e.vel[2] = 0.0;
        b.timer_s -= dt;
        if (b.timer_s <= 0.0) b.phase = sees ? STRAFE : PATROL;
        break;
      }
    }
  }
});
```

## Performance & Determinism Traps

- **Recompute `activeHolders` at the top of each tick**: Rebuilding the active count from live `EnemyBrain` entities guarantees despawned/killed enemies automatically free their attack token on the very next tick!
- **Guard every vector normalization**: Always clamp `Math.max(1e-4, dist)` so an enemy overlapping the player never produces `NaN` velocities.

## Verification Checklist

1. Run `pulse_run({ ticks: 360 })` with invariants asserting `active_tokens <= max_tokens` and zero `NaN` entity positions.
2. Inspect `pulse_look` captures during phase `2` (`TELEGRAPH`) to confirm the telegraph VFX and enemy silhouette read clearly.

## Official references

- Andrew Fray (Game AI Pro 2 — Context Steering)
- DOOM 2016 Encounter Token Pacing (GDC 2017)
- Data-Oriented ECS Combat Systems Architecture
