PL
games/rob-revisited / src / Revisited / Audio / MemoryMixer.php · commit f9a1307
<?phpnamespace App\Revisited\Audio;/** A Mixer that plays nothing and remembers everything (tests, the demo's on-screen list). */final class MemoryMixer implements Mixer{    /** @var list<array{name: string, pos: ?array, gain: float, pitch: float, loop: bool, voice: int}> every start, oldest first */    public array $played = [];    /** @var array<int, array{name: string, pos: array, gain: float, loop: bool}> loops still on */    public array $voices = [];    public ?string $music = null;    /** @var array{0: array, 1: array} */    public array $ear = [[0, 0, 0], [0, 0, 1]];    private int $next = 1;    public function play(string $name): void    {        $this->played[] = ['name' => $name, 'pos' => null, 'gain' => 1.0, 'pitch' => 1.0, 'loop' => false, 'voice' => 0];    }    public function playAt(string $name, array $pos, float $gain = 1.0, float $pitch = 1.0, bool $loop = false): int    {        $id = $this->next++;        $this->played[] = ['name' => $name, 'pos' => $pos, 'gain' => $gain, 'pitch' => $pitch, 'loop' => $loop, 'voice' => $id];        if ($loop) {            $this->voices[$id] = ['name' => $name, 'pos' => $pos, 'gain' => $gain, 'loop' => true];        }        return $id;    }    public function update(int $voice, ?array $pos, float $gain): void    {        if (isset($this->voices[$voice])) {            $this->voices[$voice]['gain'] = $gain;            if ($pos !== null) {                $this->voices[$voice]['pos'] = $pos;            }        }    }    public function stop(int $voice): void    {        unset($this->voices[$voice]);    }    public function playing(int $voice): bool    {        return isset($this->voices[$voice]);    }    public function listener(array $pos, array $forward): void    {        $this->ear = [$pos, $forward];    }    public function music(?string $name): void    {        $this->music = $name;    }    public function tick(float $dt): void    {    }    public function stopAll(): void    {        $this->voices = [];        $this->music = null;    }    // ---------------------------------------------------------------------------------------- for tests    /** @return list<string> names started since $from (an index in $played) */    public function names(int $from = 0): array    {        return array_map(fn (array $p): string => $p['name'], array_slice($this->played, $from));    }    /** How many starts of names beginning with $prefix since $from. */    public function count(string $prefix, int $from = 0): int    {        return count(array_filter($this->names($from), fn (string $n): bool => str_starts_with($n, $prefix)));    }    /** The gain of the loop $name now (0: not playing). */    public function loopGain(string $name): float    {        foreach ($this->voices as $v) {            if ($v['name'] === $name) {                return $v['gain'];            }        }        return 0.0;    }}