# Game Event Bus API Reference

`@aphrodite/game-event-bus` — High-throughput typed event bus connecting all
gaming subsystems.

---

## Architecture

```
Game Events (64 types, 8 categories)
     │
     ├──► Ring Buffer (history storage)
     ├──► Priority Queue (ordered dispatch)
     ├──► Event Router (pattern-based routing)
     ├──► Event Batcher (grouped delivery)
     └──► Event Aggregator (analysis & state inference)
```

---

## Core Classes

### GameEventBus

Main event bus for game event dispatch and subscription.

**Factory**: `createGameEventBus(config?)`

#### Methods

| Method         | Signature                                                                                   | Description                                  |
| -------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `emit`         | `emit<T>(type: GameEventType, data: T, options?: EmitOptions): GameEvent<T>`                | Emit a typed event                           |
| `subscribe`    | `subscribe(pattern: string, handler: EventHandler, options?: SubscribeOptions): () => void` | Subscribe to events (returns unsubscribe fn) |
| `process`      | `process(): void`                                                                           | Flush the priority queue                     |
| `getHistory`   | `getHistory(count?: number): GameEvent[]`                                                   | Get recent event history                     |
| `queryHistory` | `queryHistory(filter: HistoryFilter): GameEvent[]`                                          | Query history with filters                   |
| `getStats`     | `getStats(): EventBusStats`                                                                 | Get bus performance statistics               |
| `destroy`      | `destroy(): void`                                                                           | Tear down the bus                            |

#### Configuration

```typescript
interface GameEventBusConfig {
  historyCapacity: number; // default: 10000
  queueCapacity: number; // default: 5000
  batchSize: number; // default: 64
  batchMode: BatchMode; // 'none' | 'time' | 'count' | 'time-or-count'
  batchIntervalMs: number; // default: 16 (one frame at 60fps)
  slowConsumerThresholdMs: number; // default: 50
}
```

#### Event Priority

| Level      | Value | Use case                    |
| ---------- | ----- | --------------------------- |
| `Critical` | 0     | System events, safety stops |
| `High`     | 1     | Combat, damage, explosions  |
| `Normal`   | 2     | Standard game events        |
| `Low`      | 3     | Ambient, analytics          |

#### Pattern Matching

Subscribe to events using wildcard patterns:

| Pattern            | Matches                    |
| ------------------ | -------------------------- |
| `impact.collision` | Exact match                |
| `impact.*`         | All impact events          |
| `*.hit`            | Hit events in any category |
| `**`               | All events                 |

#### Meta-Events

The bus emits meta-events about its own operation:

| Event              | When                         |
| ------------------ | ---------------------------- |
| `EventEmitted`     | Any event emitted            |
| `EventBatched`     | Event added to batch         |
| `EventDropped`     | Event dropped (queue full)   |
| `QueueOverflow`    | Queue capacity exceeded      |
| `ConsumerSlowdown` | Consumer exceeds threshold   |
| `BatchFlushed`     | Batch delivered to consumers |
| `HistoryCleared`   | History buffer cleared       |
| `Destroyed`        | Bus torn down                |

#### Statistics

```typescript
interface EventBusStats {
  eventsPerSecond: number;
  averageProcessingTimeMs: number;
  peakProcessingTimeMs: number;
  totalEventsEmitted: number;
  totalEventsDropped: number;
  slowConsumerCount: number;
  historySize: number;
  queueDepth: number;
}
```

---

## Event Taxonomy

### 64 Event Types in 8 Categories

#### Impact Events (8)

| Event              | Payload                       | Intensity Computation |
| ------------------ | ----------------------------- | --------------------- |
| `impact.collision` | `{ force, objectA, objectB }` | force / maxForce      |
| `impact.hit`       | `{ damage, source, target }`  | damage / maxDamage    |
| `impact.damage`    | `{ amount, type, source }`    | amount / maxHealth    |
| `impact.explosion` | `{ radius, force, position }` | force × radius        |
| `impact.block`     | `{ damage, direction }`       | damage / maxDamage    |
| `impact.parry`     | `{ timing, damage }`          | 1.0 (perfect)         |
| `impact.knockback` | `{ force, direction }`        | force / maxForce      |
| `impact.death`     | `{ source, cause }`           | 1.0 (always max)      |

#### Achievement Events (8)

| Event                        | Payload                     |
| ---------------------------- | --------------------------- |
| `achievement.score-change`   | `{ delta, total, source }`  |
| `achievement.combo-hit`      | `{ count, multiplier }`     |
| `achievement.combo-break`    | `{ finalCount }`            |
| `achievement.milestone`      | `{ id, name, description }` |
| `achievement.level-up`       | `{ level, previousLevel }`  |
| `achievement.discovery`      | `{ id, name, rarity }`      |
| `achievement.quest-complete` | `{ id, name, reward }`      |
| `achievement.unlock`         | `{ id, name, category }`    |

#### Tension Events (8)

| Event                       | Payload                        |
| --------------------------- | ------------------------------ |
| `tension.danger-near`       | `{ distance, source, threat }` |
| `tension.chase-start`       | `{ pursuer, target }`          |
| `tension.chase-end`         | `{ result }`                   |
| `tension.countdown-tick`    | `{ remaining, total }`         |
| `tension.near-miss`         | `{ distance, source }`         |
| `tension.stealth-detection` | `{ level, source }`            |
| `tension.low-health`        | `{ current, max, percentage }` |
| `tension.boss-phase`        | `{ phase, bossId, bossHp }`    |

#### Rhythm Events (8)

| Event                    | Payload                       |
| ------------------------ | ----------------------------- |
| `rhythm.beat-hit`        | `{ accuracy, combo, bpm }`    |
| `rhythm.measure-start`   | `{ measure, bpm }`            |
| `rhythm.tempo-change`    | `{ oldBpm, newBpm }`          |
| `rhythm.drop`            | `{ intensity }`               |
| `rhythm.rhythm-accuracy` | `{ percentage, streak }`      |
| `rhythm.music-section`   | `{ section, duration }`       |
| `rhythm.note-hit`        | `{ pitch, velocity, timing }` |
| `rhythm.note-miss`       | `{ expectedPitch, timing }`   |

#### Emotion Events (8)

| Event                  | Payload                   |
| ---------------------- | ------------------------- |
| `emotion.joy`          | `{ intensity, source }`   |
| `emotion.fear`         | `{ intensity, source }`   |
| `emotion.excitement`   | `{ intensity, source }`   |
| `emotion.calm`         | `{ intensity, duration }` |
| `emotion.awe`          | `{ intensity, source }`   |
| `emotion.frustration`  | `{ intensity, source }`   |
| `emotion.satisfaction` | `{ intensity, source }`   |
| `emotion.suspense`     | `{ intensity, duration }` |

#### Environment Events (8)

| Event                         | Payload                   |
| ----------------------------- | ------------------------- |
| `environment.weather-change`  | `{ from, to, intensity }` |
| `environment.time-of-day`     | `{ time, lightLevel }`    |
| `environment.terrain-change`  | `{ from, to }`            |
| `environment.ambient-change`  | `{ type, intensity }`     |
| `environment.underwater`      | `{ depth, entering }`     |
| `environment.wind`            | `{ speed, direction }`    |
| `environment.temperature`     | `{ value, delta }`        |
| `environment.day-night-cycle` | `{ phase, progress }`     |

#### Social Events (8)

| Event                   | Payload                        |
| ----------------------- | ------------------------------ |
| `social.tip`            | `{ amount, userId, message }`  |
| `social.chat-message`   | `{ message, userId, badges }`  |
| `social.vote`           | `{ option, userId, pollId }`   |
| `social.crowd-reaction` | `{ type, intensity, count }`   |
| `social.follow`         | `{ userId }`                   |
| `social.subscribe`      | `{ userId, tier }`             |
| `social.raid`           | `{ userId, viewerCount }`      |
| `social.poll`           | `{ pollId, options, results }` |

#### System Events (8)

| Event                    | Payload                |
| ------------------------ | ---------------------- |
| `system.game-start`      | `{ gameId, config }`   |
| `system.game-end`        | `{ gameId, result }`   |
| `system.pause`           | `{ reason }`           |
| `system.resume`          | `{ pauseDuration }`    |
| `system.scene-change`    | `{ from, to }`         |
| `system.player-join`     | `{ playerId }`         |
| `system.player-leave`    | `{ playerId, reason }` |
| `system.settings-change` | `{ setting, value }`   |

### Utility Functions

| Function                | Signature                               | Description                       |
| ----------------------- | --------------------------------------- | --------------------------------- |
| `getEventCategory`      | `(type: string): EventCategory`         | Extract category from event type  |
| `getEventDescription`   | `(type: string): string`                | Human-readable event description  |
| `computeEventIntensity` | `(type: string, data: unknown): number` | Normalised 0–1 intensity          |
| `isImpactEvent`         | `(event: GameEvent): boolean`           | Type guard for impact events      |
| `isAchievementEvent`    | `(event: GameEvent): boolean`           | Type guard for achievement events |
| `isTensionEvent`        | `(event: GameEvent): boolean`           | Type guard for tension events     |
| `isRhythmEvent`         | `(event: GameEvent): boolean`           | Type guard for rhythm events      |
| `isEmotionEvent`        | `(event: GameEvent): boolean`           | Type guard for emotion events     |
| `isEnvironmentEvent`    | `(event: GameEvent): boolean`           | Type guard for environment events |
| `isSocialEvent`         | `(event: GameEvent): boolean`           | Type guard for social events      |
| `isSystemEvent`         | `(event: GameEvent): boolean`           | Type guard for system events      |

---

## Event Router

Topic-based pattern routing with advanced features.

### Configuration

```typescript
interface EventRouterConfig {
  maxConsumers: number; // default: 100
  backPressureStrategy: BackPressureStrategy;
  consumerPrioritisation: boolean;
  slowConsumerThresholdMs: number;
}
```

### Back-Pressure Strategies

| Strategy       | Behaviour                                     |
| -------------- | --------------------------------------------- |
| `Drop`         | Drop events when consumer is slow             |
| `Buffer`       | Buffer events for slow consumers              |
| `Block`        | Block emission until consumer catches up      |
| `SampleLatest` | Keep only the latest event for slow consumers |

### Features

- Multi-filter event chains with AND/OR logic
- Consumer prioritisation for ordered delivery
- Batching per-consumer with configurable thresholds
- Specificity scoring for pattern matches
- Metrics per-consumer (events received, processing time)

---

## Event Aggregator

Real-time analysis and game state inference.

### Game State Machine

Inferred game state from event frequency and intensity:

```
Idle → Calm → Building → Action → Intense → Climax → Cooldown → Idle
```

### Features

- **Sliding window** frequency analysis (configurable window size)
- **Intensity smoothing**: exponential, moving average, Gaussian
- **Correlation detection** between event types with confidence scoring
- **Threshold breach detection** for custom metrics
- **Game state inference** from aggregated event patterns

---

## Internal Data Structures

### RingBuffer

Fixed-capacity circular buffer for event history.

- O(1) push, O(1) read by index
- Automatic oldest-entry eviction at capacity
- Default capacity: 10,000 events

### PriorityEventQueue

Priority-ordered event dispatch queue.

- Events processed in priority order (Critical → Low)
- Same-priority events processed in FIFO order
- Default capacity: 5,000 events
- Overflow events are dropped with `QueueOverflow` meta-event
