ES
games/rob-revisited / src / Revisited / Audio / Soundscape.php · commit f9a1307
<?phpnamespace App\Revisited\Audio;use App\Revisited\Land\Creature;use App\Revisited\Land\Game;use App\Revisited\Land\Quest;use JumPHP\Kernel\Engine;/** * The sound of "Experience - Rob revisited": every sound is derived from the game state alone, frame after frame * (compared with the previous frame), so the scene only does: * *   enter():  $this->audio = new Soundscape($this->engine); *   update(): $this->audio->update($this->game, $dt);          (after $game->update()) *   exit():   $this->audio->stop(); *   optional: $this->audio->event('click') on menus, event('craft') after a recipe... * * What it plays by itself: *  - footsteps by the ground under Rob (grass, jungle leaves, mud, shallow water, sand, rock, snow, cave echo), one per *    stride (longer strides running, soft ones crouching), jump and landing, swimming strokes, the splash into water; *  - breathing after a long run or when exhausted, the heartbeat (low health / blood, or a predator hunting him), *    pain when hurt, death, victory; *  - ambience beds per zone and time (jungle day / night, plateau wind, dry canyon wind, caves, the Haldi village's *    murmur placed at the village), rain, thunder in storms, lake water when near the shore, fires crackling where *    they burn, random far calls (birds, night whistles, drips, pebbles, ice); *  - the animals where they are (grazers, birds, stalker growls and snarls, crawler clicks and hiss, burrower rumble, *    the glacier brute's roar, the swarm's buzz), Rôdeur shouts, Haldi greetings; *  - at night outdoors, far howls of the night predator from far directions (more often when a stalker is near); *  - a low tension drone and a stinger when something hunts him, music loops by mood (day, night, cave, danger); *  - interface feedback from the state: a message in the log, a pickup (bag grew), eat / drink (vitals rose), a fire *    lit (fires grew), a quest step, a new zone. * * Event names for event($name, $at = null) (flat, or placed at $at = [x, y, z]): *   click open close message | discover quest zone | eat drink craft chop mine pickup | swing hit bow | fire sleep *   win death pain | splash jump land land_hard | thunder stinger howl | or any file name of assets/revisited/sfx. * An event also detected from the state within EVENT_DEDUP seconds plays once. */final class Soundscape{    /** Ground biome => footstep family. */    public const GROUNDS = ['grass' => 'grass', 'jungle' => 'leaves', 'mud' => 'mud', 'sand' => 'sand', 'rock' => 'rock',        'redrock' => 'rock', 'snow' => 'snow', 'ice' => 'snow', 'cave' => 'cave', 'water' => 'water',        'jungle_dense' => 'leaves', 'marsh' => 'mud', 'basalt' => 'rock', 'beach' => 'sand', 'burnt' => 'grass'];    /** Metres between two footsteps. */    public const STRIDE_WALK = 1.45;    public const STRIDE_RUN = 2.3;    public const STRIDE_SNEAK = 0.85;    public const SWIM_STROKE = 1.05;      // seconds    public const EVENT_DEDUP = 0.4;    /** event name => files (one picked at random). */    public const EVENTS = [        'click' => ['ui_click'], 'open' => ['ui_open'], 'close' => ['ui_close'], 'message' => ['ui_message'],        'discover' => ['discover'], 'quest' => ['quest'], 'zone' => ['zone'],        'eat' => ['eat'], 'drink' => ['drink'], 'craft' => ['craft'], 'chop' => ['chop'], 'mine' => ['mine'], 'pickup' => ['pickup'],        'swing' => ['swing'], 'hit' => ['hit'], 'brandish' => ['swing'], 'bow' => ['bow'], 'fire' => ['fire_light'], 'sleep' => ['sleep'],        'win' => ['win'], 'death' => ['death'], 'pain' => ['pain_1', 'pain_2', 'pain_3'],        'splash' => ['splash'], 'jump' => ['jump'], 'land' => ['land_soft'], 'land_hard' => ['land_hard'],        'thunder' => ['thunder_far', 'thunder_near'], 'stinger' => ['stinger_1', 'stinger_2'],        'howl' => ['howl_far_1', 'howl_far_2', 'howl_far_3'],        'climb' => ['pebbles', 'mine', 'breath_1'],        // the combat mode (Land\Combat): a dodge, a critical / a counter, a level gained        'dodge' => ['breath_1', 'breath_2'], 'crit' => ['land_hard'], 'counter' => ['land_hard'], 'levelup' => ['quest'],        // the shield: raised, a blow stopped, a parry        'guard' => ['pickup'], 'block' => ['chop'], 'parry' => ['land_hard', 'chop'],    ];    private const HOSTILE = ['stalker', 'crawler', 'burrower', 'glacier_brute', 'swarm', 'river_croc', 'lava_crab'];    /** species => [file prefix variants, seconds between calls (min, max), heard within (m), when (states or null = any)] */    private const CALLS = [        'grazer' => [['grazer_1', 'grazer_2'], 6.0, 15.0, 35.0, ['idle', 'wander']],        'bird' => [['bird_1', 'bird_2', 'bird_3'], 2.5, 7.0, 40.0, null],        'stalker' => [['stalker_growl'], 4.0, 8.0, 32.0, ['stalk', 'hunt']],        'crawler' => [['crawler_click', 'crawler_click', 'crawler_hiss'], 1.8, 4.0, 18.0, null],        'burrower' => [['burrower_rumble'], 4.0, 8.0, 16.0, ['buried']],        'glacier_brute' => [['brute_roar'], 12.0, 22.0, 55.0, ['hunt', 'stalk', 'wander', 'idle']],    ];    /** species => [new state => file] */    private const ON_STATE = [        'stalker' => ['stalk' => 'stalker_growl', 'hunt' => 'stalker_snarl', 'attack' => 'stalker_snarl'],        'grazer' => ['flee' => 'grazer_alarm'],        'crawler' => ['hunt' => 'crawler_hiss', 'attack' => 'crawler_hiss', 'keep' => 'crawler_hiss', 'flee' => 'crawler_hiss'],        'burrower' => ['emerge' => 'burrower_burst'],        'glacier_brute' => ['hunt' => 'brute_roar'],        'swarm' => [],        'bird' => ['flee' => 'bird_2'],    ];    private const PITCH = ['grazer' => 1.0, 'bird' => 1.0, 'stalker' => 1.0, 'crawler' => 1.2, 'burrower' => 0.8, 'glacier_brute' => 0.85, 'swarm' => 1.0];    public Mixer $mixer;    /** Music loops by mood (false: ambience only). */    public bool $music = true;    /** 0..1, smoothed: how close and how hungry the nearest threat is (read by the demo, tests, the HUD if wanted). */    public float $danger = 0.0;    /** The footstep family under Rob at the last update. */    public string $ground = 'grass';    /** @var list<array{t: float, name: string, at: bool}> the last sounds started (newest last), for a debug list */    public array $recent = [];    /** @var array<string, float> bed name => gain now */    public array $beds = [];    public ?string $mood = null;    private float $time = 0.0;    private float $seed;    private ?string $zone = null;    private bool $first = true;    // movement    private float $px = 0.0;    private float $pz = 0.0;    private float $stepAcc = 0.0;    private int $lastStep = 0;    private bool $wasAir = false;    private bool $wasSwimming = false;    private float $prevVy = 0.0;    private float $strokeTimer = 0.0;    private float $breathTimer = 0.0;    /** out of breath 0..1 (breathing()) */    public float $breathDebt = 0.0;    private bool $panting = false;    private int $breathN = 0;    private float $heartTimer = 0.0;    // state compared with the previous frame    private float $prevHurt = 0.0;    private int $prevMessages = 0;    private string $prevLast = '';    private int $prevBag = 0;    private float $prevHunger = 0.0;    private float $prevThirst = 0.0;    private int $prevFires = 0;    private string $prevQuest = '';    private float $questTimer = 0.0;    private bool $wasDead = false;    private bool $wasWon = false;    /** @var array<string, float> event name => time it last played */    private array $lastEvent = [];    // ambience    /** @var array<string, int> bed name => voice */    private array $bedVoices = [];    /** @var array<string, float> bed name => target gain */    private array $bedTarget = [];    private float $checkTimer = 0.0;    private float $waterNear = 0.0;    private float $waterTimer = 0.0;    private float $ambientTimer = 3.0;    private float $thunderTimer = 8.0;    private float $howlTimer = 12.0;    private ?array $answer = null;    /** @var array<int, int> waterfall thing id => its looping voice */    private array $fallVoices = [];    private bool $wasNight = false;    private float $stingerAt = -100.0;    private float $rawDanger = 0.0;    private float $moodHeld = 0.0;    private ?string $moodWanted = null;    /** @var array<string, int> fire key => voice */    private array $fireVoices = [];    // creatures and people    /** @var array<int, array{state: string, timer: float}> */    private array $seen = [];    /** @var array<int, int> creature id => swarm loop voice */    private array $swarms = [];    /** @var array<int, array{state: string, near: bool, cool: float}> */    private array $people = [];    /** @var list<float> end times of the positional one-shots playing (a cap) */    private array $busy = [];    public function __construct(?Engine $engine = null, ?Mixer $mixer = null, int $seed = 12345)    {        $this->mixer = $mixer ?? ($engine !== null ? new EngineMixer($engine) : new MemoryMixer());        $this->seed = (float) max(1, $seed % 2147483646);    }    // ------------------------------------------------------------------------------------------ API    public function update(Game $g, float $dt): void    {        $dt = is_finite($dt) ? max(0.0, min($dt, 0.25)) : 0.0;        $this->time += $dt;        $eye = [$g->x, $g->eyeY(), $g->z];        $this->mixer->listener($eye, [sin($g->yaw), 0.0, cos($g->yaw)]);        if ($this->first) {            $this->remember($g);            $this->setZone($g->zone->id);            $this->first = false;        } elseif ($g->zone->id !== $this->zone) {            $this->setZone($g->zone->id);            $this->event('zone');            $this->px = $g->x;            $this->pz = $g->z;        }        $vitals = $g->body->vitals();        $this->steps($g, $dt);        $this->breathing($g, $dt, $vitals);        $this->changes($g, $dt, $vitals);        $this->rawDanger = $this->threat($g);        $rate = $this->rawDanger > $this->danger ? 1.2 : 0.25;        $this->danger += max(-$rate * $dt, min($rate * $dt, $this->rawDanger - $this->danger));        $this->heart($dt, $vitals);        $this->creatures($g, $dt);        $this->folk($g, $dt);        $this->howls($g, $dt);        $this->ambience($g, $dt, $eye);        $this->fires($g);        $this->falls($g);        $this->tension();        $this->musicMood($g, $dt);        $this->mixer->tick($dt);        $this->remember($g);    }    /** A one-shot by name (see the class comment), flat or placed at $at. */    public function event(string $name, ?array $at = null): void    {        if (isset($this->lastEvent[$name]) && $this->time - $this->lastEvent[$name] < self::EVENT_DEDUP) {            return;        }        $this->lastEvent[$name] = $this->time;        $files = self::EVENTS[$name] ?? [$name];        $file = $files[$this->pick(count($files))];        if ($at !== null) {            $this->at($file, $at);        } else {            $this->flat($file);        }    }    /** Switches the ambience to a zone (update() does it by itself when Rob changes zone). */    public function setZone(string $zoneId): void    {        if ($zoneId === $this->zone) {            return;        }        $this->zone = $zoneId;        foreach ($this->fireVoices as $v) {            $this->mixer->stop($v);        }        foreach ($this->fallVoices as $v) {            $this->mixer->stop($v);        }        $this->fallVoices = [];        foreach ($this->swarms as $v) {            $this->mixer->stop($v);        }        $this->fireVoices = $this->swarms = $this->seen = $this->people = [];        $this->ambientTimer = 2.0 + 3.0 * $this->rand();        $this->howlTimer = min($this->howlTimer, 10.0 + 10.0 * $this->rand());    }    /** Everything silent (the scene's exit()). */    public function stop(): void    {        $this->mixer->stopAll();        $this->bedVoices = $this->fireVoices = $this->swarms = $this->fallVoices = [];        $this->beds = $this->bedTarget = [];        $this->mood = null;    }    /** The footstep family under Rob now (water when he wades). */    public function groundOf(Game $g): string    {        $z = $g->zone;        if ($z->cave) {            return 'cave';        }        if ($z->water > -999 && $z->waterDepth($g->x, $g->z) > 0.04) {            return 'water';        }        return self::GROUNDS[$z->biomeAt($g->x, $g->z)] ?? 'rock';    }    // ------------------------------------------------------------------------------------------ Rob's body    private function steps(Game $g, float $dt): void    {        $d = hypot($g->x - $this->px, $g->z - $this->pz);        if ($d > 4.0) {            $d = 0.0;           // a jump between zones / a load: no footstep        }        $ground = $g->zone->heightAt($g->x, $g->z);        $air = !$g->swimming && $g->y > $ground + 0.15;        if ($g->swimming) {            if (!$this->wasSwimming) {                $this->event('splash');            }            if ($g->moving) {                $this->strokeTimer -= $dt;                if ($this->strokeTimer <= 0) {                    $this->strokeTimer += self::SWIM_STROKE;                    $this->flat('swim_' . (1 + $this->pick(3)));                }            } else {                $this->strokeTimer = 0.3;            }        } elseif (!$air) {            if ($this->wasAir && $this->prevVy < -3.0) {                $this->event($this->prevVy < -11.0 ? 'land_hard' : 'land');                $this->stepAcc = 0.0;            }            $stride = $g->running ? self::STRIDE_RUN : ($g->crouching ? self::STRIDE_SNEAK : self::STRIDE_WALK);            if ($d > 0.0005) {                $this->stepAcc += $d;                if ($this->stepAcc >= $stride) {                    $this->stepAcc = min($this->stepAcc - $stride, $stride * 0.5);                    $this->footstep($g);                }            } else {                $this->stepAcc = $stride * 0.6;     // the first step comes soon after starting            }        }        if (!$air && !$g->swimming && $g->vy > 2.0 && $this->prevVy <= 0.5) {            $this->event('jump');        } elseif ($air && !$this->wasAir && $g->vy > 2.0) {            $this->event('jump');        }        $this->ground = $this->groundOf($g);        $this->wasAir = $air;        $this->wasSwimming = $g->swimming;        $this->prevVy = $g->vy;    }    private function footstep(Game $g): void    {        $this->ground = $this->groundOf($g);        $v = 1 + $this->pick(4);        if ($v === $this->lastStep) {            $v = $v % 4 + 1;        }        $this->lastStep = $v;        $this->flat(($g->crouching ? 'stepsoft_' : 'step_') . $this->ground . '_' . $v);    }    /**     * Out of breath: an oxygen debt 0..1 that running fills (sprinting twice as fast) and rest pays back (fast standing     * still, slowly walking); he pants above 0.35 and calms down under 0.15, the panting slower as the debt falls.     * @param array<string, float> $vitals     */    private function breathing(Game $g, float $dt, array $vitals): void    {        if ($g->sprinting) {            $this->breathDebt += $dt * 0.11;        } elseif ($g->running || ($g->swimming && $g->moving)) {            $this->breathDebt += $dt * 0.055;        } else {            $this->breathDebt -= $dt * ($g->moving ? 0.03 : 0.09);        }        $this->breathDebt = max(0.0, min(1.0, $this->breathDebt));        $tired = ($vitals['fatigue'] ?? 100) < 10 && ($g->running || $g->sprinting);        if ($this->breathDebt > 0.35 || $tired) {            $this->panting = true;        } elseif ($this->breathDebt < 0.15) {            $this->panting = false;        }        if (!$this->panting || $g->dead()) {            $this->breathTimer = min($this->breathTimer, 0.5);            return;        }        $this->breathTimer -= $dt;        if ($this->breathTimer <= 0) {            $hard = $this->breathDebt;            $this->breathTimer = 2.0 - 0.9 * $hard + 0.15 * $this->rand();            $this->flat('breath_' . (1 + $this->breathN++ % 2));        }    }    /** @param array<string, float> $vitals */    private function heart(float $dt, array $vitals): void    {        $level = max(            ((float) ($vitals['health'] ?? 100) < 35) ? (35 - (float) $vitals['health']) / 35 : 0.0,            ((float) ($vitals['blood'] ?? 5.5) < 3.6) ? min(1.0, (3.6 - (float) $vitals['blood']) / 1.5) : 0.0,            $this->danger > 0.55 ? ($this->danger - 0.3) / 0.7 : 0.0,        );        if ($level <= 0.05 || $this->wasDead) {            $this->heartTimer = 0.2;            return;        }        $this->heartTimer -= $dt;        if ($this->heartTimer <= 0) {            $this->heartTimer = 1.0 - 0.45 * min(1.0, $level);            $this->flat('heartbeat');        }    }    // ------------------------------------------------------------------------------------------ what changed    /** @param array<string, float> $vitals */    private function changes(Game $g, float $dt, array $vitals): void    {        if ($g->hurt > $this->prevHurt + 0.25 && !$g->dead()) {            $this->event('pain');        }        $dead = $g->dead();        if ($dead && !$this->wasDead) {            $this->event('death');        }        $won = $g->won();        if ($won && !$this->wasWon) {            $this->event('win');        }        $msgs = $g->messages();        $last = (string) end($msgs);        if ($last !== '' && ($last !== $this->prevLast || count($msgs) !== $this->prevMessages)) {            $this->event('message');        }        $bag = array_sum($g->inv->all());        if ($bag > $this->prevBag && !$this->recently('craft')) {            $this->event('pickup');        }        if (($vitals['hunger'] ?? 0) > $this->prevHunger + 1.5) {            $this->event('eat');        }        if (($vitals['thirst'] ?? 0) > $this->prevThirst + 1.5) {            $this->event('drink');        }        if (count($g->fires) > $this->prevFires) {            $this->event('fire');        }        $this->questTimer -= $dt;        if ($this->questTimer <= 0) {            $this->questTimer = 0.5;            $key = $this->questKey($g);            if ($key !== $this->prevQuest && $this->prevQuest !== '') {                $this->event('quest');            }            $this->prevQuest = $key;        }    }    private function remember(Game $g): void    {        $v = $g->body->vitals();        $msgs = $g->messages();        $this->prevHurt = $g->hurt;        $this->prevMessages = count($msgs);        $this->prevLast = (string) end($msgs);        $this->prevBag = (int) array_sum($g->inv->all());        $this->prevHunger = (float) ($v['hunger'] ?? 0);        $this->prevThirst = (float) ($v['thirst'] ?? 0);        $this->prevFires = count($g->fires);        $this->wasDead = $g->dead();        $this->wasWon = $g->won();        $this->px = $g->x;        $this->pz = $g->z;        if ($this->prevQuest === '') {            $this->prevQuest = $this->questKey($g);        }        $this->wasNight = $g->isNight();    }    private function questKey(Game $g): string    {        $q = Quest::state($g);        return $q['chapter'] . ':' . count($q['done']) . ':' . $q['objective'];    }    private function recently(string $event): bool    {        return isset($this->lastEvent[$event]) && $this->time - $this->lastEvent[$event] < 1.0;    }    // ------------------------------------------------------------------------------------------ danger    /** 0..1 now: the strongest threat (a hunting predator close by, Rôdeurs on alert). */    private function threat(Game $g): float    {        $t = 0.0;        foreach ($g->creatures as $c) {            if (!in_array($c->species, self::HOSTILE, true) || in_array($c->state, ['dead', 'buried', 'flee'], true)) {                continue;            }            $d = hypot($c->x - $g->x, $c->z - $g->z);            $t = max($t, match ($c->state) {                'hunt', 'attack', 'emerge' => self::clamp(1.15 - $d / 30),                'stalk' => 0.75 * self::clamp(1.1 - $d / 40),                default => 0.35 * self::clamp(1 - $d / 14),            });        }        foreach ($g->npcs as $n) {            if ($n->faction === 'rodeur' && in_array($n->state, ['alert', 'attack'], true)) {                $d = hypot($n->x - $g->x, $n->z - $g->z);                $t = max($t, ($n->state === 'attack' ? 1.0 : 0.7) * self::clamp(1.1 - $d / 45));            }        }        return min(1.0, $t);    }    private function tension(): void    {        if ($this->rawDanger > 0.5 && $this->time - $this->stingerAt > 25.0) {            $this->stingerAt = $this->time;            $this->flat($this->rawDanger > 0.8 ? 'stinger_2' : 'stinger_1');        }        $this->bedTarget['bed_drone'] = 0.75 * $this->danger;    }    // ------------------------------------------------------------------------------------------ animals and people    private function creatures(Game $g, float $dt): void    {        $now = [];        foreach ($g->creatures as $c) {            $id = $c->id;            $now[$id] = true;            $d = hypot($c->x - $g->x, $c->z - $g->z);            $old = $this->seen[$id] ?? null;            $timer = $old === null ? 1.0 + 4.0 * $this->rand() : $old['timer'] - $dt;            if ($old !== null && $old['state'] !== $c->state) {                if ($c->state === 'dead') {                    $this->voice($c, 'creature_death', $d, 50.0);                } elseif (isset(self::ON_STATE[$c->species][$c->state])) {                    $this->voice($c, self::ON_STATE[$c->species][$c->state], $d, 60.0);                    $timer = max($timer, 2.5);                }            }            $call = self::CALLS[$c->species] ?? null;            if ($call !== null && $timer <= 0) {                [$files, $min, $max, $range, $states] = $call;                $timer = $min + ($max - $min) * $this->rand();                if ($d < $range && ($states === null || in_array($c->state, $states, true))) {                    $this->voice($c, $files[$this->pick(count($files))], $d, $range);                }            }            $this->seen[$id] = ['state' => $c->state, 'timer' => $timer];            if ($c->species === 'swarm') {                $this->swarm($c, $d);            }        }        foreach (array_keys($this->seen) as $id) {            if (!isset($now[$id])) {                unset($this->seen[$id]);                if (isset($this->swarms[$id])) {                    $this->mixer->stop($this->swarms[$id]);                    unset($this->swarms[$id]);                }            }        }    }    private function voice(Creature $c, string $file, float $d, float $range): void    {        if ($d > $range) {            return;        }        $pitch = (self::PITCH[$c->species] ?? 1.0) * (0.92 + 0.16 * $this->rand());        $this->at($file, [$c->x, $c->y + 0.8, $c->z], 1.0, $pitch);    }    private function swarm(Creature $c, float $d): void    {        $pos = [$c->x, $c->y + 0.5, $c->z];        $on = $d < 16 && $c->state !== 'dead';        $v = $this->swarms[$c->id] ?? 0;        if ($on && $v === 0) {            $v = $this->mixer->playAt('swarm_loop', $pos, 0.8, 1.0, true);            if ($v > 0) {                $this->swarms[$c->id] = $v;                $this->log('swarm_loop', true);            }        } elseif ($on) {            $this->mixer->update($v, $pos, 0.8);        } elseif ($v !== 0) {            $this->mixer->stop($v);            unset($this->swarms[$c->id]);        }    }    private function folk(Game $g, float $dt): void    {        $now = [];        foreach ($g->npcs as $n) {            $now[$n->id] = true;            $d = hypot($n->x - $g->x, $n->z - $g->z);            $p = $this->people[$n->id] ?? ['state' => $n->state, 'near' => $d < 6, 'cool' => 0.0];            $p['cool'] -= $dt;            $pos = [$n->x, $n->y + 1.6, $n->z];            if ($n->faction === 'rodeur') {                if ($p['state'] !== $n->state && $d < 70) {                    if ($n->state === 'alert' && $p['cool'] <= 0) {                        $this->at('rodeur_shout_' . (1 + $n->id % 2), $pos, 1.0, 0.95 + 0.1 * $this->rand());                        $p['cool'] = 6.0;                    } elseif ($n->state === 'attack' && $p['cool'] <= 3.0) {                        $this->at('rodeur_attack', $pos, 1.0, 0.95 + 0.1 * $this->rand());                        $p['cool'] = 8.0;                    } elseif ($n->state === 'dead') {                        $this->at('death', $pos, 1.0, 1.1);                    }                }            } elseif ($n->faction === 'haldi' && $n->state !== 'sleep') {                $near = $d < 6;                if ($near && !$p['near'] && $p['cool'] <= 0) {                    $this->at('haldi_' . (1 + $n->id % 3), $pos, 0.9, 0.95 + 0.1 * $this->rand());                    $p['cool'] = 45.0;                }                $p['near'] = $near;            }            $p['state'] = $n->state;            $this->people[$n->id] = $p;        }        $this->people = array_intersect_key($this->people, $now);    }    /** At night outdoors: far howls of the night predator, from far directions; sooner when a stalker is near. */    private function howls(Game $g, float $dt): void    {        $night = $g->isNight() && !$g->zone->cave;        if ($night && !$this->wasNight) {            $this->howlTimer = 6.0 + 10.0 * $this->rand();        }        if ($this->answer !== null && $this->time >= $this->answer[0]) {            $this->at($this->answer[1], $this->answer[2], 0.8, 0.9 + 0.15 * $this->rand());            $this->answer = null;        }        if (!$night) {            return;        }        $this->howlTimer -= $dt;        if ($this->howlTimer > 0) {            return;        }        $stalker = null;        $best = 1e9;        foreach ($g->creatures as $c) {            $d = hypot($c->x - $g->x, $c->z - $g->z);            if ($c->species === 'stalker' && $c->state !== 'dead' && $d < $best) {                [$stalker, $best] = [$c, $d];            }        }        $close = $stalker !== null && $best < 70;        $this->howlTimer = $close ? 9.0 + 14.0 * $this->rand() : 28.0 + 40.0 * $this->rand();        if ($stalker !== null && $best < 40 && $stalker->state === 'stalk') {            // the one that follows him: its own, nearer howl, from where it is            $this->at('howl_' . (1 + $this->pick(3)), [$stalker->x, $stalker->y + 1.0, $stalker->z], 1.0, 0.95 + 0.1 * $this->rand());            return;        }        $a = $stalker !== null ? atan2($stalker->x - $g->x, $stalker->z - $g->z) + ($this->rand() - 0.5) * 0.8 : $this->rand() * 6.2832;        $r = 28.0 + 17.0 * $this->rand();        $pos = [$g->x + sin($a) * $r, $g->y + 6.0, $g->z + cos($a) * $r];        $this->at('howl_far_' . (1 + $this->pick(3)), $pos, 1.0, 0.92 + 0.14 * $this->rand());        if ($this->rand() < 0.3) {            $b = $a + 1.6 + $this->rand() * 3.0;            $this->answer = [$this->time + 2.5 + 2.0 * $this->rand(), 'howl_far_' . (1 + $this->pick(3)),                [$g->x + sin($b) * ($r + 8), $g->y + 6.0, $g->z + cos($b) * ($r + 8)]];        }    }    // ------------------------------------------------------------------------------------------ ambience    private function ambience(Game $g, float $dt, array $eye): void    {        $zone = $g->zone;        $light = $g->lightLevel();        $day = self::clamp(($light - 0.15) / 0.35);        $w = $zone->cave ? null : $g->weather;        $kind = $w['kind'] ?? 'clear';        $amount = (float) ($w['amount'] ?? 0.0);        $wet = in_array($kind, ['rain', 'storm'], true) ? $amount : 0.0;        $storm = $kind === 'storm' ? $amount : 0.0;        $snow = $kind === 'snow' ? $amount : 0.0;        $t = ['bed_jungle_day' => 0.0, 'bed_jungle_night' => 0.0, 'bed_wind_plateau' => 0.0, 'bed_wind_canyon' => 0.0,            'bed_cave' => 0.0, 'bed_rain' => 0.0, 'bed_water' => 0.0];        if ($zone->cave) {            $t['bed_cave'] = 0.7;        } elseif ($zone->id === 'plateau') {            $t['bed_wind_plateau'] = 0.5 + 0.35 * max($storm, $snow);        } elseif ($zone->id === 'canyon') {            $t['bed_wind_canyon'] = 0.45 + 0.3 * $storm;            $t['bed_jungle_night'] = 0.2 * (1 - $day);        } else {            $t['bed_jungle_day'] = 0.55 * $day * (1 - 0.6 * $wet);            $t['bed_jungle_night'] = 0.55 * (1 - $day) * (1 - 0.5 * $wet);            $t['bed_wind_plateau'] = 0.3 * $storm;        }        $t['bed_rain'] = $wet > 0 ? 0.25 + 0.55 * $wet : 0.0;        $this->waterTimer -= $dt;        if ($this->waterTimer <= 0) {            $this->waterTimer = 0.5;            $this->waterNear = $this->shore($g);        }        $t['bed_water'] = $g->swimming ? 0.6 : 0.5 * $this->waterNear;        foreach ($t as $k => $v) {            $this->bedTarget[$k] = $v;        }        $this->runBeds($dt, $eye);        $this->village($g);        $this->randomCalls($g, $dt, $day);        if ($storm > 0.05) {            $this->thunderTimer -= $dt;            if ($this->thunderTimer <= 0) {                $this->thunderTimer = (7.0 + 18.0 * $this->rand()) / (0.5 + $storm);                $this->flat($this->rand() < 0.3 ? 'thunder_near' : 'thunder_far');            }        }    }    /** 0..1: how close the lake's edge is (sampled around Rob). */    private function shore(Game $g): float    {        $z = $g->zone;        if ($z->cave || $z->water <= -999) {            return 0.0;        }        if ($z->waterDepth($g->x, $g->z) > 0) {            return 1.0;        }        foreach ([3.0, 6.0, 10.0, 15.0] as $r) {            for ($k = 0; $k < 8; $k++) {                $a = $k * 0.785398;                if ($z->waterDepth($g->x + sin($a) * $r, $g->z + cos($a) * $r) > 0) {                    return self::clamp(1.1 - $r / 16);                }            }        }        return 0.0;    }    private function runBeds(float $dt, array $eye): void    {        $this->checkTimer -= $dt;        $check = $this->checkTimer <= 0;        if ($check) {            $this->checkTimer = 1.0;        }        foreach ($this->bedTarget as $name => $target) {            $gain = $this->beds[$name] ?? 0.0;            $gain += max(-0.35 * $dt, min(0.35 * $dt, $target - $gain));            $this->beds[$name] = $gain;            $v = $this->bedVoices[$name] ?? 0;            if ($gain < 0.004) {                if ($v !== 0) {                    $this->mixer->stop($v);                    unset($this->bedVoices[$name]);                }                unset($this->beds[$name]);                continue;            }            if ($v !== 0 && $check && !$this->mixer->playing($v)) {                $v = 0;             // its voice was taken / muted: start it again            }            if ($v === 0) {                $v = $this->mixer->playAt($name, $eye, $gain, 1.0, true);                if ($v > 0) {                    $this->bedVoices[$name] = $v;                    $this->log($name, false);                }            } else {                $this->mixer->update($v, $eye, $gain);            }        }    }    /** The Haldi village's murmur, placed at the village (canyon). */    private function village(Game $g): void    {        $c = $g->villageCentre();        $v = $this->bedVoices['bed_village'] ?? 0;        if ($c === null) {            if ($v !== 0) {                $this->mixer->stop($v);                unset($this->bedVoices['bed_village']);            }            return;        }        [$x, $z] = [(float) $c[0], (float) $c[1]];        $pos = [$x, $g->zone->heightAt($x, $z) + 2.0, $z];        $gain = $g->isNight() ? 0.45 : 0.9;        if ($v !== 0 && !$this->mixer->playing($v)) {            $v = 0;        }        if ($v === 0) {            $v = $this->mixer->playAt('bed_village', $pos, $gain, 1.0, true);            if ($v > 0) {                $this->bedVoices['bed_village'] = $v;                $this->log('bed_village', true);            }        } else {            $this->mixer->update($v, $pos, $gain);        }        $this->beds['bed_village'] = $gain;    }    /** Fires crackle where they burn (the two nearest within 20 m). */    private function fires(Game $g): void    {        $near = [];        foreach ($g->fires as $f) {            $d = hypot($f['x'] - $g->x, $f['z'] - $g->z);            if ($d < 20) {                $near[sprintf('%.1f:%.1f', $f['x'], $f['z'])] = [$d, $f];            }        }        uasort($near, fn (array $a, array $b): int => $a[0] <=> $b[0]);        $near = array_slice($near, 0, 2, true);        foreach ($this->fireVoices as $key => $v) {            if (!isset($near[$key])) {                $this->mixer->stop($v);                unset($this->fireVoices[$key]);            }        }        foreach ($near as $key => [$d, $f]) {            $pos = [$f['x'], $g->zone->heightAt($f['x'], $f['z']) + 0.4, $f['z']];            if (!isset($this->fireVoices[$key])) {                $v = $this->mixer->playAt('fire_loop', $pos, 0.9, 0.9 + 0.2 * $this->rand(), true);                if ($v > 0) {                    $this->fireVoices[$key] = $v;                    $this->log('fire_loop', true);                }            }        }    }    /** Waterfalls roar where their water hits the pool (heard from far: a loud loop, Audio3d's distance does the rest). */    private function falls(Game $g): void    {        $near = [];        foreach ($g->zone->thingsNear($g->x, $g->z, 95.0) as $t) {            if ($t->kind === 'waterfall') {                $reach = (float) ($t->data['reach'] ?? 5.4);                $near[$t->id] = [$t->x + sin($t->yaw) * $reach, (float) ($t->data['bottom'] ?? $t->y) + 1.5, $t->z + cos($t->yaw) * $reach];            }        }        foreach ($this->fallVoices as $id => $v) {            if (!isset($near[$id])) {                $this->mixer->stop($v);                unset($this->fallVoices[$id]);            }        }        foreach ($near as $id => $pos) {            $v = $this->fallVoices[$id] ?? 0;            if ($v !== 0 && $this->checkTimer >= 0.98 && !$this->mixer->playing($v)) {                $v = 0;            }            if ($v === 0) {                $v = $this->mixer->playAt('waterfall_loop', $pos, 1.0, 1.0, true);                if ($v > 0) {                    $this->fallVoices[$id] = $v;                    $this->log('waterfall_loop', true);                }            }        }        $this->beds['waterfall'] = $near === [] ? 0.0 : 1.0;    }    /** Far calls around Rob (birds, night whistles, drips, pebbles, ice), placed in random directions. */    private function randomCalls(Game $g, float $dt, float $day): void    {        $this->ambientTimer -= $dt;        if ($this->ambientTimer > 0) {            return;        }        $zone = $g->zone;        [$files, $min, $max, $r0, $r1] = match (true) {            $zone->cave => [['drip_1', 'drip_2', 'drip_3', 'drip_1', 'drip_2', 'pebbles'], 2.0, 6.0, 4.0, 14.0],            $zone->id === 'plateau' => [['ice_creak', 'pebbles'], 14.0, 32.0, 12.0, 30.0],            $zone->id === 'canyon' => $day > 0.5 ? [['pebbles', 'bird_3', 'call_day_2'], 9.0, 22.0, 15.0, 35.0] : [['call_night_1', 'pebbles'], 14.0, 30.0, 20.0, 40.0],            default => $day > 0.5 ? [['call_day_1', 'call_day_2', 'bird_1', 'bird_2', 'bird_3'], 4.0, 10.0, 12.0, 35.0]                : [['call_night_1', 'call_night_2'], 9.0, 22.0, 18.0, 40.0],        };        $this->ambientTimer = $min + ($max - $min) * $this->rand();        $a = $this->rand() * 6.2832;        $r = $r0 + ($r1 - $r0) * $this->rand();        $y = $zone->cave ? $g->eyeY() + 1.0 : $g->y + 3.0 + 6.0 * $this->rand();        $this->at($files[$this->pick(count($files))], [$g->x + sin($a) * $r, $y, $g->z + cos($a) * $r], 0.8, 0.9 + 0.2 * $this->rand());    }    private function musicMood(Game $g, float $dt): void    {        $want = !$this->music || $g->dead() ? null : match (true) {            $this->danger > 0.5 => 'music_danger',            $g->zone->cave => 'music_cave',            $g->isNight() => 'music_night',            default => 'music_day',        };        if ($want !== $this->moodWanted) {            $this->moodWanted = $want;            $this->moodHeld = 0.0;        }        $this->moodHeld += $dt;        $hold = $want === 'music_danger' || $this->mood === null ? 0.8 : 4.0;        if ($want !== $this->mood && $this->moodHeld >= $hold) {            $this->mood = $want;            $this->mixer->music($want);        }    }    // ------------------------------------------------------------------------------------------ helpers    private function flat(string $file): void    {        $this->mixer->play($file);        $this->log($file, false);    }    private function at(string $file, array $pos, float $gain = 1.0, float $pitch = 1.0): void    {        $this->busy = array_values(array_filter($this->busy, fn (float $end): bool => $end > $this->time));        if (count($this->busy) >= 6) {            return;            // Audio3d has 16 voices: keep room for the beds and loops        }        $this->busy[] = $this->time + 3.0;        $this->mixer->playAt($file, $pos, $gain, $pitch);        $this->log($file, true);    }    private function log(string $name, bool $at): void    {        $this->recent[] = ['t' => $this->time, 'name' => $name, 'at' => $at];        if (count($this->recent) > 12) {            array_shift($this->recent);        }    }    /** 0..1 (Park-Miller in floats: the same on 32-bit PHP). */    private function rand(): float    {        $this->seed = fmod($this->seed * 16807.0, 2147483647.0);        return ($this->seed - 1) / 2147483646.0;    }    private function pick(int $n): int    {        return min($n - 1, (int) floor($this->rand() * $n));    }    private static function clamp(float $v): float    {        return max(0.0, min(1.0, $v));    }}