Eve library

Scene Creation Guide

Guide

Revision 1

On this page

Complete guide for creating, configuring, and testing scenes in the Aphrodite gaming platform. Covers the scene definition format, environment creation, performer integration, effects and atmosphere configuration, transitions, audio, and the rendering pipeline.


Table of Contents#

  1. Scene Architecture
  2. Scene Definition Format
  3. Layers
  4. Effects and Post-Processing
  5. Cameras
  6. Environment and Atmosphere
  7. Audio
  8. Performer Integration
  9. Dynamic Elements
  10. Scene Transitions
  11. Environment Creation Workflow
  12. Gallery and Photography
  13. Testing Scenes
  14. Reference

1. Scene Architecture#

1.1 Library Hierarchy#

The scene system is organized as a core composition engine with domain-specific scene libraries built on top:

Library Purpose Example scenes
@aphrodite/scene-composer Core engine: layers, effects, cameras, audio, performer integration, transitions Foundation for all scenes
@aphrodite/scene-nature Natural environments Jungle, Underwater, Volcanic, Arctic, Zen Garden, Storm
@aphrodite/scene-goddess Scale/divine scenes Cityscape, Mountain, Ocean, Cosmic, Forest
@aphrodite/scene-fantasy Fantasy environments Temple, Fairy Forest, Gothic, Phoenix, Crystal, Astral
@aphrodite/scene-abstract Minimalist/abstract Sacred Geometry, Chrome/Liquid Metal, Void, Kaleidoscope
@aphrodite/scene-urban Urban settings Cyberpunk, Amphitheater, Art Deco, Rooftop
@aphrodite/scene-cosmic Space scenes Nebula Throne, Solar System, Black Hole, Lunar

1.2 Module Structure#

Each scene library follows this structure:

text
libs/aphrodite/scene-{name}/
├── src/
│   ├── index.ts                    # Public API exports
│   └── {module-name}/
│       ├── index.ts                # Module barrel exports
│       ├── {module}-types.ts       # Types, enums, interfaces, presets
│       ├── {module}.ts             # Implementation
│       └── {module}.spec.ts        # Tests (141+ per module)
├── project.json
├── package.json
├── tsconfig.json
└── vitest.config.ts

1.3 Rendering Pipeline#

The scene composer processes scenes through an 8-stage pipeline:

text
1. VALIDATE        → Validate scene definition structure
2. LOAD_ASSETS     → Load mesh, texture, audio assets
3. BUILD_LAYERS    → Initialize layer rendering state
4. APPLY_EFFECTS   → Set up post-processing effect chains
5. CONFIGURE_CAMERAS → Initialize camera system
6. CONFIGURE_AUDIO → Initialize audio sources and soundscapes
7. APPLY_PARAMETERS → Apply environment parameters
8. FINALIZE        → Signal ready, emit SCENE_LOADED

2. Scene Definition Format#

2.1 The SceneDefinition Interface#

Every scene is defined by a single SceneDefinition object:

typescript
interface SceneDefinition {
  id: string; // Unique scene identifier
  name: string; // Display name
  category: SceneCategory; // Nature, Urban, Fantasy, etc.
  layers: SceneLayer[]; // Visual layers (background, terrain, etc.)
  effects: SceneEffect[]; // Post-processing effects
  cameras: SceneCamera[]; // Available cameras
  activeCameraId: string; // Currently active camera
  audioSources: AudioSource[]; // Audio emitters
  audioConfig: AudioConfig; // Global audio settings
  environment: EnvironmentParams; // Lighting, weather, time of day
  parameters: SceneParameter[]; // Tweakable parameters
  bounds: BoundingBox; // Scene boundaries
}

2.2 Scene Categories#

typescript
const SceneCategory = {
  NATURE: 'nature',
  URBAN: 'urban',
  FANTASY: 'fantasy',
  SCIFI: 'sci-fi',
  ABSTRACT: 'abstract',
  UNDERWATER: 'underwater',
  CELESTIAL: 'celestial',
  HISTORICAL: 'historical',
  SURREAL: 'surreal',
  MINIMALIST: 'minimalist',
} as const;

2.3 Creating a Scene#

typescript
import {
  createEmptyScene,
  createLayer,
  createEffect,
  createCamera,
  createAudioSource,
  createParameter,
} from '@aphrodite/scene-composer';

// Start with a blank scene
const scene = createEmptyScene();
scene.name = 'Enchanted Forest';
scene.category = 'fantasy';

// Add layers
scene.layers.push(
  createLayer('background', 'Night Sky'),
  createLayer('terrain', 'Forest Floor'),
  createLayer('vegetation', 'Ancient Trees'),
  createLayer('particles', 'Fireflies'),
  createLayer('atmosphere', 'Mist'),
  createLayer('performer', 'Performer Spot')
);

// Add effects
scene.effects.push(
  createEffect('bloom', 'Magical Glow', { intensity: 0.6, threshold: 0.7 }),
  createEffect('fog', 'Forest Mist', {
    density: 0.3,
    color: { r: 0.3, g: 0.4, b: 0.5, a: 1 },
  }),
  createEffect('god_rays', 'Moonbeams', { intensity: 0.4, decay: 0.95 }),
  createEffect('color_grade', 'Enchanted Palette', {
    temperature: -0.1,
    tint: 0.05,
    saturation: 1.2,
  })
);

// Add cameras
const mainCam = createCamera('orbit', {
  position: { x: 0, y: 5, z: -10 },
  target: { x: 0, y: 1, z: 0 },
  fov: 50,
  orbitRadius: 10,
  orbitSpeed: 0.1,
});
scene.cameras.push(mainCam);
scene.activeCameraId = mainCam.id;

3. Layers#

Layers are the building blocks of scene composition. They are rendered in z-order from back to front.

3.1 Layer Types#

Type Purpose Typical z-order
background Sky, backdrop, distant mountains 0
sky Dynamic sky system, clouds 1
terrain Ground, floor, landscape 2
water Oceans, rivers, ponds 3
vegetation Trees, grass, flowers 4
architecture Buildings, structures, ruins 5
props Interactive/decorative objects 6
fauna Animals, creatures, NPCs 7
atmosphere Fog, mist, dust particles 8
particles Particle effects (fire, sparks) 9
emissive Glowing elements, neon, magic 10
performer Performer placement zone 11
overlay Screen-space overlays 12
hud UI elements 13
custom User-defined layer type varies

3.2 Layer Configuration#

typescript
interface SceneLayer {
  id: string; // Auto-generated unique ID
  name: string; // Display name
  type: LayerType; // One of the 15 types above
  enabled: boolean; // Active/inactive toggle
  visible: boolean; // Render visibility
  zOrder: number; // Rendering order (lower = further back)
  transform: Transform; // Position, rotation, scale
  blend: LayerBlendMode; // How this layer blends with layers below
  params: Record<string, unknown>; // Layer-specific parameters
  tags: string[]; // Searchable tags
  bounds?: BoundingBox; // Optional layer-specific bounds
}

3.3 Layer Management#

typescript
import { SceneComposerEngine } from '@aphrodite/scene-composer';

const engine: SceneComposerEngine = createSceneComposer();

// Add a layer to the active scene
engine.addLayer(createLayer('particles', 'Rain'), sceneId);

// Update layer properties
engine.updateLayer('layer-id', {
  visible: false,
  params: { density: 0.5 },
});

// Reorder layers
engine.reorderLayers(sceneId, ['bg-layer', 'terrain-layer', 'performer-layer']);

// Remove a layer
engine.removeLayer('layer-id', sceneId);

4. Effects and Post-Processing#

4.1 Effect Types#

Effect Description Key parameters
ssao Screen-space ambient occlusion radius, intensity, bias
bloom Light bloom/glow intensity, threshold, radius
dof Depth of field (bokeh) focusDistance, aperture, focalLength
motion_blur Motion blur intensity, samples
color_grade Color grading/LUT temperature, tint, saturation, contrast
vignette Edge darkening intensity, smoothness
chromatic_aberration Color fringing intensity, offset
film_grain Film grain noise intensity, size
god_rays Volumetric light shafts intensity, decay, density
ssr Screen-space reflections intensity, maxDistance
fog Distance fog density, color, nearDistance, farDistance
heat_distortion Heat haze intensity, speed
lens_flare Lens flare intensity, threshold
tone_map Tone mapping exposure, method
sharpen Image sharpening intensity
custom User-defined effect arbitrary params

4.2 Effect Configuration#

typescript
interface SceneEffect {
  id: string;
  name: string;
  type: EffectType;
  enabled: boolean;
  priority: number; // Execution order (lower = first)
  params: Record<string, unknown>;
}

Effects are processed in priority order. Lower priority numbers execute first:

typescript
// Typical effect ordering
scene.effects = [
  createEffect('ssao', 'Ambient Occlusion', { priority: 1 }),
  createEffect('bloom', 'Glow', { priority: 5 }),
  createEffect('dof', 'Bokeh', { priority: 10 }),
  createEffect('color_grade', 'Color', { priority: 15 }),
  createEffect('tone_map', 'Tone Map', { priority: 20 }),
  createEffect('vignette', 'Vignette', { priority: 25 }),
];

4.3 Genre-Appropriate Effects#

Genre/mood Recommended effects Settings
Horror fog, vignette, film_grain, chromatic_aberration High density fog, strong vignette, heavy grain
Fantasy bloom, god_rays, color_grade Warm bloom, ethereal rays
Sci-fi bloom, chromatic_aberration, ssr Cool bloom, subtle aberration
Nature ssao, dof, color_grade, fog Gentle fog, warm grading
Urban night bloom, lens_flare, ssr, chromatic_aberration Neon bloom, wet reflections
Abstract bloom, heat_distortion, color_grade Creative grading, distortion
Underwater fog, color_grade, chromatic_aberration Blue-green grade, distance fog
Cosmic bloom, god_rays, lens_flare Intense bloom, stellar flares

5. Cameras#

5.1 Camera Modes#

Mode Behavior Use case
static Fixed position and target Establishing shots
orbit Orbits around a target point Default performer view
path Follows a predefined spline path Cinematic sequences
track Tracks a moving target Follow performer movement
free User-controlled free camera Debug/exploration
dolly_zoom Vertigo zoom (push in + zoom out) Dramatic reveal
crane Overhead crane movement Bird's-eye transitions
handheld Simulated handheld shake Raw/intimate feel

5.2 Camera Configuration#

typescript
interface SceneCamera {
  id: string;
  mode: CameraMode;
  projection: ProjectionType; // 'perspective' or 'orthographic'
  position: Vec3;
  target: Vec3;
  fov: number; // Field of view (degrees)
  near: number; // Near clip plane
  far: number; // Far clip plane
  orbitRadius: number; // For orbit mode
  orbitSpeed: number; // Orbit speed (rad/s)
  path?: CameraPath; // For path mode
  shake?: CameraShake; // Handheld shake config
}

5.3 Camera Utilities#

typescript
import {
  computeOrbitPosition,
  evaluateCameraPath,
  computeCameraShake,
  computeDollyZoomFOV,
} from '@aphrodite/scene-composer';

// Calculate orbit camera position
const pos = computeOrbitPosition(radius, theta, phi, target);

// Interpolate along a camera path (0.0 to 1.0)
const pathPos = evaluateCameraPath(cameraPath, 0.5);

// Compute shake offset for handheld mode
const shakeOffset = computeCameraShake(shakeConfig, time);

// Dolly zoom: compute FOV for given distance
const fov = computeDollyZoomFOV(baseFOV, currentDistance);

6. Environment and Atmosphere#

6.1 Environment Parameters#

The environment controls global lighting, weather, and atmospheric conditions:

typescript
interface EnvironmentParams {
  timeOfDay: TimeOfDay;
  weather: WeatherType;
  season: Season;
  lighting: LightingParams;
  atmosphere: AtmosphereParams;
}

6.2 Time of Day#

Value Description Sun elevation Color temperature
dawn Early morning Low, east Warm pink/orange
morning Mid-morning Medium-low Warm white
noon Midday Directly overhead Neutral white
afternoon Afternoon Medium-high, west Slightly warm
sunset Dusk Low, west Deep orange/red
dusk Twilight Just below horizon Cool purple/blue
night Night Below horizon Cool blue/silver
midnight Deep night Far below Very dark blue
typescript
import {
  applyTimeOfDay,
  getSunElevation,
  getColorTemperature,
} from '@aphrodite/scene-composer';

// Apply time-of-day to environment parameters
const nightEnv = applyTimeOfDay(environment, 'night');

// Get sun angle for custom calculations
const elevation = getSunElevation('sunset'); // radians

// Get color temperature for lighting
const kelvin = getColorTemperature('dawn'); // warm K value

6.3 Weather Types#

Weather Effects Intensity
clear None None
partly_cloudy Scattered clouds Low
overcast Full cloud cover, diffused light Medium
rain Rain particles, puddles, wet surfaces Medium
heavy_rain Dense rain, reduced visibility High
thunderstorm Rain, lightning, thunder audio Very high
snow Snowflakes, accumulation Medium
blizzard Dense snow, wind, low visibility Very high
fog Distance fog, reduced visibility Medium
sandstorm Sand particles, warm tint High
aurora Northern lights, sky color shifts Low
typescript
import { applyWeather } from '@aphrodite/scene-composer';

const stormEnv = applyWeather(environment, 'thunderstorm');

6.4 Lighting Configuration#

typescript
interface LightingParams {
  sunDirection: Vec3; // Directional light direction
  sunColor: Color; // Sun color (RGBA)
  sunIntensity: number; // 0.0–2.0
  ambientColor: Color; // Ambient fill color
  ambientIntensity: number; // 0.0–1.0
  shadowDarkness: number; // 0.0–1.0 (0 = no shadows)
  shadowSoftness: number; // 0.0–1.0 (1 = fully soft)
  volumetricEnabled: boolean; // Volumetric lighting on/off
  volumetricDensity: number; // Volumetric fog density
}

6.5 Atmosphere Configuration#

typescript
interface AtmosphereParams {
  fogDensity: number; // 0.0–1.0
  fogColor: Color; // Fog tint
  cloudCoverage: number; // 0.0–1.0
  windDirection: Vec2; // XZ wind direction
  windStrength: number; // 0.0–1.0
  mieCoefficient: number; // Atmospheric scattering (haze)
  rayleighCoefficient: number; // Sky color scattering
}

6.6 Environment Interpolation#

Smoothly blend between environment states:

typescript
import { interpolateEnvironment } from '@aphrodite/scene-composer';

// Blend 50% between day and night environments
const twilight = interpolateEnvironment(dayEnv, nightEnv, 0.5);

7. Audio#

7.1 Audio Source Types#

Type Description Spatial
ambient Background environmental sound No
positional 3D positioned sound source Yes
music Background music track No
sfx Sound effects Optional
reverb Reverb zone Zone-based

7.2 Soundscape Layers#

The audio system uses layered soundscapes:

Layer Behavior Example
ambient_bed Continuous background Wind, ocean, forest ambience
random_emitter Random intermittent sounds Bird calls, distant thunder
rhythmic Tempo-driven sound Heartbeat, clockwork
reactive Responds to game events Crowd cheers, alarms
weather Weather-linked audio Rain, wind intensity
time_of_day Time-linked audio Crickets at night, birds at dawn
typescript
import {
  createSoundscape,
  createPositionalSource,
} from '@aphrodite/scene-composer';

// Create a multi-layer soundscape
const forestSoundscape = createSoundscape([
  { type: 'ambient_bed', asset: 'forest-ambience', volume: 0.5 },
  {
    type: 'random_emitter',
    asset: 'bird-calls',
    interval: [5000, 15000],
    volume: 0.3,
  },
  { type: 'weather', asset: 'wind-gusts', volume: 0.4 },
]);

// Create a positional audio source (e.g., a waterfall)
const waterfall = createPositionalSource(
  'waterfall-loop',
  {
    x: 10,
    y: 3,
    z: -5,
  },
  {
    radius: 20,
    attenuation: 'exponential',
    volume: 0.8,
  }
);

7.3 Spatial Audio#

typescript
import {
  computeDistanceAttenuation,
  computePositionalVolume,
  computeSpatialPan,
  computeDopplerShift,
  computeOcclusionAttenuation,
  computeUnderwaterFilter,
} from '@aphrodite/scene-composer';

// Distance-based volume falloff
const volume = computeDistanceAttenuation(distance, radius, 'exponential');

// Stereo panning based on listener orientation
const pan = computeSpatialPan(sourcePos, listenerPos);

// Doppler effect for moving sources
const pitchShift = computeDopplerShift(sourceVel, listenerVel);

// Audio occlusion (walls, objects)
const occluded = computeOcclusionAttenuation(sourcePos, obstacles);

// Underwater muffling based on depth
const filter = computeUnderwaterFilter(depth);

7.4 Reverb#

typescript
import { getReverbPreset, interpolateReverb } from '@aphrodite/scene-composer';

// Get a built-in reverb preset
const caveReverb = getReverbPreset('cave');
const hallReverb = getReverbPreset('hall');

// Blend reverb as player moves between spaces
const blended = interpolateReverb(caveReverb, hallReverb, 0.3);

8. Performer Integration#

The performer integration system places and lights performers within scenes, with biometric-reactive environmental effects.

8.1 Placement Modes#

Mode Behavior Use case
fixed Exact world-space coordinates Precise staging
center_grounded Centered on ground plane Default placement
path Follows a predefined path Walk-on sequences
stage_mark Snaps to predefined marks Multi-position scenes
freeform User-positioned freely Custom setups
typescript
import {
  computeCenterGroundedPosition,
  computeRelativeScale,
  computeAutoFitScale,
} from '@aphrodite/scene-composer';

// Place performer at scene center on ground
const pos = computeCenterGroundedPosition(performer, sceneBounds);

// Scale performer relative to scene size
const scale = computeRelativeScale(performer, sceneBounds);

// Auto-fit performer to camera view
const fitScale = computeAutoFitScale(performer, cameraFOV);

8.2 Performer Lighting#

Three-point lighting is the standard setup:

typescript
import {
  createThreePointLighting,
  updateLightPositions,
} from '@aphrodite/scene-composer';

// Generate key, fill, and rim lights
const lights = createThreePointLighting();

// Update positions to follow performer
updateLightPositions(lights, performerTransform);

Lighting integration modes:

Mode Description
scene_only Performer lit entirely by scene lights
dedicated Performer has independent lighting
hybrid Blend of scene and dedicated lights
emissive Performer emits own light (glow effect)

Configuration:

typescript
interface PerformerLightingConfig {
  mode: LightingIntegrationMode;
  lights: PerformerLight[];
  sceneAmbientInfluence: number; // 0–1, how much scene ambient affects performer
  sceneDirectionalInfluence: number; // 0–1, how much scene sun affects performer
  emissionColor: Color; // Glow color (for emissive mode)
  emissionIntensity: number; // Glow strength
  receiveShadows: boolean;
  castShadows: boolean;
  subsurfaceScatter: number; // Skin translucency
}

8.3 Movement Influence#

The performer's movement affects the scene environment:

Influence type Effect Example
particle_disturbance Scatters nearby particles Walking through fireflies
water_ripple Creates surface ripples Standing in shallow water
vegetation_sway Pushes vegetation aside Walking through tall grass
ground_impact Footstep effects Dust clouds, snow compression
wind_disturbance Disturbs wind field Moving through fog
light_trail Leaves light traces Speed trail effect
sound_propagation Movement-based sound Footsteps, rustling
typescript
import {
  createDefaultMovementInfluences,
  computeMovementState,
} from '@aphrodite/scene-composer';

// Get standard movement influences
const influences = createDefaultMovementInfluences();

// Compute movement metrics from position delta
const state = computeMovementState(performer, deltaTime);
// state.speed, state.direction, state.isGrounded, state.idleTime

8.4 Biometric Mappings#

Map performer biometric data to scene parameters for reactive environments:

typescript
interface BiometricMapping {
  source: BiometricType; // heart_rate, breath_rate, skin_conductance, etc.
  target: SceneReactionTarget; // lighting, particles, atmosphere, audio, effects, etc.
  targetId: string; // Specific element ID to affect
  curve: 'linear' | 'exponential' | 'logarithmic' | 'sigmoid';
  inputRange: Vec2; // [min, max] of biometric input
  outputRange: Vec2; // [min, max] of scene parameter output
  smoothing: number; // 0–1, temporal smoothing
  enabled: boolean;
  inverted: boolean; // Invert the mapping
}

Available biometric sources:

Source What it measures
heart_rate BPM from chest strap or wearable
breath_rate Breaths per minute
skin_conductance Galvanic skin response (arousal)
body_temperature Core temperature
muscle_tension EMG sensor data
vocal_energy Voice loudness/energy
facial_expression Expression classification
movement_energy Overall body activity

Available scene targets:

Target What it controls
lighting Light intensity, color, direction
particles Particle rate, speed, color
atmosphere Fog, wind, cloud density
audio Volume, reverb, pitch
effects Post-processing intensity
parameters Any scene parameter
sky Sky color, star brightness
animations Animation speed, triggers

Example — heart rate controlling particle intensity:

typescript
import { evaluateBiometricMappings } from '@aphrodite/scene-composer';

const mappings: BiometricMapping[] = [
  {
    source: 'heart_rate',
    target: 'particles',
    targetId: 'firefly-emitter',
    curve: 'sigmoid',
    inputRange: { x: 60, y: 120 }, // 60–120 BPM
    outputRange: { x: 0.2, y: 1.0 }, // 20%–100% particle density
    smoothing: 0.3,
    enabled: true,
    inverted: false,
  },
  {
    source: 'skin_conductance',
    target: 'atmosphere',
    targetId: 'fog-layer',
    curve: 'exponential',
    inputRange: { x: 0, y: 1 },
    outputRange: { x: 0.1, y: 0.8 }, // Fog thickens with arousal
    smoothing: 0.5,
    enabled: true,
    inverted: false,
  },
];

const updates = evaluateBiometricMappings(biometricData, mappings);
// Returns parameter updates to apply to scene elements

8.5 Performer Camera#

Dedicated camera modes for framing the performer:

Mode Description
orbit Orbits around performer
over_shoulder Over-shoulder angle
close_up Face close-up
full_body Full body framing
follow Follows performer movement
dolly Slow dolly toward/away
aerial Bird's-eye overhead
first_person Performer POV
typescript
import { computePerformerCameraPosition } from '@aphrodite/scene-composer';

const cameraConfig: PerformerCameraConfig = {
  mode: 'orbit',
  offset: { x: 0, y: 1.5, z: 0 },
  lookAtOffset: { x: 0, y: 1.0, z: 0 },
  distance: 5,
  orbitSpeed: 0.2,
  orbitElevation: 0.3,
  smoothing: 0.1,
  autoReframe: true,
  fovOverride: 45,
};

const camPos = computePerformerCameraPosition(cameraConfig, performerTransform);

9. Dynamic Elements#

9.1 Interactive Props#

Props that respond to the performer and environment:

typescript
import {
  computePropDisplacement,
  computeFlickerIntensity,
} from '@aphrodite/scene-composer';

// Calculate how a prop moves in response to performer influence
const displacement = computePropDisplacement(prop, influences);

// Flicker effect for torches, candles, neon signs
const flickerBrightness = computeFlickerIntensity(flickerConfig, time);

9.2 Fauna AI#

Boid-based animal behavior system:

typescript
import {
  computeSeparation,
  computeAlignment,
  computeCohesion,
  decideFaunaState,
  computeFaunaSteering,
  updateFaunaInstance,
} from '@aphrodite/scene-composer';

// Boid flocking calculations
const separation = computeSeparation(bird, nearbyBirds);
const alignment = computeAlignment(bird, nearbyBirds);
const cohesion = computeCohesion(bird, flock);

// State machine: idle, flee, wander, follow, school
const newState = decideFaunaState(bird, stimuli);

// Compute steering force
const steering = computeFaunaSteering(bird, newState);

// Update position and orientation
updateFaunaInstance(bird, deltaTime);

9.3 Destructible Elements#

typescript
import {
  applyDamage,
  generateDebris,
  repairElement,
} from '@aphrodite/scene-composer';

// Apply damage to a destructible prop
const result = applyDamage(vase, 50, impactPoint);

// Generate debris particles
const debris = generateDebris(vase, damageAmount);

// Repair a broken element
repairElement(vase);

10. Scene Transitions#

10.1 Transition Types#

Transition Description Duration
cut Instant switch 0ms
cross_dissolve Alpha blend between scenes 500–2000ms
fade_through Fade to black then fade in 1000–3000ms
morph Smooth geometry morph 1000–3000ms
portal Portal/window opens between scenes 1500–3000ms
tunnel Travel through a tunnel 2000–4000ms
particle_dissolve Scene dissolves into particles 1500–3000ms
particle_reform Particles reform into new scene 1500–3000ms
radial_wipe Circular wipe 500–1500ms
linear_wipe Directional wipe 500–1500ms
zoom_through Zoom into scene element 1000–2000ms
whip_pan Fast camera whip 300–800ms

10.2 Easing Functions#

Easing Character
linear Constant speed
ease_in Slow start
ease_out Slow end
ease_in_out Slow start and end
ease_in_quad / ease_out_quad / ease_in_out_quad Quadratic variants
ease_in_cubic / ease_out_cubic / ease_in_out_cubic Cubic variants
smoothstep Hermite interpolation
spring Spring physics overshoot
bounce Bouncing settle

10.3 Portal and Tunnel Shapes#

Portal shapes: circle, oval, rectangle, diamond, star, hexagon, keyhole, custom

Tunnel styles: straight, spiral, wormhole, corridor, vortex

10.4 Using Transitions#

typescript
import {
  evaluateEasing,
  computeCrossDissolve,
  computePortalMask,
  computeTunnelTransition,
  computeParticleDissolveTransition,
} from '@aphrodite/scene-composer';

// Ease a transition progress value
const eased = evaluateEasing('ease_in_out', rawProgress);

// Compute cross-dissolve blend factor
const blend = computeCrossDissolve(sourceScene, destScene, eased);

// Compute portal mask (returns alpha mask)
const mask = computePortalMask('circle', eased, center, size);

// Particle dissolve between scenes
const particleState = computeParticleDissolveTransition(source, dest, eased);

11. Environment Creation Workflow#

This section walks through creating a complete scene module from scratch.

11.1 Plan the Scene#

Before coding, define:

  1. Category — Which SceneCategory does this belong to?
  2. Key elements — What unique objects/phenomena define this scene?
  3. Atmosphere — What time of day, weather, and mood?
  4. Performer placement — Where does the performer stand?
  5. Biometric hooks — What reacts to the performer's body?
  6. Audio — What does it sound like?
  7. Parameters — What can be tweaked at runtime?

11.2 Create the Types File#

Define all the scene-specific types, enums, and presets:

typescript
// libs/aphrodite/scene-{name}/src/{module}/{module}-types.ts

// Scene-specific enums
export const TreeVariety = {
  Oak: 'oak',
  Pine: 'pine',
  Willow: 'willow',
} as const;
export type TreeVarietyValue = (typeof TreeVariety)[keyof typeof TreeVariety];

// Scene element interfaces
export interface Tree {
  readonly id: string;
  readonly variety: TreeVarietyValue;
  readonly position: Vec3;
  readonly height: number;
  readonly age: number;
}

// Scene config
export interface ForestSceneConfig {
  readonly treeCount: number;
  readonly density: number;
  readonly season: 'spring' | 'summer' | 'autumn' | 'winter';
  readonly timeOfDay: TimeOfDay;
  readonly performerPosition: Vec3;
  readonly windSpeed: number;
}

// Scene state
export interface ForestSceneState {
  readonly trees: Tree[];
  readonly time: number;
  readonly windDirection: Vec3;
}

// Presets
export const TREE_PRESETS: Record<TreeVarietyValue, Partial<Tree>> = {
  oak: { height: 15, age: 100 },
  pine: { height: 20, age: 80 },
  willow: { height: 10, age: 60 },
};

// Default config
export const DEFAULT_FOREST_CONFIG: ForestSceneConfig = {
  treeCount: 20,
  density: 0.6,
  season: 'summer',
  timeOfDay: 'afternoon',
  performerPosition: { x: 0, y: 0, z: 0 },
  windSpeed: 0.3,
};

11.3 Implement the Scene#

typescript
// libs/aphrodite/scene-{name}/src/{module}/{module}.ts

// Unique ID counters
let nextId = 1;
export function resetForestIdCounters(): void {
  nextId = 1;
}

// Element creation
export function createTree(
  variety: TreeVarietyValue,
  position: Vec3,
  config: ForestSceneConfig
): Tree {
  const preset = TREE_PRESETS[variety];
  return {
    id: `tree-${nextId++}`,
    variety,
    position,
    height: preset.height ?? 10,
    age: preset.age ?? 50,
  };
}

// Element update (called each frame)
export function updateTree(tree: Tree, dt: number, wind: Vec3): Tree {
  // Apply wind sway, growth, seasonal changes...
  return { ...tree };
}

// Scene factory
export function createForestScene(
  config: Partial<ForestSceneConfig> = {}
): ForestSceneState {
  const cfg = { ...DEFAULT_FOREST_CONFIG, ...config };
  const trees: Tree[] = [];
  for (let i = 0; i < cfg.treeCount; i++) {
    const variety = Object.values(TreeVariety)[i % 3];
    trees.push(createTree(variety, randomPosition(cfg.density), cfg));
  }
  return { trees, time: 0, windDirection: { x: 1, y: 0, z: 0 } };
}

// Scene update (main loop)
export function updateForestScene(
  state: ForestSceneState,
  dt: number
): ForestSceneState {
  return {
    ...state,
    time: state.time + dt,
    trees: state.trees.map((t) => updateTree(t, dt, state.windDirection)),
  };
}

11.4 Write Tests#

Follow the established test patterns (141+ tests per module):

typescript
// libs/aphrodite/scene-{name}/src/{module}/{module}.spec.ts
import { describe, it, expect, beforeEach } from 'vitest';
import {
  createForestScene,
  createTree,
  updateTree,
  resetForestIdCounters,
} from './{module}.js';

describe('Forest Scene', () => {
  beforeEach(() => {
    resetForestIdCounters();
  });

  describe('createTree', () => {
    it('should create a tree with correct variety', () => {
      /* ... */
    });
    it('should use preset height values', () => {
      /* ... */
    });
    it('should assign unique IDs', () => {
      /* ... */
    });
  });

  describe('createForestScene', () => {
    it('should create the configured number of trees', () => {
      /* ... */
    });
    it('should use default config when none provided', () => {
      /* ... */
    });
  });

  describe('updateForestScene', () => {
    it('should advance time', () => {
      /* ... */
    });
    it('should update all trees', () => {
      /* ... */
    });
  });
});

11.5 Wire Up Exports#

typescript
// libs/aphrodite/scene-{name}/src/{module}/index.ts
export * from './{module}-types.js';
export * from './{module}.js';

// libs/aphrodite/scene-{name}/src/index.ts
export * from './{module}/index.js';

The scene system includes a gallery/photography mode for capturing and sharing scene screenshots with professional color grading.

12.1 Color Grading#

typescript
import {
  applyColorAdjustments,
  applyToneCurve,
  computeVignetteMultiplier,
  computeGrainValue,
  computeBloomContribution,
} from '@aphrodite/scene-composer';

// Apply color adjustments (temperature, tint, saturation, contrast)
const graded = applyColorAdjustments(pixelColor, adjustments);

// Custom tone curve
const toned = applyToneCurve(luminance, curvePoints);

// Vignette mask
const vignette = computeVignetteMultiplier(screenPos, vignetteConfig);

// Film grain
const grain = computeGrainValue(screenUV, grainIntensity);

12.2 Depth of Field#

typescript
import {
  computeCircleOfConfusion,
  computeDepthOfFieldRange,
} from '@aphrodite/scene-composer';

// Calculate bokeh radius for a given depth
const coc = computeCircleOfConfusion(pixelDepth, dofConfig);

// Get the in-focus range
const range = computeDepthOfFieldRange(dofConfig);

12.3 Composition Guides#

typescript
import {
  computeCompositionOverlay,
  computeRuleOfThirdsScore,
} from '@aphrodite/scene-composer';

// Generate composition guide overlay (rule of thirds, golden ratio, etc.)
const overlay = computeCompositionOverlay('rule_of_thirds', viewport);

// Score a composition for rule-of-thirds alignment
const score = computeRuleOfThirdsScore(subjectPosition);

13. Testing Scenes#

13.1 Scene Validation#

The loading pipeline includes validation. Test that your scene definition passes:

typescript
import { runLoadingPipeline } from '@aphrodite/scene-composer';

const result = runLoadingPipeline(myScene, true /* validate */);
expect(result.success).toBe(true);
expect(result.errors).toHaveLength(0);

13.2 Scene Element Tests#

Test individual scene elements:

typescript
describe('scene elements', () => {
  it('should create elements with unique IDs', () => {
    const a = createElement(...);
    const b = createElement(...);
    expect(a.id).not.toBe(b.id);
  });

  it('should reset ID counters', () => {
    createElement(...);
    resetIdCounters();
    const after = createElement(...);
    expect(after.id).toBe('element-1');
  });

  it('should update with time progression', () => {
    const state = createScene();
    const updated = updateScene(state, 16.67); // ~60 FPS
    expect(updated.time).toBeGreaterThan(state.time);
  });
});

13.3 Running Tests#

bash
# Type check
cd libs/aphrodite/scene-{name} && npx tsc --noEmit

# Run tests
cd libs/aphrodite/scene-{name} && npx vitest run

# Run specific module tests
cd libs/aphrodite/scene-{name} && npx vitest run src/{module}/{module}.spec.ts

14. Reference#

14.1 Scene Categories#

Category Description Libraries
nature Natural outdoor environments scene-nature
urban City and man-made environments scene-urban
fantasy Magical/mythological settings scene-fantasy
sci-fi Futuristic/technological scene-cosmic
abstract Non-representational scene-abstract
underwater Aquatic environments scene-nature
celestial Space/astronomical scene-cosmic
historical Period/historical settings —
surreal Dreamlike/impossible scene-abstract
minimalist Clean, simple scene-abstract

14.2 All Layer Types (15)#

background, sky, terrain, water, atmosphere, particles, props, fauna, vegetation, architecture, emissive, overlay, performer, hud, custom

14.3 All Effect Types (16)#

ssao, bloom, dof, motion_blur, color_grade, vignette, chromatic_aberration, film_grain, god_rays, ssr, fog, heat_distortion, lens_flare, tone_map, sharpen, custom

14.4 All Camera Modes (8)#

static, orbit, path, track, free, dolly_zoom, crane, handheld

14.5 All Transition Types (12)#

cross_dissolve, morph, portal, tunnel, particle_dissolve, particle_reform, cut, fade_through, radial_wipe, linear_wipe, zoom_through, whip_pan

14.6 Existing Scene Modules#

Library Modules
scene-nature Jungle, Underwater, Volcanic, Arctic, Zen Garden, Storm
scene-goddess Cityscape, Mountain, Ocean, Cosmic, Forest, Interactions
scene-fantasy Temple, Fairy Forest, Gothic, Phoenix, Crystal, Astral
scene-abstract Sacred Geometry, Chrome/Liquid Metal, Void, Kaleidoscope
scene-urban Cyberpunk, Amphitheater, Art Deco, Rooftop
scene-cosmic Nebula Throne, Solar System, Black Hole, Lunar