# Game Genre Development Guide

Complete guide for creating, configuring, and testing new game genres in the
Aphrodite gaming platform. This document covers every subsystem that a new genre
must integrate with, provides working code examples, and explains the testing
strategy.

---

## Table of Contents

1. [Overview](#1-overview)
2. [Genre Registration Points](#2-genre-registration-points)
3. [Step 1 — Define the Genre Type](#3-step-1--define-the-genre-type)
4. [Step 2 — Create a Graphics Profile](#4-step-2--create-a-graphics-profile)
5. [Step 3 — Create a Device Reaction Profile](#5-step-3--create-a-device-reaction-profile)
6. [Step 4 — Create a Music Palette](#6-step-4--create-a-music-palette)
7. [Step 5 — Configure Performer Layout Adaptation](#7-step-5--configure-performer-layout-adaptation)
8. [Step 6 — Visual Effects Integration](#8-step-6--visual-effects-integration)
9. [Step 7 — Testing Your Genre](#9-step-7--testing-your-genre)
10. [Reference Tables](#10-reference-tables)
11. [Checklist](#11-checklist)

---

## 1. Overview

A "genre" in Aphrodite is not a single flag — it is a cross-cutting concern that
touches five distinct subsystems:

| Subsystem             | Library                             | What it controls                                |
| --------------------- | ----------------------------------- | ----------------------------------------------- |
| **Graphics Settings** | `@aphrodite/game-runtime`           | FPS targets, priority weights, preset overrides |
| **Device Reactions**  | `@aphrodite/game-testing`           | Haptic intensity/duration/frequency constraints |
| **Music Scoring**     | `@aphrodite/cinematic-music-engine` | Instrument palettes, scales, tempo, mood        |
| **Performer Layout**  | `@aphrodite/performer-compositor`   | Camera framing, overlay size, layout rules      |
| **Visual Effects**    | `@aphrodite/vfx-*` libraries        | Effect budgets controlled via priority weights  |

Adding a new genre means touching all five. This guide walks through each one in
order.

### Design Principles

- **Type-safe enums** — Every genre system uses an `as const` object pattern
  (not TypeScript `enum`) for tree-shakeability and interoperability.
- **Profiles are data** — Genre differences are expressed as configuration
  objects, not code branches. No `if (genre === 'fps')` sprawl.
- **Safety first** — Device reaction profiles are bounded by global safety
  limits that cannot be exceeded regardless of genre configuration.
- **Testable** — Every profile has a corresponding test suite that validates
  constraints hold for all genres.

---

## 2. Genre Registration Points

When you add a new genre, you must update the following files:

| File                                                                 | What to add                                        |
| -------------------------------------------------------------------- | -------------------------------------------------- |
| `libs/aphrodite/game-runtime/src/types.ts`                           | New value in `GenreType` const object              |
| `libs/aphrodite/game-runtime/src/config/genre-profiles.ts`           | New `GenreProfile` + entry in `GENRE_PROFILES`     |
| `libs/aphrodite/game-testing/src/device-tests/device-tests-types.ts` | New value in `GameGenre` const enum                |
| `libs/aphrodite/game-testing/src/device-tests/device-tests.ts`       | New entry in `DEFAULT_GENRE_PROFILES`              |
| `libs/aphrodite/cinematic-music-engine/src/palettes.ts`              | New value in `GenreType` + new `PaletteDefinition` |
| `libs/aphrodite/performer-compositor/src/adaptive.ts`                | New value in `GameGenre` + layout mapping          |

---

## 3. Step 1 — Define the Genre Type

### 3.1 Runtime Genre Type

Add the new genre to the `GenreType` const object in
`libs/aphrodite/game-runtime/src/types.ts`:

```typescript
// libs/aphrodite/game-runtime/src/types.ts

export const GenreType = {
  FPS: 'fps',
  TPS: 'tps',
  RPG: 'rpg',
  RTS: 'rts',
  PLATFORMER: 'platformer',
  RACING: 'racing',
  SIMULATION: 'simulation',
  PUZZLE: 'puzzle',
  HORROR: 'horror',
  SANDBOX: 'sandbox',
  FIGHTING: 'fighting',
  MOBA: 'moba',
  // ↓ Add your genre here
  BATTLE_ROYALE: 'battle-royale',
} as const;

export type GenreType = (typeof GenreType)[keyof typeof GenreType];
```

**Rules:**

- Key is UPPER_SNAKE_CASE
- Value is lowercase kebab-case
- The value string must be globally unique across all genre const objects
- The `type GenreType` union is automatically derived — no manual update needed

### 3.2 Testing Genre Enum

If the genre needs device reaction profiling, add it to the `GameGenre` const
enum in `libs/aphrodite/game-testing/src/device-tests/device-tests-types.ts`:

```typescript
export const enum GameGenre {
  ACTION = 'action',
  HORROR = 'horror',
  RACING = 'racing',
  RHYTHM = 'rhythm',
  RPG = 'rpg',
  PUZZLE = 'puzzle',
  SIMULATION = 'simulation',
  SPORTS = 'sports',
  // ↓ Add your genre here
  BATTLE_ROYALE = 'battle-royale',
}
```

> **Note:** `GameGenre` uses `const enum` (inlined at compile time). This is a
> separate enum from the runtime `GenreType` because the testing library has
> different genre granularity — it groups by haptic profile similarity rather
> than gameplay mechanics.

### 3.3 Music Genre Type

If the genre needs a custom music palette, add it to the `GenreType` const
object in `libs/aphrodite/cinematic-music-engine/src/palettes.ts`:

```typescript
export const GenreType = {
  Fantasy: 'fantasy',
  SciFi: 'sci-fi',
  Horror: 'horror',
  Action: 'action',
  Romance: 'romance',
  Eastern: 'eastern',
  Western: 'western',
  Steampunk: 'steampunk',
  Medieval: 'medieval',
  Noir: 'noir',
  // ↓ Add your genre here
  Cyberpunk: 'cyberpunk',
} as const;
```

> **Note:** Music genres are thematic (Fantasy, Noir, Steampunk), not mechanical
> (FPS, RPG). A single music genre can serve multiple game genres. Only add a
> new music genre if existing palettes don't capture the sonic identity you
> need.

### 3.4 Performer Compositor Genre

Add the genre to `GameGenre` in
`libs/aphrodite/performer-compositor/src/adaptive.ts`:

```typescript
export const GameGenre = {
  FPS: 'fps',
  RPG: 'rpg',
  Racing: 'racing',
  // ...existing genres...
  // ↓ Add your genre here
  BattleRoyale: 'battle-royale',
} as const;
```

---

## 4. Step 2 — Create a Graphics Profile

The graphics profile tells the engine what to prioritize when rendering your
genre. It lives in `libs/aphrodite/game-runtime/src/config/genre-profiles.ts`.

### 4.1 The GenreProfile Interface

```typescript
export interface GenreProfile {
  genre: GenreType;
  name: string; // Display name
  description: string; // Optimization rationale
  targetFps: number; // Ideal frame rate
  prioritizeFramerate: boolean; // true = drop quality to maintain FPS
  drawDistancePriority: number; // 0–1, importance of view distance
  shadowPriority: number; // 0–1, importance of shadow quality
  effectsPriority: number; // 0–1, importance of particle/VFX
  antiAliasingPriority: number; // 0–1, importance of AA
  postProcessPriority: number; // 0–1, importance of post-processing
  motionBlurRecommended: boolean; // Genre-level motion blur recommendation
  dynamicResolutionRecommended: boolean; // Genre-level DRS recommendation
  presetOverrides: Partial<
    Record<
      // Per-quality-preset setting overrides
      GraphicsPreset,
      Partial<GraphicsSettings>
    >
  >;
}
```

### 4.2 Writing a Profile

Think about what matters for the genre. Use existing profiles as a guide:

| Question                         | High priority examples       | Low priority examples        |
| -------------------------------- | ---------------------------- | ---------------------------- |
| Does the player need to see far? | RTS (0.9), RPG (0.8)         | Fighting (0.3), Puzzle (0.2) |
| Are precise visuals critical?    | FPS AA (0.9), Fighting (0.8) | Puzzle (0.4)                 |
| Is framerate critical?           | FPS (120), Fighting (60)     | RPG (60), Puzzle (30)        |
| Are effects a selling point?     | Fighting (0.9), Horror (0.7) | Puzzle (0.3)                 |

Here is a complete example for a hypothetical **Battle Royale** genre:

```typescript
/** Battle Royale — large maps, many players, prioritize draw distance and FPS. */
const PROFILE_BATTLE_ROYALE: GenreProfile = {
  genre: GT.BATTLE_ROYALE,
  name: 'Battle Royale',
  description:
    'Large open maps with many concurrent players. Prioritizes draw distance ' +
    'for spotting distant enemies, high framerate for competitive advantage, ' +
    'and dynamic resolution to maintain FPS during large firefights.',
  targetFps: 120,
  prioritizeFramerate: true,
  drawDistancePriority: 0.9, // Must see far for looting and combat
  shadowPriority: 0.4, // Shadows are nice but not critical
  effectsPriority: 0.6, // Explosions, airdrops, zone effects
  antiAliasingPriority: 0.7, // Important for spotting at distance
  postProcessPriority: 0.3, // Minimal — keep visibility clear
  motionBlurRecommended: false, // Competitive players disable this
  dynamicResolutionRecommended: true, // Essential for large-scale fights
  presetOverrides: {
    [GP.LOW]: { targetFps: 60, drawDistance: 0.6, motionBlur: false },
    [GP.MEDIUM]: { targetFps: 120, drawDistance: 0.8, motionBlur: false },
    [GP.HIGH]: { targetFps: 120, drawDistance: 1.0, motionBlur: false },
    [GP.ULTRA]: { targetFps: 120, drawDistance: 1.0, motionBlur: false },
    [GP.CINEMATIC]: { targetFps: 60, motionBlur: true },
  },
};
```

### 4.3 Registering the Profile

Add the profile to the `GENRE_PROFILES` record:

```typescript
export const GENRE_PROFILES: Record<GenreType, GenreProfile> = {
  // ...existing profiles...
  [GT.BATTLE_ROYALE]: { ...PROFILE_BATTLE_ROYALE },
};
```

### 4.4 Runtime Custom Profiles

The `GenreProfileManager` also supports registering custom profiles at runtime
without modifying source. This is useful for user-configurable genres or A/B
testing:

```typescript
const manager = createGenreProfileManager();

// Create a modified profile from an existing one
const custom = manager.createCustomProfile('fps', {
  name: 'Competitive FPS',
  targetFps: 240,
  postProcessPriority: 0.1,
  presetOverrides: {
    [GP.LOW]: { targetFps: 144 },
  },
});

// Register it under a custom key
manager.registerCustomProfile('competitive-fps', custom);

// Now it's available through all lookup methods
const settings = manager.getRecommendedSettings(
  'competitive-fps' as GenreType,
  'high'
);
```

### 4.5 Settings Manager Integration

The `SettingsManager` in `@aphrodite/game-runtime` applies genre profiles
automatically when a genre is set:

```typescript
import { createSettingsManager } from '@aphrodite/game-runtime';

const settings = createSettingsManager();
settings.setGenre('battle-royale'); // Applies genre overrides, emits GENRE_PROFILE_APPLIED
```

The `SettingsManager` also serializes/deserializes the active genre, so it
persists across save/load cycles.

---

## 5. Step 3 — Create a Device Reaction Profile

Device reaction profiles constrain haptic feedback for your genre. They enforce
intensity, duration, frequency, and type limits that ensure the physical
experience matches the genre's feel.

### 5.1 The GenreReactionProfile Interface

```typescript
export interface GenreReactionProfile {
  readonly genre: GameGenre;
  readonly minIntensity: number; // Floor (0–1)
  readonly maxIntensity: number; // Ceiling (0–1)
  readonly avgIntensityRange: [number, number]; // Expected average window
  readonly minDurationMs: number; // Shortest allowed reaction
  readonly maxDurationMs: number; // Longest allowed reaction
  readonly maxFrequencyHz: number; // Max reactions per second
  readonly allowedTypes: readonly string[]; // Permitted reaction type strings
}
```

### 5.2 Design Guidelines

The reaction profile should reflect the genre's "physical vocabulary":

| Genre feel                     | Intensity | Duration  | Frequency | Types                     |
| ------------------------------ | --------- | --------- | --------- | ------------------------- |
| **Fast, explosive** (Action)   | 0.1–0.85  | 20–2000ms | 25 Hz     | impact, explosion, rumble |
| **Slow, atmospheric** (Horror) | 0.05–0.7  | 50–5000ms | 10 Hz     | pulse, ambient, rumble    |
| **Rhythmic, precise** (Rhythm) | 0.2–0.8   | 10–500ms  | 20 Hz     | beat, tap, pulse          |
| **Gentle, minimal** (Puzzle)   | 0.05–0.5  | 20–1000ms | 5 Hz      | click, snap, solve        |

**Key considerations:**

- `maxIntensity` must not exceed the global safety limit
  (`DEFAULT_SAFETY_LIMITS.maxIntensity = 0.85`)
- `maxDurationMs` must not exceed `DEFAULT_SAFETY_LIMITS.maxDurationMs = 5000`
- `maxFrequencyHz` must not exceed `DEFAULT_SAFETY_LIMITS.maxFrequencyHz = 30`
- `avgIntensityRange` should be a narrow window that represents the "normal"
  feel — too wide and it won't catch outliers
- `allowedTypes` should always include `'haptic'` and `'vibration'` as base
  types, plus genre-specific types

### 5.3 Writing the Profile

Add the profile to `DEFAULT_GENRE_PROFILES` in
`libs/aphrodite/game-testing/src/device-tests/device-tests.ts`:

```typescript
const DEFAULT_GENRE_PROFILES: Record<GameGenre, GenreReactionProfile> = {
  // ...existing profiles...
  [GameGenre.BATTLE_ROYALE]: {
    genre: GameGenre.BATTLE_ROYALE,
    minIntensity: 0.1,
    maxIntensity: 0.85,
    avgIntensityRange: [0.25, 0.6],
    minDurationMs: 15,
    maxDurationMs: 3000,
    maxFrequencyHz: 25,
    allowedTypes: [
      'haptic',
      'vibration',
      'rumble',
      'gunshot',
      'explosion',
      'impact',
      'vehicle',
      'zone',
      'loot',
    ],
  },
};
```

### 5.4 Safety Limits

All reaction profiles are bounded by `DEFAULT_SAFETY_LIMITS`:

```typescript
export const DEFAULT_SAFETY_LIMITS: SafetyLimits = {
  maxIntensity: 0.85, // Absolute maximum for any single device
  maxDurationMs: 5000, // No reaction longer than 5 seconds
  maxFrequencyHz: 30, // No more than 30 reactions/second
  cooldownMs: 33, // ~30 Hz minimum gap between reactions
  maxConcurrentDevices: 8, // Max devices active simultaneously
  maxTotalIntensity: 3.0, // Sum of all concurrent device intensities
};
```

The `SafetyLimitVerifier` class enforces these limits at runtime regardless of
what the genre profile allows. Your genre profile values are the design intent;
safety limits are the hard ceiling.

### 5.5 Validation

The `GenreReactionProfileValidator` validates reaction samples against a genre
profile:

```typescript
import {
  createGenreReactionProfileValidator,
  type ReactionSample,
  GameGenre,
} from '@aphrodite/game-testing';

const validator = createGenreReactionProfileValidator();

const samples: ReactionSample[] = [
  {
    deviceId: 'controller-1',
    type: 'gunshot',
    intensity: 0.7,
    durationMs: 200,
    timestamp: 0,
  },
  {
    deviceId: 'controller-1',
    type: 'explosion',
    intensity: 0.85,
    durationMs: 1500,
    timestamp: 500,
  },
];

const result = validator.validate(samples, GameGenre.BATTLE_ROYALE);
console.log(result.passed); // true/false
console.log(result.violations); // string[] of any constraint failures
```

---

## 6. Step 4 — Create a Music Palette

Music palettes define the sonic identity of a genre. They specify instruments,
chord progressions, scales, tempo ranges, and dynamic profiles.

### 6.1 The PaletteDefinition Interface

```typescript
export interface PaletteDefinition {
  id: PaletteId; // Branded string ID
  name: string; // Display name
  genre: GenreTypeValue; // Music genre tag
  description: string; // Sonic character description
  instruments: InstrumentEntry[]; // Available instruments
  chordProgressions: ChordProgression[]; // Harmonic vocabulary
  scales: ScaleDefinition[]; // Available scales
  textureLayers: TextureLayerDefinition[]; // Layer activation rules
  tempoRange: TempoRange; // BPM constraints
  dynamicProfile: DynamicProfile; // Velocity/dynamics behavior
  defaultMood: MoodTypeValue; // Starting mood
  supportedMoods: MoodTypeValue[]; // Moods this palette can express
  tags: string[]; // Searchable metadata tags
}
```

### 6.2 Instrument Roles and Texture Layers

Every instrument has a **role** and a **layer**:

**Roles** determine the musical function:

| Role       | Purpose                  | Example                     |
| ---------- | ------------------------ | --------------------------- |
| `lead`     | Primary melody           | Celtic Harp, Synth Lead     |
| `harmony`  | Chordal support          | Ensemble Strings, Pad       |
| `bass`     | Low-frequency foundation | Double Bass, Sub Bass       |
| `rhythm`   | Rhythmic drive           | Bodhrán, Drum Kit           |
| `texture`  | Ambient/atmospheric      | Ethereal Choir, Reverb Wash |
| `accent`   | Punctuation/stingers     | French Horn, Cymbal         |
| `drone`    | Sustained note/cluster   | Tanpura, Synthesizer Drone  |
| `ornament` | Decorative flourishes    | Harp Glissando, Trill       |

**Layers** determine when the instrument activates based on intensity:

| Layer        | Intensity threshold | Purpose                 |
| ------------ | ------------------- | ----------------------- |
| `foundation` | Always active       | Core sonic bed          |
| `core`       | Low                 | Primary musical content |
| `color`      | Medium              | Timbral variety         |
| `sparkle`    | Medium-high         | Brightness and detail   |
| `atmosphere` | Variable            | Ambient texture         |
| `rhythmic`   | Medium              | Rhythmic drive          |

### 6.3 Writing a Palette

Here is a complete example for a hypothetical **Cyberpunk** music palette:

```typescript
import {
  GenreType,
  MoodType,
  ScaleType,
  InstrumentRole,
  TextureLayer,
  type PaletteDefinition,
  type PaletteId,
  type InstrumentEntryId,
  type ChordProgressionId,
} from './palettes.js';

const CYBERPUNK_PALETTE: PaletteDefinition = {
  id: 'palette-cyberpunk' as PaletteId,
  name: 'Cyberpunk',
  genre: GenreType.Cyberpunk,
  description:
    'Dark, futuristic soundscape blending analog synths with glitchy digital ' +
    'textures. Heavy use of minor scales, dissonant chord extensions, and ' +
    'driving electronic rhythms.',

  instruments: [
    {
      id: 'cyberpunk-synth-lead' as InstrumentEntryId,
      name: 'Analog Synth Lead',
      role: InstrumentRole.Lead,
      layer: TextureLayer.Core,
      weight: 0.9,
      minIntensity: 0.2,
      maxIntensity: 1.0,
      panPosition: 0.1, // Slightly right of center
      reverbSend: 0.3,
      tags: ['synth', 'analog', 'lead', 'cyberpunk'],
    },
    {
      id: 'cyberpunk-pad' as InstrumentEntryId,
      name: 'Dark Pad',
      role: InstrumentRole.Harmony,
      layer: TextureLayer.Foundation,
      weight: 1.0,
      minIntensity: 0.0,
      maxIntensity: 0.8,
      panPosition: 0.0, // Center
      reverbSend: 0.6,
      tags: ['synth', 'pad', 'dark', 'ambient'],
    },
    {
      id: 'cyberpunk-sub-bass' as InstrumentEntryId,
      name: 'Sub Bass',
      role: InstrumentRole.Bass,
      layer: TextureLayer.Foundation,
      weight: 0.95,
      minIntensity: 0.1,
      maxIntensity: 0.9,
      panPosition: 0.0,
      reverbSend: 0.1,
      tags: ['bass', 'sub', 'electronic'],
    },
    {
      id: 'cyberpunk-drum-machine' as InstrumentEntryId,
      name: 'Drum Machine',
      role: InstrumentRole.Rhythm,
      layer: TextureLayer.Rhythmic,
      weight: 0.85,
      minIntensity: 0.3,
      maxIntensity: 1.0,
      panPosition: 0.0,
      reverbSend: 0.2,
      tags: ['drums', 'electronic', 'machine'],
    },
    {
      id: 'cyberpunk-glitch' as InstrumentEntryId,
      name: 'Glitch Texture',
      role: InstrumentRole.Texture,
      layer: TextureLayer.Sparkle,
      weight: 0.6,
      minIntensity: 0.4,
      maxIntensity: 1.0,
      panPosition: -0.3,
      reverbSend: 0.5,
      tags: ['glitch', 'texture', 'digital', 'fx'],
    },
    {
      id: 'cyberpunk-stinger' as InstrumentEntryId,
      name: 'Brass Stinger',
      role: InstrumentRole.Accent,
      layer: TextureLayer.Color,
      weight: 0.7,
      minIntensity: 0.5,
      maxIntensity: 1.0,
      panPosition: 0.2,
      reverbSend: 0.4,
      tags: ['brass', 'stinger', 'accent', 'cinematic'],
    },
  ],

  chordProgressions: [
    {
      id: 'cyberpunk-dark-drive' as ChordProgressionId,
      name: 'Dark Drive',
      mood: MoodType.Tense,
      tension: 0.7,
      chords: [
        { root: 0, intervals: [0, 3, 7, 10], name: 'Cm7', tension: 0.5 },
        { root: 5, intervals: [0, 3, 7, 10], name: 'Fm7', tension: 0.4 },
        { root: 8, intervals: [0, 4, 7, 11], name: 'AbMaj7', tension: 0.3 },
        { root: 10, intervals: [0, 3, 6, 10], name: 'Bbm7b5', tension: 0.8 },
      ],
    },
    {
      id: 'cyberpunk-neon-pulse' as ChordProgressionId,
      name: 'Neon Pulse',
      mood: MoodType.Aggressive,
      tension: 0.8,
      chords: [
        { root: 0, intervals: [0, 3, 7], name: 'Cm', tension: 0.5 },
        { root: 3, intervals: [0, 4, 7], name: 'Eb', tension: 0.3 },
        { root: 7, intervals: [0, 3, 7], name: 'Gm', tension: 0.6 },
        { root: 10, intervals: [0, 4, 7], name: 'Bb', tension: 0.4 },
      ],
    },
  ],

  scales: [
    {
      type: ScaleType.HarmonicMinor,
      intervals: [0, 2, 3, 5, 7, 8, 11],
      root: 0,
      mood: MoodType.Tense,
    },
    {
      type: ScaleType.Phrygian,
      intervals: [0, 1, 3, 5, 7, 8, 10],
      root: 0,
      mood: MoodType.Ominous,
    },
    {
      type: ScaleType.Blues,
      intervals: [0, 3, 5, 6, 7, 10],
      root: 0,
      mood: MoodType.Aggressive,
    },
  ],

  textureLayers: [
    {
      layer: TextureLayer.Foundation,
      instruments: [
        'cyberpunk-pad' as InstrumentEntryId,
        'cyberpunk-sub-bass' as InstrumentEntryId,
      ],
      activationIntensity: 0.0,
      deactivationIntensity: 0.0,
      volume: 0.7,
      priority: 10,
    },
    {
      layer: TextureLayer.Core,
      instruments: ['cyberpunk-synth-lead' as InstrumentEntryId],
      activationIntensity: 0.2,
      deactivationIntensity: 0.15,
      volume: 0.8,
      priority: 8,
    },
    {
      layer: TextureLayer.Rhythmic,
      instruments: ['cyberpunk-drum-machine' as InstrumentEntryId],
      activationIntensity: 0.3,
      deactivationIntensity: 0.2,
      volume: 0.75,
      priority: 7,
    },
    {
      layer: TextureLayer.Color,
      instruments: ['cyberpunk-stinger' as InstrumentEntryId],
      activationIntensity: 0.5,
      deactivationIntensity: 0.4,
      volume: 0.6,
      priority: 5,
    },
    {
      layer: TextureLayer.Sparkle,
      instruments: ['cyberpunk-glitch' as InstrumentEntryId],
      activationIntensity: 0.6,
      deactivationIntensity: 0.5,
      volume: 0.5,
      priority: 3,
    },
  ],

  tempoRange: {
    minBpm: 100,
    maxBpm: 160,
    preferredBpm: 128,
    allowRubato: false, // Electronic music is metronomic
  },

  dynamicProfile: {
    minVelocity: 40,
    maxVelocity: 127,
    preferredRange: [60, 110],
    crescendoSpeed: 0.4, // Fast builds for dramatic moments
    decrescendoSpeed: 0.3,
  },

  defaultMood: MoodType.Tense,
  supportedMoods: [
    MoodType.Tense,
    MoodType.Aggressive,
    MoodType.Ominous,
    MoodType.Mysterious,
    MoodType.Heroic,
  ],

  tags: ['cyberpunk', 'electronic', 'dark', 'futuristic', 'synth', 'urban'],
};
```

### 6.4 Music Genre vs Game Genre

Music genres and game genres are **not 1:1**. A single game can use multiple
music palettes, and a single palette can serve many games:

| Game genre    | Likely music palettes      |
| ------------- | -------------------------- |
| FPS           | Action, SciFi              |
| RPG           | Fantasy, Medieval, Eastern |
| Horror        | Horror, Noir               |
| Racing        | Action, SciFi              |
| Battle Royale | Action, Cyberpunk          |

Only create a new music genre if no existing palette captures the sonic identity
you need. You can also blend palettes at runtime using the palette engine's
morph system.

### 6.5 Palette Registration

Register the palette in the palette engine's registry (typically in the same
`palettes.ts` file or via the `PaletteEngine.loadPalette()` method at runtime):

```typescript
// Static registration (in palettes.ts)
export const BUILT_IN_PALETTES: PaletteDefinition[] = [
  FANTASY_PALETTE,
  SCI_FI_PALETTE,
  // ...existing palettes...
  CYBERPUNK_PALETTE,
];

// Runtime registration
const engine = createPaletteEngine();
engine.loadPalette(CYBERPUNK_PALETTE);
```

---

## 7. Step 5 — Configure Performer Layout Adaptation

The performer compositor uses genre information to optimize how performers are
displayed during gameplay.

### 7.1 Genre-to-Layout Mapping

Each genre has a preferred layout configuration that determines performer size,
position, and camera behavior:

```typescript
// In libs/aphrodite/performer-compositor/src/adaptive.ts

export const GameGenre = {
  // ...existing genres...
  BattleRoyale: 'battle-royale',
} as const;
```

### 7.2 Layout Rules

The adaptive layout engine uses a rule-based system. Each rule has a predicate
(when to activate) and a layout suggestion (what to do):

```typescript
// Example: Battle Royale layout rules
const battleRoyaleRules: AdaptiveRule[] = [
  {
    id: 'br-default',
    genre: GameGenre.BattleRoyale,
    priority: 1,
    enabled: true,
    predicate: (ctx) => ctx.genre === GameGenre.BattleRoyale,
    suggestion: {
      performerSize: 0.15, // Small — gameplay is the focus
      performerPosition: 'bottom-right',
      layout: 'pip', // Picture-in-picture
    },
  },
  {
    id: 'br-final-circle',
    genre: GameGenre.BattleRoyale,
    priority: 10,
    enabled: true,
    predicate: (ctx) =>
      ctx.genre === GameGenre.BattleRoyale &&
      ctx.moment === GameMoment.BossEncounter,
    suggestion: {
      performerSize: 0.25, // Larger for dramatic final moments
      performerPosition: 'bottom-center',
      layout: 'overlay',
    },
  },
];
```

### 7.3 Game Moments

The adaptive system recognizes specific game moments that override default
layout:

| Moment          | Typical behavior                         |
| --------------- | ---------------------------------------- |
| `Normal`        | Default genre layout                     |
| `Cutscene`      | Minimize performer, focus on scene       |
| `BossEncounter` | Enlarge performer for emotional reaction |
| `QTE`           | Center and scale performer               |
| `Victory`       | Full-screen celebration layout           |
| `Defeat`        | Sympathetic framing                      |

Map your genre's key moments to these categories when configuring rules.

---

## 8. Step 6 — Visual Effects Integration

Visual effects in Aphrodite are genre-agnostic — the same VFX engines serve all
genres. Genre influence comes through **priority weights** in the graphics
profile.

### 8.1 How Priority Weights Affect VFX

The `effectsPriority` and `postProcessPriority` values in your `GenreProfile`
control the VFX budget:

| Priority value | Effect                                                          |
| -------------- | --------------------------------------------------------------- |
| 0.0–0.3        | Minimal effects — only essential feedback                       |
| 0.3–0.6        | Moderate effects — standard particles, basic post-processing    |
| 0.6–0.8        | Rich effects — full particles, bloom, color grading             |
| 0.8–1.0        | Maximum effects — volumetric lighting, advanced post-processing |

### 8.2 Per-Genre VFX Strategy

When designing VFX for your genre, consider these guidelines:

**Competitive genres (FPS, Fighting, MOBA, Battle Royale):**

- Keep `postProcessPriority` low (0.2–0.4) — visual clarity is paramount
- Set `effectsPriority` medium (0.5–0.7) — feedback effects matter but shouldn't
  obscure gameplay
- Disable `motionBlurRecommended` — perceived input lag

**Atmospheric genres (Horror, RPG, Simulation):**

- Set `postProcessPriority` high (0.7–0.9) — bloom, fog, color grading create
  mood
- Moderate `effectsPriority` (0.5–0.7) — atmospheric particles and lighting
- Enable `motionBlurRecommended` for cinematic feel

**Casual genres (Puzzle, Sandbox):**

- Low everything (0.2–0.4) — clean, readable visuals
- Effects should be celebratory (solve confirmations, build completions)

### 8.3 Available VFX Libraries

Your genre can use any of these VFX engines via their public APIs:

| Library                          | Capabilities                                                                      |
| -------------------------------- | --------------------------------------------------------------------------------- |
| `@aphrodite/vfx-particles`       | Particle emitters, trails, explosions, sparks                                     |
| `@aphrodite/vfx-post-processing` | Bloom, motion blur, color grading, vignette, chromatic aberration                 |
| `@aphrodite/vfx-volumetric`      | Volumetric fog, god rays, atmospheric scattering                                  |
| `@aphrodite/scene-nature`        | Procedural environments (jungle, underwater, volcanic, arctic, zen garden, storm) |

### 8.4 Genre-Specific Preset Overrides for VFX

Use `presetOverrides` in your `GenreProfile` to control VFX-related settings per
quality level:

```typescript
presetOverrides: {
  [GP.LOW]: {
    motionBlur: false,
    volumetrics: false,
    particleQuality: 0.3,
  },
  [GP.MEDIUM]: {
    motionBlur: false,
    volumetrics: false,
    particleQuality: 0.6,
  },
  [GP.HIGH]: {
    motionBlur: false,
    volumetrics: true,
    particleQuality: 0.9,
  },
  [GP.ULTRA]: {
    motionBlur: false,
    volumetrics: true,
    particleQuality: 1.0,
  },
},
```

---

## 9. Step 7 — Testing Your Genre

Every genre needs test coverage across all subsystems.

### 9.1 Graphics Profile Tests

Add tests in `libs/aphrodite/game-runtime/src/config/genre-profiles.spec.ts`:

```typescript
import { describe, it, expect, beforeEach } from 'vitest';
import {
  GenreProfileManager,
  GENRE_PROFILES,
  createGenreProfileManager,
} from './genre-profiles.js';
import { GenreType, HardwareTier } from '../types.js';

describe('Battle Royale genre profile', () => {
  it('should exist in GENRE_PROFILES', () => {
    expect(GENRE_PROFILES[GenreType.BATTLE_ROYALE]).toBeDefined();
  });

  it('should prioritize framerate', () => {
    const profile = GENRE_PROFILES[GenreType.BATTLE_ROYALE];
    expect(profile.prioritizeFramerate).toBe(true);
    expect(profile.targetFps).toBeGreaterThanOrEqual(120);
  });

  it('should have high draw distance priority', () => {
    const profile = GENRE_PROFILES[GenreType.BATTLE_ROYALE];
    expect(profile.drawDistancePriority).toBeGreaterThanOrEqual(0.8);
  });

  it('should not recommend motion blur', () => {
    expect(GENRE_PROFILES[GenreType.BATTLE_ROYALE].motionBlurRecommended).toBe(
      false
    );
  });

  it('should recommend dynamic resolution', () => {
    expect(
      GENRE_PROFILES[GenreType.BATTLE_ROYALE].dynamicResolutionRecommended
    ).toBe(true);
  });

  it('should produce valid settings for all hardware tiers', () => {
    const manager = createGenreProfileManager();
    const tiers: HardwareTier[] = [
      'low',
      'medium',
      'high',
      'ultra',
    ] as HardwareTier[];
    for (const tier of tiers) {
      const settings = manager.getRecommendedSettings(
        GenreType.BATTLE_ROYALE,
        tier
      );
      expect(settings.targetFps).toBeGreaterThan(0);
    }
  });

  it('all priority values should be between 0 and 1', () => {
    const profile = GENRE_PROFILES[GenreType.BATTLE_ROYALE];
    const priorities = [
      profile.drawDistancePriority,
      profile.shadowPriority,
      profile.effectsPriority,
      profile.antiAliasingPriority,
      profile.postProcessPriority,
    ];
    for (const p of priorities) {
      expect(p).toBeGreaterThanOrEqual(0);
      expect(p).toBeLessThanOrEqual(1);
    }
  });
});
```

### 9.2 Device Reaction Profile Tests

Add tests in
`libs/aphrodite/game-testing/src/device-tests/device-tests.spec.ts`:

```typescript
import { describe, it, expect } from 'vitest';
import {
  createGenreReactionProfileValidator,
  createSafetyLimitVerifier,
  GameGenre,
  DEFAULT_SAFETY_LIMITS,
} from '@aphrodite/game-testing';

describe('Battle Royale device reaction profile', () => {
  const validator = createGenreReactionProfileValidator();

  it('should validate conforming samples', () => {
    const result = validator.validate(
      [
        {
          deviceId: 'pad-1',
          type: 'gunshot',
          intensity: 0.6,
          durationMs: 150,
          timestamp: 0,
        },
        {
          deviceId: 'pad-1',
          type: 'explosion',
          intensity: 0.8,
          durationMs: 1200,
          timestamp: 500,
        },
        {
          deviceId: 'pad-1',
          type: 'loot',
          intensity: 0.3,
          durationMs: 100,
          timestamp: 1500,
        },
      ],
      GameGenre.BATTLE_ROYALE
    );

    expect(result.passed).toBe(true);
    expect(result.violations).toHaveLength(0);
  });

  it('should reject intensity above genre maximum', () => {
    const result = validator.validate(
      [
        {
          deviceId: 'pad-1',
          type: 'explosion',
          intensity: 0.95,
          durationMs: 200,
          timestamp: 0,
        },
      ],
      GameGenre.BATTLE_ROYALE
    );

    expect(result.passed).toBe(false);
    expect(result.violations.length).toBeGreaterThan(0);
  });

  it('should reject disallowed reaction types', () => {
    const result = validator.validate(
      [
        {
          deviceId: 'pad-1',
          type: 'magic',
          intensity: 0.5,
          durationMs: 200,
          timestamp: 0,
        },
      ],
      GameGenre.BATTLE_ROYALE
    );

    expect(result.passed).toBe(false);
  });

  it('profile values should not exceed safety limits', () => {
    // This is tested generically for all genres in the main test suite,
    // but it's good practice to assert explicitly for new genres
    const profile = validator.getProfile(GameGenre.BATTLE_ROYALE);
    expect(profile.maxIntensity).toBeLessThanOrEqual(
      DEFAULT_SAFETY_LIMITS.maxIntensity
    );
    expect(profile.maxDurationMs).toBeLessThanOrEqual(
      DEFAULT_SAFETY_LIMITS.maxDurationMs
    );
    expect(profile.maxFrequencyHz).toBeLessThanOrEqual(
      DEFAULT_SAFETY_LIMITS.maxFrequencyHz
    );
  });
});
```

### 9.3 Music Palette Tests

Test that the palette definition is well-formed:

```typescript
import { describe, it, expect } from 'vitest';
import { CYBERPUNK_PALETTE } from './palettes.js';

describe('Cyberpunk music palette', () => {
  it('should have at least one instrument per role', () => {
    const roles = new Set(CYBERPUNK_PALETTE.instruments.map((i) => i.role));
    expect(roles.has('lead')).toBe(true);
    expect(roles.has('harmony')).toBe(true);
    expect(roles.has('bass')).toBe(true);
    expect(roles.has('rhythm')).toBe(true);
  });

  it('should have at least one chord progression', () => {
    expect(CYBERPUNK_PALETTE.chordProgressions.length).toBeGreaterThanOrEqual(
      1
    );
  });

  it('should have at least one scale', () => {
    expect(CYBERPUNK_PALETTE.scales.length).toBeGreaterThanOrEqual(1);
  });

  it('should have valid tempo range', () => {
    const { tempoRange } = CYBERPUNK_PALETTE;
    expect(tempoRange.minBpm).toBeLessThan(tempoRange.maxBpm);
    expect(tempoRange.preferredBpm).toBeGreaterThanOrEqual(tempoRange.minBpm);
    expect(tempoRange.preferredBpm).toBeLessThanOrEqual(tempoRange.maxBpm);
  });

  it('should have valid dynamic profile', () => {
    const { dynamicProfile } = CYBERPUNK_PALETTE;
    expect(dynamicProfile.minVelocity).toBeLessThan(dynamicProfile.maxVelocity);
    expect(dynamicProfile.preferredRange[0]).toBeGreaterThanOrEqual(
      dynamicProfile.minVelocity
    );
    expect(dynamicProfile.preferredRange[1]).toBeLessThanOrEqual(
      dynamicProfile.maxVelocity
    );
  });

  it('instrument weights should be between 0 and 1', () => {
    for (const inst of CYBERPUNK_PALETTE.instruments) {
      expect(inst.weight).toBeGreaterThanOrEqual(0);
      expect(inst.weight).toBeLessThanOrEqual(1);
    }
  });

  it('texture layers should reference valid instrument IDs', () => {
    const instrumentIds = new Set(
      CYBERPUNK_PALETTE.instruments.map((i) => i.id)
    );
    for (const layer of CYBERPUNK_PALETTE.textureLayers) {
      for (const id of layer.instruments) {
        expect(instrumentIds.has(id)).toBe(true);
      }
    }
  });

  it('default mood should be in supported moods', () => {
    expect(CYBERPUNK_PALETTE.supportedMoods).toContain(
      CYBERPUNK_PALETTE.defaultMood
    );
  });
});
```

### 9.4 Running Tests

From the library directory, bypass Nx and run directly:

```bash
# Type check
cd libs/aphrodite/game-runtime && npx tsc --noEmit

# Run specific test file
cd libs/aphrodite/game-runtime && npx vitest run src/config/genre-profiles.spec.ts

# Run all tests in the library
cd libs/aphrodite/game-testing && npx vitest run
```

### 9.5 Test Coverage Checklist

For each new genre, verify:

- [ ] Profile exists in all relevant registries
- [ ] All priority values are in [0, 1]
- [ ] Target FPS is positive and reasonable
- [ ] Motion blur and dynamic resolution recommendations are intentional
- [ ] Preset overrides produce valid settings for all quality levels
- [ ] Device reaction profile respects safety limits
- [ ] Reaction type allowlist includes base types (`haptic`, `vibration`)
- [ ] Music palette has instruments covering lead, harmony, bass, and rhythm
- [ ] Tempo range is valid (min < preferred < max)
- [ ] Dynamic profile velocities are valid (min < max, preferred within range)
- [ ] Texture layer instrument references are valid
- [ ] Performer layout rules activate for the correct genre/moment combos

---

## 10. Reference Tables

### 10.1 Existing Runtime Genres (12)

| Key          | Value        | Target FPS | Prioritize FPS | Motion Blur | Dynamic Res |
| ------------ | ------------ | ---------- | -------------- | ----------- | ----------- |
| `FPS`        | `fps`        | 120        | Yes            | No          | Yes         |
| `TPS`        | `tps`        | 60         | Yes            | Yes         | Yes         |
| `RPG`        | `rpg`        | 60         | No             | Yes         | No          |
| `RTS`        | `rts`        | 60         | No             | No          | Yes         |
| `PLATFORMER` | `platformer` | 60         | Yes            | No          | Yes         |
| `RACING`     | `racing`     | 60         | Yes            | Yes         | Yes         |
| `SIMULATION` | `simulation` | 30         | No             | No          | No          |
| `PUZZLE`     | `puzzle`     | 30         | No             | No          | No          |
| `HORROR`     | `horror`     | 60         | No             | Yes         | No          |
| `SANDBOX`    | `sandbox`    | 60         | No             | No          | Yes         |
| `FIGHTING`   | `fighting`   | 60         | Yes            | No          | No          |
| `MOBA`       | `moba`       | 120        | Yes            | No          | Yes         |

### 10.2 Existing Device Reaction Genres (8)

| Genre      | Intensity | Duration  | Max Hz | Key Types              |
| ---------- | --------- | --------- | ------ | ---------------------- |
| ACTION     | 0.1–0.85  | 20–2000ms | 25     | impact, explosion      |
| HORROR     | 0.05–0.7  | 50–5000ms | 10     | pulse, ambient         |
| RACING     | 0.1–0.9   | 10–3000ms | 30     | engine, crash, surface |
| RHYTHM     | 0.2–0.8   | 10–500ms  | 20     | beat, tap              |
| RPG        | 0.05–0.75 | 30–3000ms | 15     | magic, hit, heal       |
| PUZZLE     | 0.05–0.5  | 20–1000ms | 5      | click, snap, solve     |
| SIMULATION | 0.05–0.6  | 30–4000ms | 10     | feedback, ambient      |
| SPORTS     | 0.1–0.85  | 15–2000ms | 20     | impact, kick, catch    |

### 10.3 Existing Music Genres (10)

| Genre     | Sonic character       | Typical scales                   |
| --------- | --------------------- | -------------------------------- |
| Fantasy   | Orchestral, Celtic    | Major, Dorian, Pentatonic        |
| SciFi     | Electronic, synthetic | Whole Tone, Lydian               |
| Horror    | Dissonant, sparse     | Locrian, Phrygian, Chromatic     |
| Action    | Driving, rhythmic     | Minor, Mixolydian, Blues         |
| Romance   | Warm, lyrical         | Major, Aeolian                   |
| Eastern   | Exotic, ornamental    | Hirajoshi, InSen, Pelog, Slendro |
| Western   | Acoustic, rustic      | Mixolydian, Major, Pentatonic    |
| Steampunk | Mechanical, whimsical | Dorian, Lydian                   |
| Medieval  | Historic, modal       | Dorian, Aeolian, Mixolydian      |
| Noir      | Jazz, moody           | Blues, HarmonicMinor, Chromatic  |

### 10.4 Available Moods (12)

Triumphant, Mysterious, Melancholic, Tense, Serene, Heroic, Ominous, Playful,
Romantic, Aggressive, Ethereal, Solemn

### 10.5 Available Scales (20)

Major, Minor, Dorian, Phrygian, Lydian, Mixolydian, Aeolian, Locrian,
HarmonicMinor, MelodicMinor, WholeTone, Chromatic, Pentatonic, PentatonicMinor,
Blues, HungarianMinor, Hirajoshi, InSen, Pelog, Slendro

---

## 11. Checklist

Use this checklist when adding a new genre:

### Type Definitions

- [ ] Add to `GenreType` in `game-runtime/src/types.ts`
- [ ] Add to `GameGenre` in
      `game-testing/src/device-tests/device-tests-types.ts` (if haptic profiling
      needed)
- [ ] Add to `GenreType` in `cinematic-music-engine/src/palettes.ts` (if new
      music genre needed)
- [ ] Add to `GameGenre` in `performer-compositor/src/adaptive.ts`

### Profiles and Configuration

- [ ] Create `GenreProfile` in `game-runtime/src/config/genre-profiles.ts`
- [ ] Add to `GENRE_PROFILES` record
- [ ] Create `GenreReactionProfile` in
      `game-testing/src/device-tests/device-tests.ts`
- [ ] Add to `DEFAULT_GENRE_PROFILES` record
- [ ] Create `PaletteDefinition` (if new music genre)
- [ ] Register palette in palette engine
- [ ] Add performer layout rules

### Testing

- [ ] Graphics profile tests (priorities, FPS, recommendations)
- [ ] Device reaction profile tests (validation, safety limits)
- [ ] Music palette tests (instruments, progressions, scales, tempo)
- [ ] Type check passes (`npx tsc --noEmit`)
- [ ] All tests pass (`npx vitest run`)

### Documentation

- [ ] Update reference tables in this document
- [ ] Add genre to architecture.md library catalog if creating a genre-specific
      library
