Files
bworld/tests/sound_test.ts
T
2026-11-22 07:54:31 -03:00

352 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// sounds: sounds.json and sounds/ read, checked and packed, and what the client plays and where
import { assert, assertEquals, assertStringIncludes, assertThrows } from "@std/assert";
import { create_mod } from "@/tools/new_mod.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { read_mod, write_mod } from "@/common/mod.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { SoundJson } from "@/common/mod_data.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import { type Listener, Sounds, sounds } from "@/client/sounds.ts";
import { copy_dir, ListOutput, load_as_player, stone_floor, test_game, test_mob, VOLUMES } from "./helpers.ts";
// what an ogg file starts with. nothing decodes them outside the browser, so the rest doesn't have to be audio
const OGG = (n: number) => new Uint8Array([0x4f, 0x67, 0x67, 0x53, n]);
// a folder of mods: the base game, which the template depends on, and one made from the template with these sound
// files and sounds.json
function sound_mod(files: Record<string, Uint8Array>, sounds_json?: Record<string, unknown>) {
const dir = Deno.makeTempDirSync({ prefix: "bworld_sounds_" });
copy_dir("mods/bworld", `${dir}/bworld`);
create_mod("noisy", "Noisy", dir);
for (const [path, bytes] of Object.entries(files)) {
const file = `${dir}/noisy/sounds/${path}`;
Deno.mkdirSync(file.slice(0, file.lastIndexOf("/")), { recursive: true });
Deno.writeFileSync(file, bytes);
}
if (sounds_json) {
Deno.writeTextFileSync(`${dir}/noisy/sounds.json`, JSON.stringify({ format_version: 1, sounds: sounds_json }));
}
return dir;
}
async function checked(dir: string) {
return (await load_and_check(dir)).find((mod) => mod.id === "noisy")!;
}
Deno.test("check-mods reads sounds.json into sounds named after their keys", async () => {
const dir = sound_mod(
{ "walker/step_1.ogg": OGG(1), "walker/step_2.ogg": OGG(2) },
{ "walker/step": { files: ["walker/step_1", "walker/step_2"], volume: 0.5, category: "entities" } },
);
const mod = await checked(dir);
assertEquals(mod.report.errors, []);
assertEquals(mod.report.warnings, []);
assertEquals(mod.sounds.map((sound) => sound.json), [
{ id: "noisy:walker/step", files: ["walker/step_1", "walker/step_2"], volume: 0.5, category: "entities" },
]);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports missing and broken sound files, and warns about ones nothing plays", async () => {
const dir = sound_mod({ "step.ogg": OGG(1), "unused.ogg": OGG(2), "renamed.ogg": new Uint8Array([1, 2, 3]) }, {
step: { files: ["step", "nowhere"] },
loud: { files: ["step"], volume: 2 },
"Bad Name": { files: ["step"] },
odd: { files: ["step"], category: "weather" },
});
const mod = await checked(dir);
const errors = mod.report.errors.join("\n");
assertStringIncludes(errors, "step: there's no sounds/nowhere.ogg");
assertStringIncludes(errors, "loud: volume");
assertStringIncludes(errors, "Bad Name: sound names");
assertStringIncludes(errors, "odd: category");
assertStringIncludes(errors, "sounds/renamed.ogg: isn't an ogg file");
assertEquals(mod.report.warnings, ["sounds/unused.ogg: no sound in sounds.json plays it"]);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("packing a mod keeps its sounds and their files", async () => {
const dir = sound_mod({ "walker/step.ogg": OGG(7) }, { "walker/step": { files: ["walker/step"], range: 24 } });
const mod = read_mod(await pack_mod(await checked(dir)), "noisy.cubi");
assertEquals(mod.data.sounds, [{ id: "noisy:walker/step", files: ["walker/step"], range: 24 }]);
assertEquals([...mod.sounds!], [["walker/step", OGG(7)]]);
// a .cubi whose sound names a file it doesn't have doesn't load
const missing = { ...mod, sounds: new Map() };
assertThrows(() => read_mod(write_mod(missing), "noisy.cubi"), Error, "there's no sounds/walker/step.ogg");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a player's client gets the sounds of the server's mods", async () => {
const dir = sound_mod({ "step.ogg": OGG(1) }, { step: { files: ["step"] } });
await load_as_player(dir);
const output = new ListOutput();
sounds.set_output(output);
assert(sounds.exists("noisy:step"));
sounds.play("noisy:step");
assertEquals(output.voices.map((voice) => voice.file), [{ id: "noisy:step", bytes: OGG(1) }]);
sounds.stop_all();
Deno.removeSync(dir, { recursive: true });
});
// the client
const at = (x: number): Listener => ({ x, y: 0, z: 0, yaw: 0, pitch: 0 });
// a client's sounds with these definitions, each with one file of its own name, and a clock tests move
function client_sounds(definitions: Omit<SoundJson, "files">[]) {
EverythingRegistry.clear();
const files = new Map<string, Uint8Array>();
for (const json of definitions) {
const path = json.id.split(":")[1];
EverythingRegistry.register<SoundJson>("sounds", json.id, { ...json, files: [path] });
files.set(path, OGG(1));
}
const time = { now: 0 };
const client = new Sounds(() => time.now);
client.set_files([{ id: "noisy", sounds: files }]);
const output = new ListOutput();
client.set_output(output);
return { client, output, time };
}
Deno.test("a sound plays at its definition's volume and pitch times the play's", () => {
const { client, output } = client_sounds([{ id: "noisy:click", volume: 0.5, pitch: 2, category: "ui" }]);
const playing = client.play("noisy:click", { volume: 0.5, pitch: 0.75 });
assert(playing.playing);
const [voice] = output.voices;
assertEquals(voice.file.id, "noisy:click");
assertEquals([voice.settings.volume, voice.settings.pitch, voice.settings.category], [0.25, 1.5, "ui"]);
assertEquals(voice.settings.at, undefined);
playing.volume = 2;
assertEquals(voice.settings.volume, 1);
playing.stop();
assert(voice.stopped);
assert(!playing.playing);
assertThrows(() => client.play("noisy:nothing"), Error, "unknown sound noisy:nothing");
});
Deno.test("a sound at a point is only heard within its range, which a louder one reaches further", () => {
const { client, output } = client_sounds([{ id: "noisy:thud", range: 10 }]);
client.frame(at(0), () => undefined, VOLUMES);
assert(!client.play("noisy:thud", { at: { x: 15, y: 0, z: 0 } }).playing);
assertEquals(output.voices.length, 0);
assert(client.play("noisy:thud", { at: { x: 15, y: 0, z: 0 }, volume: 2 }).playing);
assertEquals(output.voices[0].settings.range, 20);
assert(client.play("noisy:thud", { at: { x: 5, y: 0, z: 0 } }).playing);
});
Deno.test("a sound finishes when its file has played", () => {
const { client, output } = client_sounds([{ id: "noisy:thud" }]);
const playing = client.play("noisy:thud");
output.voices[0].ended = true;
client.frame(at(0), () => undefined, VOLUMES);
assert(!playing.playing);
assertEquals(client.voices, 0);
});
Deno.test("a loop out of range waits, and comes back as far in as it would have got", () => {
const { client, output, time } = client_sounds([{ id: "noisy:hum", range: 10 }]);
client.frame(at(0), () => undefined, VOLUMES);
time.now = 100;
const hum = client.play("noisy:hum", { at: { x: 0, y: 0, z: 0 }, loop: true, pitch: 2 });
assertEquals(output.playing.length, 1);
time.now = 103;
client.frame(at(50), () => undefined, VOLUMES);
assertEquals(output.playing.length, 0);
assert(hum.playing);
time.now = 105;
client.frame(at(1), () => undefined, VOLUMES);
assertEquals(output.playing.length, 1);
// 5 seconds at twice the speed
assertEquals(output.playing[0].settings.offset, 10);
});
Deno.test("a loop played before anything can play starts once it can, and a one-off is dropped", () => {
const { client, output } = client_sounds([{ id: "noisy:hum" }, { id: "noisy:thud" }]);
output.ready = false;
const hum = client.play("noisy:hum", { loop: true });
const thud = client.play("noisy:thud");
assert(hum.playing);
assert(!thud.playing);
output.ready = true;
client.frame(at(0), () => undefined, VOLUMES);
assertEquals(output.voices.map((voice) => voice.file.id), ["noisy:hum"]);
});
Deno.test("a sound following an entity moves with it and stops when it goes", () => {
const { client, output } = client_sounds([{ id: "noisy:theme" }]);
const entities = new Map<string, Position>([["jester", { x: 3, y: 0, z: 0 }]]);
const where = (id: string) => entities.get(id);
client.frame(at(0), where, VOLUMES);
const theme = client.play("noisy:theme", { follow: "jester", loop: true });
assertEquals(output.voices[0].settings.at, { x: 3, y: 0, z: 0 });
entities.set("jester", { x: 4, y: 1, z: 0 });
client.frame(at(0), where, VOLUMES);
assertEquals(output.voices[0].settings.at, { x: 4, y: 1, z: 0 });
entities.delete("jester");
client.frame(at(0), where, VOLUMES);
assert(!theme.playing);
assert(output.voices[0].stopped);
});
Deno.test("a sound following an entity this client doesn't have yet waits a frame for it", () => {
const { client, output } = client_sounds([{ id: "noisy:theme" }]);
const entities = new Map<string, Position>();
const where = (id: string) => entities.get(id);
// like one played as the entity's animator is made, before the entity is in the level
const late = client.play("noisy:theme", { follow: "jester" });
const nobody = client.play("noisy:theme", { follow: "nobody" });
assert(late.playing);
assertEquals(output.voices.length, 0);
entities.set("jester", { x: 3, y: 0, z: 0 });
client.frame(at(0), where, VOLUMES);
assert(late.playing);
assertEquals(output.voices.map((voice) => voice.settings.at), [{ x: 3, y: 0, z: 0 }]);
assert(!nobody.playing);
});
Deno.test("at most 64 sounds play at once, and a loop waits for room", () => {
const { client, output } = client_sounds([{ id: "noisy:thud" }, { id: "noisy:hum" }]);
const thuds = Array.from({ length: 64 }, () => client.play("noisy:thud"));
assert(!client.play("noisy:thud").playing);
const hum = client.play("noisy:hum", { loop: true });
assert(hum.playing);
assertEquals(client.voices, 64);
thuds[0].stop();
client.frame(at(0), () => undefined, VOLUMES);
assertEquals(output.voices.at(-1)!.file.id, "noisy:hum");
assertEquals(client.voices, 64);
});
// the server: who it sends sounds to
// what the noisy mod's script does: its bell's shared rule rings when clicked, and /ring x y z [except] [volume] plays
// the ring at x y z with ctx.sounds.play
const NOISY_SCRIPT = `
import type { ServerContext } from "cubi/server";
import type { SharedContext } from "cubi/shared";
export function shared(ctx: SharedContext) {
ctx.components.register_block("noisy:bell", {
on_interact(block) {
ctx.sounds.play("noisy:ring", block.x + 0.5, block.y + 0.5, block.z + 0.5);
return true;
},
});
}
export function server(ctx: ServerContext) {
ctx.commands.register("ring", {
description: "",
usage: "/ring x y z [except] [volume]",
run([x, y, z, except, volume], player) {
ctx.sounds.play("noisy:ring", Number(x), Number(y), Number(z), {
except: except === "except" ? player : undefined,
volume: volume === undefined ? undefined : Number(volume),
});
},
});
}
`;
// a bell block next to where players stand
const BELL = [2, 100, 0] as const;
// a game with the noisy mod, its bell, alice at 0 100 0 and bob 12 blocks along x. the ring is heard 10 blocks away
async function noisy_game() {
const dir = sound_mod({ "ring.ogg": OGG(1) }, { ring: { files: ["ring"], range: 10 } });
Deno.writeTextFileSync(`${dir}/noisy/scripts/main.ts`, NOISY_SCRIPT);
Deno.removeSync(`${dir}/noisy/recipes`, { recursive: true });
Deno.writeTextFileSync(
`${dir}/noisy/blocks/example_block.json`,
JSON.stringify({
format_version: 1,
block: {
id: "noisy:bell",
textures: "noisy:example_block",
interactive: true,
components: { "noisy:bell": {} },
},
}),
);
const t = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
stone_floor(t.game, 16);
t.game.set_block(...BELL, "noisy:bell");
t.join(1, "alice");
t.join(2, "bob");
const move = (conn: number, x: number) => t.send(conn, { type: "move", x, y: 100, z: 0.5, yaw: 0, pitch: 0 });
move(1, 0.5);
move(2, 12.5);
for (let i = 0; i < 5; i++) t.game.tick();
t.take(1);
t.take(2);
// the sounds conn was sent since last asked
const heard = (conn: number) => t.take(conn).filter((m) => m.type === "sound");
return { ...t, move, heard };
}
Deno.test("ctx.sounds.play reaches the players in range, further for a louder sound, and never except", async () => {
const { send, heard } = await noisy_game();
send(1, { type: "chat", text: "/ring 0 101 0" });
assertEquals(heard(1), [{ type: "sound", sound: "noisy:ring", at: [0, 101, 0] }]);
assertEquals(heard(2), []);
send(1, { type: "chat", text: "/ring 0 101 0 nobody 2" });
assertEquals(heard(1).length, 1);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:ring", at: [0, 101, 0], volume: 2 }]);
send(1, { type: "chat", text: "/ring 12 101 0 except" });
assertEquals(heard(1), []);
assertEquals(heard(2).length, 1);
});
Deno.test("a player's sound is only theirs, and a block's comes from its middle", async () => {
const { game, heard } = await noisy_game();
game.mods.player(game.players()[1]).play_sound("noisy:ring", { pitch: 2 });
assertEquals(heard(1), []);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:ring", pitch: 2 }]);
game.mods.block_ref(...BELL, "noisy:bell").play_sound("noisy:ring");
assertEquals(heard(1), [{ type: "sound", sound: "noisy:ring", at: [2.5, 100.5, 0.5] }]);
assertThrows(() => game.mods.player(game.players()[0]).play_sound("noisy:nothing"), Error, "unknown sound");
assertThrows(() => game.mods.player(game.players()[0]).play_sound("noisy:ring", { volume: -1 }), Error, "volume");
});
Deno.test("a mob's sound follows it, for the players who see it within range", async () => {
const { game, heard } = await noisy_game();
const mob = test_mob(game, {}, 4.5, 100, 0.5);
game.tick();
heard(1);
heard(2);
game.mods.mob(mob).play_sound("noisy:ring");
assertEquals(heard(1), [{ type: "sound", sound: "noisy:ring", entity: mob.id }]);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:ring", entity: mob.id }]);
mob.set_position(-6.5, 100, 0.5);
game.tick();
game.mods.mob(mob).play_sound("noisy:ring");
assertEquals(heard(1).length, 1);
assertEquals(heard(2), []);
});
Deno.test("a shared rule's sound isn't sent to the player whose click ran it, whose client played it", async () => {
const { send, heard, move } = await noisy_game();
move(2, 6.5);
send(1, { type: "use_block", x: BELL[0], y: BELL[1], z: BELL[2], face: "west", hit: [0, 0.5, 0.5], seq: 1 });
assertEquals(heard(1), []);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:ring", at: [2.5, 100.5, 0.5] }]);
});