# Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js

> Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.

- **Canonical page:** https://gamecrew.ai/techniques/three/enemy-npc-ai-steering
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** ai
- **Tags:** `ai`, `enemy`, `npc`, `steering`, `patrol`, `telegraph`, `combat`, `attack-tokens`, `threejs`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

In 60 Hz browser games (`game.onUpdate`), enemy and NPC AI must be **readable to the player**, **deterministic**, and **zero-allocation per step** so headless `play` tests and 90 Hz headsets never stutter:
1. **8-Slot Context Steering on `CollisionWorld`**: Pre-allocate 8 unit horizontal directions and scratch `THREE.Vector3` instances; probe `world.raycast` along each slot to mask walls/pillars while steering smoothly around corners or orbiting the player.
2. **Explicit `telegraph -> strike -> recover` Phases**: Flash an emissive windup color and play an audio cue (`game.audio.play('telegraph')`) for `0.45 s` before the strike window opens, then hold `recover` (`0.65 s`) so skilled players can punish dodged attacks.
3. **Encounter Attack Tokens**: Share an `AttackTokenPool(2)` across the encounter so at most 2 enemies lunge simultaneously while others circle on a strafe ring.

## Mathematical & Algorithmic Core

- **Context Slot Score**: For 8 unit directions $\hat{\mathbf{u}}_i = (\cos \frac{\pi i}{4}, 0, \sin \frac{\pi i}{4})$, interest $I_i = \max(0.05, \hat{\mathbf{u}}_i \cdot \hat{\mathbf{g}})$, obstacle danger $D_i = \mathrm{clamp}(1 - d_i / R_{\text{probe}}, 0, 1)$, and unblocked weight $S_i = I_i (1 - D_i)$ when $D_i \le 0.7$.
- **Tangential Strafe Orbit**: $\mathbf{g}_{\text{orbit}} = \mathrm{normalize}(\hat{\mathbf{r}} \cdot \mathrm{clamp}(\frac{d - r_{\text{pref}}}{r_{\text{pref}}}, -1, 1) + 0.75 \hat{\mathbf{t}})$.

## Engine Implementation

### Zero-GC Context Steering + Token Pool + Enemy Brain (`Assets/Game/enemyAi.ts`)

```ts
import * as THREE from 'three';
import type { CollisionWorld, Game } from 'ccgd';

export type EnemyPhase = 'patrol' | 'strafe' | 'telegraph' | 'strike' | 'recover';

const DIRS: readonly THREE.Vector3[] = Array.from({ length: 8 }, (_, i) => {
  const a = (i * Math.PI) / 4;
  return new THREE.Vector3(Math.cos(a), 0, Math.sin(a));
});

const _origin = new THREE.Vector3();
const _goal = new THREE.Vector3();
const _sum = new THREE.Vector3();

export class AttackTokenPool {
  private readonly holders = new Set<string>();
  maxTokens: number;

  constructor(maxTokens = 2) {
    this.maxTokens = maxTokens;
  }

  tryAcquire(id: string): boolean {
    if (this.holders.has(id)) return true;
    if (this.holders.size >= this.maxTokens) return false;
    this.holders.add(id);
    return true;
  }

  release(id: string): void {
    this.holders.delete(id);
  }

  get activeCount(): number {
    return this.holders.size;
  }
}

export function solveContextSteering(
  world: CollisionWorld,
  position: THREE.Vector3,
  desiredDir: THREE.Vector3,
  probeDist = 2.2,
  out = new THREE.Vector3()
): THREE.Vector3 {
  _goal.set(desiredDir.x, 0, desiredDir.z);
  if (_goal.lengthSq() < 1e-6) return out.set(0, 0, 0);
  _goal.normalize();

  _origin.set(position.x, position.y + 0.6, position.z);
  _sum.set(0, 0, 0);
  let total = 0;

  for (let i = 0; i < 8; i++) {
    const u = DIRS[i];
    const interest = Math.max(0.05, u.dot(_goal));
    const hit = world.raycast(_origin, u, probeDist);
    const danger = hit ? Math.max(0, Math.min(1, 1 - hit.distance / Math.max(0.05, probeDist))) : 0;
    if (danger > 0.7) continue;
    const score = interest * (1 - danger);
    _sum.addScaledVector(u, score);
    total += score;
  }

  return total > 1e-4 ? out.copy(_sum).normalize() : out.copy(_goal);
}

export function orbitDirection(
  selfPos: THREE.Vector3,
  targetPos: THREE.Vector3,
  preferredRadius = 4.2,
  orbitSign: 1 | -1 = 1,
  out = new THREE.Vector3()
): THREE.Vector3 {
  const dx = targetPos.x - selfPos.x;
  const dz = targetPos.z - selfPos.z;
  const dist = Math.hypot(dx, dz);
  if (dist < 1e-4) return out.set(0, 0, 1);
  const rx = dx / dist;
  const rz = dz / dist;
  const tx = -rz * orbitSign;
  const tz = rx * orbitSign;
  const rw = Math.max(-1, Math.min(1, (dist - preferredRadius) / Math.max(0.5, preferredRadius)));
  return out.set(rx * rw + tx * 0.75, 0, rz * rw + tz * 0.75).normalize();
}

export class EnemyBrain {
  readonly id: string;
  readonly waypoints: THREE.Vector3[];
  private readonly pool?: AttackTokenPool;
  phase: EnemyPhase = 'patrol';
  waypointIndex = 0;
  timer = 0;
  memorySec = 0;
  readonly lastSeen = new THREE.Vector3();
  private readonly steer = new THREE.Vector3();
  private readonly desired = new THREE.Vector3();

  constructor(id: string, waypoints: THREE.Vector3[] = [], pool?: AttackTokenPool) {
    this.id = id;
    this.waypoints = waypoints;
    this.pool = pool;
  }

  step(
    game: Game,
    world: CollisionWorld,
    selfPos: THREE.Vector3,
    forward: THREE.Vector3,
    targetPos: THREE.Vector3,
    dt: number,
    outMove = new THREE.Vector3()
  ): THREE.Vector3 {
    const sightRange = game.tuning.value('enemySightRange', 14);
    const telegraphSec = game.tuning.value('enemyTelegraphSec', 0.45);
    const recoverSec = game.tuning.value('enemyRecoverSec', 0.65);

    const dx = targetPos.x - selfPos.x;
    const dz = targetPos.z - selfPos.z;
    const dist = Math.hypot(dx, dz);
    const inCone =
      dist <= sightRange && (dist < 1e-3 || (forward.x * dx + forward.z * dz) / dist >= 0.35);
    const eye = _origin.set(selfPos.x, selfPos.y + 1.1, selfPos.z);
    const rayDir = this.desired.set(dx, 0, dz).normalize();
    const blocked = dist > 0.4 && world.raycast(eye, rayDir, dist - 0.35) !== null;
    const sees = inCone && !blocked;

    if (sees) {
      this.lastSeen.copy(targetPos);
      this.memorySec = 2.5;
    } else if (this.memorySec > 0) {
      this.memorySec = Math.max(0, this.memorySec - dt);
    }

    switch (this.phase) {
      case 'patrol': {
        if (sees) {
          this.phase = 'strafe';
          return outMove.set(0, 0, 0);
        }
        if (this.waypoints.length === 0) return outMove.set(0, 0, 0);
        const wp = this.waypoints[this.waypointIndex % this.waypoints.length];
        if (Math.hypot(wp.x - selfPos.x, wp.z - selfPos.z) < 0.65) {
          this.waypointIndex = (this.waypointIndex + 1) % this.waypoints.length;
        }
        this.desired.subVectors(wp, selfPos);
        return solveContextSteering(world, selfPos, this.desired, 2.2, outMove).multiplyScalar(0.65);
      }
      case 'strafe': {
        if (!sees && this.memorySec <= 0) {
          this.pool?.release(this.id);
          this.phase = 'patrol';
          return outMove.set(0, 0, 0);
        }
        if (sees && dist <= 3.5 && (!this.pool || this.pool.tryAcquire(this.id))) {
          this.phase = 'telegraph';
          this.timer = telegraphSec;
          return outMove.set(0, 0, 0);
        }
        const goal = sees ? targetPos : this.lastSeen;
        orbitDirection(selfPos, goal, 4.2, this.id.charCodeAt(0) % 2 === 0 ? 1 : -1, this.steer);
        return solveContextSteering(world, selfPos, this.steer, 2.2, outMove);
      }
      case 'telegraph': {
        this.timer -= dt;
        if (this.timer <= 0) {
          this.phase = 'strike';
          this.timer = 0.22;
        }
        return outMove.set(0, 0, 0);
      }
      case 'strike': {
        this.timer -= dt;
        if (this.timer <= 0) {
          this.pool?.release(this.id);
          this.phase = 'recover';
          this.timer = recoverSec;
        }
        return outMove.set(forward.x, 0, forward.z).normalize().multiplyScalar(1.65);
      }
      case 'recover': {
        this.timer -= dt;
        if (this.timer <= 0) this.phase = sees ? 'strafe' : 'patrol';
        return outMove.set(0, 0, 0);
      }
    }
  }
}
```

## Performance & Determinism Traps

- **Zero allocations in `game.onUpdate`**: Reuse module-level scratch vectors (`_origin`, `_goal`, `_sum`) and instance vectors (`this.steer`, `this.desired`) so `1,000` fast-forwarded test steps allocate zero garbage.
- **Strip-only TypeScript (`erasableSyntaxOnly`)**: Declare class fields explicitly instead of using constructor parameter properties (`constructor(public ...)`).

## Verification Checklist

1. Add a play test in `Assets/Game/Tests/play/` stepping `EnemyBrain` through `patrol -> strafe -> telegraph -> strike -> recover` and asserting `AttackTokenPool.activeCount <= 2`.
2. Run `compile`, `test_play`, and `audit_game` to confirm clean TypeScript types and bounded `tuning.json` knobs.

## Official references

- Andrew Fray (Game AI Pro 2, Ch. 18 — Context Steering)
- Craig Reynolds (GDC 1999 — Steering Behaviors)
- DOOM 2016 Encounter Token Architecture (GDC 2017)
