Files
2026-11-22 08:35:54 -03:00

521 lines
22 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";
import { client_level } from "./client_level.ts";
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { ChunkColumn } from "@/common/section.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import type { EntityInfo } from "@/common/protocol.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 sound played with an offset starts as if it had started that long ago", () => {
const { client, output, time } = client_sounds([{ id: "noisy:theme", range: 10 }]);
client.frame(at(0), () => undefined, VOLUMES);
time.now = 100;
client.play("noisy:theme", { offset: 12 });
// its file at twice the speed is twice as far in
client.play("noisy:theme", { offset: 12, pitch: 2 });
assertEquals(output.voices.map((voice) => voice.settings.offset), [12, 24]);
// a loop coming back in range keeps counting from when it would have started
output.voices.length = 0;
client.play("noisy:theme", { at: { x: 0, y: 0, z: 0 }, loop: true, offset: 30 });
time.now = 103;
client.frame(at(50), () => undefined, VOLUMES);
time.now = 105;
client.frame(at(1), () => undefined, VOLUMES);
assertEquals(output.playing.at(-1)!.settings.offset, 35);
assertThrows(() => client.play("noisy:theme", { offset: -1 }), Error, "offset");
});
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;
// the noisy mod's folder: its bell, a rock whose sounds are "noisy:rock", a walker whose sounds are "noisy:walker"
// and a quiet entity without any
function noisy_dir() {
const dir = sound_mod(
Object.fromEntries(["ring", "rock_break", "rock_place", "rock_step", "walker_step", "walker_hurt"].map(
(name, i) => [`${name}.ogg`, OGG(i)],
)),
{
ring: { files: ["ring"], range: 10 },
"rock/break": { files: ["rock_break"] },
"rock/place": { files: ["rock_place"] },
"rock/step": { files: ["rock_step"] },
"walker/step": { files: ["walker_step"] },
"walker/hurt": { files: ["walker_hurt"] },
},
);
Deno.writeTextFileSync(`${dir}/noisy/scripts/main.ts`, NOISY_SCRIPT);
Deno.removeSync(`${dir}/noisy/recipes`, { recursive: true });
const data = (path: string, key: string, json: Record<string, unknown>) =>
Deno.writeTextFileSync(`${dir}/noisy/${path}`, JSON.stringify({ format_version: 1, [key]: json }));
data("blocks/example_block.json", "block", {
id: "noisy:bell",
textures: "noisy:example_block",
interactive: true,
components: { "noisy:bell": {} },
});
data("blocks/rock.json", "block", {
id: "noisy:rock",
textures: "noisy:example_block",
mining: { toughness: 1 },
sounds: "noisy:rock",
});
Deno.mkdirSync(`${dir}/noisy/entities`);
const entity = { texture: "noisy:example_block", behavior: "scripted", width: 0.6, height: 1.8 };
data("entities/walker.json", "entity", { id: "noisy:walker", ...entity, sounds: "noisy:walker" });
data("entities/quiet.json", "entity", { id: "noisy:quiet", ...entity });
return dir;
}
// 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,
// the rock 16
async function noisy_game() {
const dir = noisy_dir();
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] }]);
});
// blocks' and entities' "sounds"
Deno.test("check-mods reports a block's or entity's sounds that have none of what they can have", async () => {
const dir = noisy_dir();
const rock = JSON.parse(Deno.readTextFileSync(`${dir}/noisy/blocks/rock.json`));
rock.block.sounds = "noisy:rok";
Deno.writeTextFileSync(`${dir}/noisy/blocks/rock.json`, JSON.stringify(rock));
const walker = JSON.parse(Deno.readTextFileSync(`${dir}/noisy/entities/walker.json`));
walker.entity.sounds = "noisy:walkr";
Deno.writeTextFileSync(`${dir}/noisy/entities/walker.json`, JSON.stringify(walker));
const errors = (await checked(dir)).report.errors;
assertEquals(errors, [
"blocks/rock.json: sounds noisy:rok has none of noisy:rok/break, noisy:rok/place, noisy:rok/step, noisy:rok/hit",
"entities/walker.json: sounds noisy:walkr has none of noisy:walkr/hurt, noisy:walkr/death, noisy:walkr/step, " +
"noisy:walkr/ambient",
]);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a player breaking or placing a block is heard by everyone near but them, whose client played it", async () => {
const { game, send, heard } = await noisy_game();
const rock_at = [-2, 100, 0] as const;
game.set_block(...rock_at, "noisy:rock");
send(1, { type: "break_block", x: rock_at[0], y: rock_at[1], z: rock_at[2], seq: 1 });
assertEquals(game.world.get_block_id(...rock_at), "cubi:air");
assertEquals(heard(1), []);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:rock/break", at: [-1.5, 100.5, 0.5] }]);
send(1, { type: "chat", text: "/give noisy:rock" });
send(1, { type: "use_block", x: rock_at[0], y: 99, z: rock_at[2], face: "top", hit: [0.5, 1, 0.5], seq: 2 });
assertEquals(game.world.get_block_id(...rock_at), "noisy:rock");
assertEquals(heard(1), []);
assertEquals(heard(2), [{ type: "sound", sound: "noisy:rock/place", at: [-1.5, 100.5, 0.5] }]);
// broken by something that isn't a player, like a script, everyone hears it from the server
game.destroy_block(...rock_at);
assertEquals(heard(1).length, 1);
assertEquals(heard(2).length, 1);
});
// a client with the noisy mod, a floor of its rock under y 100 and the listener just above it, its sounds going to
// output
async function noisy_client() {
const dir = noisy_dir();
await load_as_player(dir);
Deno.removeSync(dir, { recursive: true });
const { level } = client_level(DEFAULT_SHAPE);
const rock = EverythingRegistry.get_id("blocks", "noisy:rock")!;
const flat = new Uint32Array(DEFAULT_SHAPE.volume).fill(rock, 99 * CHUNK_AREA, 100 * CHUNK_AREA);
level.set_chunk(ChunkColumn.from_flat(0, 0, DEFAULT_SHAPE, flat, new Array(CHUNK_AREA).fill("bworld:plains")));
const output = new ListOutput();
sounds.stop_all();
sounds.set_output(output);
sounds.frame({ x: 8, y: 101, z: 8, yaw: 0, pitch: 0 }, () => undefined, VOLUMES);
const entity = (type: string) =>
new RemoteEntity(level, {
kind: "entity",
id: type,
type,
x: 8.5,
y: 100,
z: 8.5,
yaw: 0,
pitch: 0,
data: {},
} as Extract<EntityInfo, { kind: "entity" }>);
// walks entity along x, distance blocks a tick for ticks
const walk = (entity: RemoteEntity, distance: number, ticks: number) => {
for (let i = 0; i < ticks; i++) {
entity.save_previous_position();
entity.x += distance;
entity.tick();
}
};
// what's played since last asked, as [file, volume]
const played = () => {
const voices = output.voices.map((voice) => [voice.file.id, voice.settings.volume]);
output.voices.length = 0;
return voices;
};
return { entity, walk, played };
}
Deno.test("an entity steps every 1.6 blocks it walks on a block: its own step, or the block's quieter one", async () => {
const { entity, walk, played } = await noisy_client();
const walker = entity("noisy:walker");
walk(walker, 0.4, 8);
assertEquals(played(), [["noisy:walker_step", 1], ["noisy:walker_step", 1]]);
const quiet = entity("noisy:quiet");
walk(quiet, 0.4, 5);
assertEquals(played(), [["noisy:rock_step", 0.15]]);
// in the air there's nothing to step on
quiet.set_position(8.5, 104, 8.5);
walk(quiet, 0.4, 8);
assertEquals(played(), []);
sounds.stop_all();
});
Deno.test("an entity sounds hurt when it's hurt, and only what it has", async () => {
const { entity, played } = await noisy_client();
entity("noisy:walker").on_event("hurt");
assertEquals(played(), []);
// heard following it, once the frame finds where it is
sounds.frame({ x: 8, y: 101, z: 8, yaw: 0, pitch: 0 }, () => ({ x: 8.5, y: 100, z: 8.5 }), VOLUMES);
assertEquals(played(), [["noisy:walker_hurt", 1]]);
// it has no death sound, and the quiet one has none at all
entity("noisy:walker").on_event("death");
entity("noisy:quiet").on_event("hurt");
sounds.frame({ x: 8, y: 101, z: 8, yaw: 0, pitch: 0 }, () => ({ x: 8.5, y: 100, z: 8.5 }), VOLUMES);
assertEquals(played(), []);
sounds.stop_all();
});