Sounds on shared and server

This commit is contained in:
2026-11-22 07:44:13 -03:00
parent 47934b272c
commit 8e587f6446
16 changed files with 386 additions and 30 deletions
+2
View File
@@ -241,6 +241,8 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
fluid_rules,
recipes: () => recipe_book,
running: () => rules_setup,
// rules only run here to guess what the player's own actions do, so this is the sound their action makes
play_sound: (sound, x, y, z, options) => sounds.play(sound, { ...options, at: { x, y, z } }),
}));
rules_setup = false;
check_recipe_types(recipe_book);
+15
View File
@@ -12,6 +12,7 @@ import { ItemEntity } from "./entity/item_entity.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts";
import { menu_screens, receive_mod_message, receive_overlay_message } from "./mods.ts";
import { sounds } from "./sounds.ts";
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
// fit in CHUNK_BUDGET_MS
@@ -195,6 +196,20 @@ export class ClientPacketListener {
case "break_progress":
level.set_break_progress(message.x, message.y, message.z, message.stage);
break;
case "sound": {
const at = message.at;
try {
sounds.play(message.sound, {
at: at && { x: at[0], y: at[1], z: at[2] },
follow: message.entity,
volume: message.volume,
pitch: message.pitch,
});
} catch (e) {
console.warn(`the server played a sound this client can't:`, e);
}
break;
}
case "push": {
const player = client.player;
player.vx += message.motion[0];
+3 -7
View File
@@ -5,14 +5,12 @@
// sounds.json, see docs/modding/resources/sounds.md. this decides what plays, an output (client/audio_output.ts in the
// browser) plays it
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { SoundCategory, SoundJson } from "@/common/mod_data.ts";
import { sound_range, sound_to_play, type SoundCategory, type SoundJson } from "@/common/mod_data.ts";
import type { ClientPlayOptions, PlayingSound } from "@/common/mod_api/client.ts";
import type { Position } from "@/common/mod_api/shared.ts";
export type Volumes = Record<"master" | SoundCategory, number>;
// how far away a sound is heard at volume 1 when its definition doesn't say
const DEFAULT_RANGE = 16;
// sounds playing at once at most. past that a new one is dropped, and loops wait for room
const MAX_VOICES = 64;
@@ -114,9 +112,8 @@ class Playing implements PlayingSound {
return (this.json.pitch ?? 1) * this.#pitch;
}
// a louder sound is heard further, like a sound at volume 2 twice as far
get range() {
return (this.json.range ?? DEFAULT_RANGE) * Math.max(1, this.total_volume);
return sound_range(this.json, this.#volume);
}
// whether the listener is close enough to hear it, always for one heard as it is
@@ -159,8 +156,7 @@ export class Sounds {
}
play(sound: string, options: ClientPlayOptions = {}): PlayingSound {
const json = EverythingRegistry.get<SoundJson>("sounds", sound);
if (!json) throw new Error(`unknown sound ${sound}`);
const json = sound_to_play(sound, options);
const path = json.files[Math.floor(Math.random() * json.files.length)];
const file = this.#files.get(`${sound.split(":")[0]}:${path}`);
if (!file) throw new Error(`sound ${sound} has no file ${path}`);
+21
View File
@@ -11,6 +11,7 @@ import type {
Id,
ItemStack,
ModInfo,
PlayOptions,
Position,
RecipeLookup,
Season,
@@ -32,6 +33,7 @@ export type {
Id,
ItemStack,
ModInfo,
PlayOptions,
Position,
Season,
TagApi,
@@ -65,9 +67,19 @@ export interface ServerContext {
ui: ServerUi;
net: ServerNet;
storage: ModStorage;
// sounds from the mods' sounds.json, played on players' clients, see docs/modding/resources/sounds.md
sounds: ServerSounds;
log(...args: unknown[]): void;
}
// one-off sounds. what lasts, like a machine's hum, is a client phase's to play, see ClientSounds in cubi/client
export interface ServerSounds {
// once at x y z, for every player within its range. except leaves out a player whose own client already played it,
// like the one whose click a client phase answered with a sound. throws for a sound no mod defines
play(sound: Id, x: number, y: number, z: number, options?: PlayOptions & { except?: Player }): void;
exists(sound: Id): boolean;
}
// components
export interface BlockRef {
@@ -90,6 +102,8 @@ export interface BlockRef {
// turns on_tick and on_second off for this block, or back on, like a machine with nothing to do. it stays off until
// it's turned on again, saved with the world, and goes with the block
set_ticking(ticking: boolean): void;
// ctx.sounds.play at its middle
play_sound(sound: Id, options?: PlayOptions): void;
}
// P is the component's params from the block json
@@ -295,6 +309,8 @@ export interface MobRef extends LivingRef {
// removes one
get_client_data<T>(field: string): T | undefined;
set_client_data(field: string, value: unknown): void;
// a sound following it, like EntityRef.play_sound
play_sound(sound: Id, options?: PlayOptions): void;
}
// commands, brigadier's way like neoforge's: see common/commands.ts and docs/modding/misc/commands.md
@@ -570,6 +586,8 @@ export interface EntityRef {
// changes what an item lying around is, like ItemEntity.setItem. undefined or a count of 0 removes it. throws for
// every other kind of entity
set_item(item: ItemStack | undefined): void;
// a sound following it, once, for every player who sees it and is within its range
play_sound(sound: Id, options?: PlayOptions): void;
}
export interface Player {
@@ -634,6 +652,9 @@ export interface Player {
// every tick, then on_finish_using after ticks, or on_release_using if they let go first. -1 uses it until they let
// go, like a bow. it slows them down like sneaking. for an on_use to call. switching away from it stops it
start_using(ticks: number): void;
// a sound only they hear, as it is wherever they are, like one in a menu. ctx.sounds.play for one others near
// them hear too
play_sound(sound: Id, options?: PlayOptions): void;
// stops using it without on_release_using or on_finish_using, like stopUsingItem
stop_using(): void;
is_using(): boolean;
+6
View File
@@ -190,6 +190,12 @@ export interface SharedContext {
// registers stops its mod loading once every shared phase has set up. see RecipeType
register_type<R, I>(type: Id, rules: RecipeType<R, I>): void;
} & RecipeLookup;
readonly sounds: {
// once at x y z, from a rule. on the server, for every player in range but the one whose break, place or click
// ran the rule, since their client ran it too and played it already. on a client, only there. throws for a
// sound no mod defines. see docs/modding/resources/sounds.md
play(sound: Id, x: number, y: number, z: number, options?: PlayOptions): void;
};
readonly components: {
// the rules of a block component, the same id the server phase registers the rest of it under
// deno-lint-ignore no-explicit-any
+24
View File
@@ -8,6 +8,7 @@ import { is_tint_color, type TintColor } from "./worldgen/biome_colors.ts";
import {
type BlockRegistry,
type BlockStateDefinition,
EverythingRegistry,
FLUID_DEFAULTS,
FLUID_LEVEL,
type FluidContainerProperties,
@@ -25,6 +26,7 @@ import {
import type { BlockPart, BlockVariant, ModelFileJson } from "./block_models.ts";
import { expand_items, list_matches } from "./tags.ts";
import { GAME_VERSION } from "./constants.ts";
import type { PlayOptions } from "./mod_api/shared.ts";
import {
by_kind,
color,
@@ -636,6 +638,28 @@ export function validate_sound(json: unknown): Problems {
return find_problems(sound_schema, json);
}
// how far away a sound is heard at volume 1 when its definition doesn't say
const DEFAULT_SOUND_RANGE = 16;
// how far a sound played at volume is heard: its range, further for a louder one, like twice as far at volume 2
export function sound_range(json: SoundJson, volume = 1) {
return (json.range ?? DEFAULT_SOUND_RANGE) * Math.max(1, (json.volume ?? 1) * volume);
}
// a mod playing sound with options: its definition, or an error saying what's wrong with them
export function sound_to_play(sound: unknown, options: PlayOptions = {}): SoundJson {
const json = typeof sound === "string" ? EverythingRegistry.get<SoundJson>("sounds", sound) : undefined;
if (!json) throw new Error(`unknown sound ${sound}`);
const { volume = 1, pitch = 1 } = options;
if (typeof volume !== "number" || !(volume >= 0) || !Number.isFinite(volume)) {
throw new Error(`a sound's volume must be 0 or more`);
}
if (typeof pitch !== "number" || !(pitch > 0) || !Number.isFinite(pitch)) {
throw new Error(`a sound's pitch must be more than 0`);
}
return json;
}
// whether a file starts the way every ogg does, so a wav or mp3 renamed to .ogg is caught when the mod is checked
// instead of failing to play
export function is_ogg(bytes: Uint8Array): boolean {
+11 -1
View File
@@ -12,7 +12,7 @@ export const AIR_ID = "cubi:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 29;
export const PROTOCOL_VERSION = 30;
export interface PlayerInfo {
id: string;
@@ -267,6 +267,16 @@ export type ServerMessage =
// cracks on a block a machine is breaking, from 0 to BREAK_STAGES, to the players who have its chunk. none without
// a stage, and when the block changes
| { type: "break_progress"; x: number; y: number; z: number; stage?: number }
// a sound from a mod's sounds.json, played once: at a point, following an entity, or with neither heard as it is.
// volume and pitch multiply its own, 1 when not given
| {
type: "sound";
sound: string;
at?: [number, number, number];
entity?: string;
volume?: number;
pitch?: number;
}
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
| { type: "cursor"; item: ItemData | null }
// a menu opened, replacing any other. id counts 1 to 100 and around, type is the menu type whose screen draws it.
+11 -1
View File
@@ -3,7 +3,8 @@
// what mods' shared phases get, built the same way on the server and every client so they register the same rules and
// recipes. each side gives it its own world, rules and recipe book
import type { ModInfo, SharedContext, SharedWorld } from "./mod_api/shared.ts";
import type { ModInfo, PlayOptions, SharedContext, SharedWorld } from "./mod_api/shared.ts";
import { sound_to_play } from "./mod_data.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
import { AIR_ID } from "./protocol.ts";
import { is_solid } from "./block_shapes.ts";
@@ -22,6 +23,8 @@ export interface SharedSide {
recipes: () => RecipeBook;
// whether the shared phases are running, the only time they can register
running: () => boolean;
// a rule's sound, see SharedContext.sounds. checked already
play_sound(sound: string, x: number, y: number, z: number, options: PlayOptions): void;
}
export function shared_context(mod: ModInfo, side: SharedSide): SharedContext {
@@ -43,6 +46,13 @@ export function shared_context(mod: ModInfo, side: SharedSide): SharedContext {
},
recipes: shared_recipes_api(mod.id, side.recipes, register),
world: side.world,
sounds: {
play(sound, x, y, z, options = {}) {
if (![x, y, z].every(Number.isFinite)) throw new Error("a position is three numbers");
sound_to_play(sound, options);
side.play_sound(sound, x, y, z, { volume: options.volume, pitch: options.pitch });
},
},
components: {
register_block(id, rules) {
register.new_id("component", id, side.block_rules.has(id));
+52 -6
View File
@@ -1,7 +1,7 @@
# Sounds
A mod's sounds are `.ogg` files in its `sounds/` folder, put together into sounds by its `sounds.json`. Client phases
play them with `ctx.sounds`.
A mod's sounds are `.ogg` files in its `sounds/` folder, put together into sounds by its `sounds.json`. Server phases,
shared rules and client phases play them with `ctx.sounds`.
## Sound Files
@@ -43,6 +43,52 @@ A sound without a category only follows the player's master volume.
## Playing Sounds
Sounds are played where what makes them happens: a server phase for what happens in the world, a shared rule for what a
player's click does, a client phase for what only that player sees, like a screen. Whichever plays it, `volume` and
`pitch` multiply the sound's own, and a sound played at a volume over 1 is heard further away, not louder: at 2, twice
as far. Each throws for a sound no mod defines.
### From the Server
The server only plays a sound once, for the players who can hear it then. A sound that lasts, like a machine's hum, is a
client phase's to play, see [Lasting Sounds](#lasting-sounds).
```ts
// at a point, for every player within its range
ctx.sounds.play("copper_tools:anvil/land", x + 0.5, y, z + 0.5, { volume: 2 });
// at a block's middle
block.play_sound("copper_tools:machine/done");
// following a mob or another entity, for the players who see it within range
mob.play_sound("copper_tools:walker/growl", { pitch: 0.8 });
// only that player hears it, as it is wherever they are
player.play_sound("copper_tools:quest/complete");
```
`ctx.sounds.play` takes `except`, a player who doesn't get it. That's for a player whose own client already played it,
like when a client phase plays a click's sound right away and tells the server about it.
### From Shared Rules
A shared rule's sound, like a door opening in its `on_interact`, plays right away for the player who clicked, since
their client runs the rule too, and reaches everyone else from the server:
```ts
export function shared(ctx: SharedContext) {
ctx.components.register_block("copper_tools:bell", {
on_interact(block) {
ctx.sounds.play("copper_tools:ring", block.x + 0.5, block.y + 0.5, block.z + 0.5);
return true;
},
});
}
```
On the server, a rule running for a player's break, place or click plays it for every player in range but that one. A
rule running for anything else, like a script changing a block, plays it for everyone. A mob opening a door changes its
states from a script, which doesn't run `on_interact`, so that script plays the sound itself.
### On a Client
In a client phase, `ctx.sounds.play` plays a sound on that player's client only:
```ts
@@ -62,11 +108,11 @@ With nothing but its id it's heard as it is wherever the player is, like a click
| `at` | A point it comes from. It fades to nothing at its range, and isn't played at all from further away. |
| `follow` | An entity's id. It comes from where the entity is drawn, and stops when the entity goes. |
| `loop` | Plays again from the start until stopped. |
| `volume` | Multiplies the sound's own. Over 1 it's heard further away, not louder: at 2, twice as far. |
| `volume` | Multiplies the sound's own. |
| `pitch` | Multiplies the sound's own. 2 is an octave up, and twice as fast. |
`play` throws for a sound no mod defines, and `ctx.sounds.exists(id)` checks first. It returns the sound playing, which
can be stopped or changed while it plays:
`ctx.sounds.exists(id)` checks a sound is there before playing it. `play` returns the sound playing, which can be
stopped or changed while it plays:
```ts
const hum = ctx.sounds.play("copper_tools:machine/hum", { at: { x: 10.5, y: 64.5, z: 3.5 }, loop: true });
@@ -78,7 +124,7 @@ hum.stop();
A looping sound out of range waits silently, and when the player comes back in range it plays on from as far into the
file as it would have got, as if it never stopped.
### What Doesn't Play
#### What Doesn't Play
- **Before the player's first click or key press.** Browsers keep sound off until then. A sound played earlier is
dropped, and a loop starts then.
+3
View File
@@ -15,6 +15,7 @@ import type { Season } from "@/common/worldgen/biomes.ts";
import { type Collisions, type FluidInCell, physics } from "@/common/physics.ts";
import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
import type { PlayOptions } from "@/common/mod_api/shared.ts";
import type { LivingEntity } from "./living_entity.ts";
// this far below the bottom of the world, entities have fallen out of it
@@ -102,6 +103,8 @@ export interface EntityLevel {
take_item(item: Entity, by: string): void;
// sent to clients tracking the entity, for the renderer: "hurt" flashes it red, "death" starts falling over
entity_event(entity: Entity, event: EntityEvent): void;
// a sound following it, for the players tracking it within its range, see EntityRef.play_sound
play_sound(entity: Entity, sound: string, options: PlayOptions): void;
// it died, after dropping its things
on_death(entity: Entity, source: DamageSource): void;
// what it drops when it dies, from its type's loot table
+27
View File
@@ -11,6 +11,8 @@ import { biome_season } from "@/common/worldgen/biomes.ts";
import { Tags } from "@/common/tags.ts";
import type { ItemStack } from "@/common/inventory.ts";
import type { EntityEvent, EntityInfo, ServerMessage } from "@/common/protocol.ts";
import type { PlayOptions } from "@/common/mod_api/shared.ts";
import { sound_range, sound_to_play } from "@/common/mod_data.ts";
import type { ServerPlayer } from "../player.ts";
import type { ServerWorld } from "../world.ts";
import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts";
@@ -36,6 +38,21 @@ export interface EntityHost {
inside_blocks?(entity: Entity): void;
}
// a sound clients play, with only what's set. where is where it comes from, see the message in common/protocol.ts
export function sound_message(
sound: string,
{ volume, pitch }: PlayOptions,
where: { at?: [number, number, number]; entity?: string } = {},
): ServerMessage {
return {
type: "sound",
sound,
...where,
...(volume !== undefined && volume !== 1 && { volume }),
...(pitch !== undefined && pitch !== 1 && { pitch }),
};
}
// what a client was last told about an entity, so only changes get sent
interface Sent {
x: number;
@@ -189,6 +206,16 @@ export class EntityManager implements EntityLevel {
}
}
play_sound(entity: Entity, sound: string, options: PlayOptions) {
const range = sound_range(sound_to_play(sound, options), options.volume);
const message = sound_message(sound, options, { entity: entity.id });
for (const [player, tracked] of this.#tracked) {
if (tracked.has(entity.id) && player.hears(entity.x, entity.y, entity.z, range)) {
this.#host.send(player, message);
}
}
}
on_death(entity: Entity, source: DamageSource) {
this.#host.on_entity_death?.(entity, source);
}
+53 -14
View File
@@ -48,7 +48,8 @@ import { physics } from "@/common/physics.ts";
import { EXHAUSTION } from "./vitals.ts";
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import type { LootContext, Position, SchematicPlacement, UseTarget } from "@/common/mod_api/server.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import { type EntityJson, sound_range, sound_to_play } from "@/common/mod_data.ts";
import type { PlayOptions } from "@/common/mod_api/shared.ts";
import { encode_schematic } from "@/common/schematic.ts";
import { capture_schematic, placed_schematic, type RegisteredSchematic } from "./schematics.ts";
import {
@@ -88,7 +89,7 @@ import {
} from "./entity/item_entity.ts";
import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts";
import { EntityManager, sound_message } from "./entity/entity_manager.ts";
import { NaturalSpawner } from "./natural_spawner.ts";
import { create_entity, entity_type_ids, load_entity } from "./entity/entity_types.ts";
import { damage_source, type DamageSource, type Entity, type SavedEntity } from "./entity/entity.ts";
@@ -763,6 +764,40 @@ export class GameServer {
}
}
// a sound at x y z for every player within its range, except one whose client already played it. see
// ServerSounds.play
play_sound(sound: string, x: number, y: number, z: number, options: PlayOptions & { except?: ServerPlayer } = {}) {
const range = sound_range(sound_to_play(sound, options), options.volume);
const message = sound_message(sound, options, { at: [x, y, z] });
for (const player of this.#players.values()) {
if (player !== options.except && player.hears(x, y, z, range)) this.#send(player, message);
}
}
// a sound only player hears, as it is wherever they are, see Player.play_sound
play_sound_to(player: ServerPlayer, sound: string, options: PlayOptions = {}) {
sound_to_play(sound, options);
this.#send(player, sound_message(sound, options));
}
// the player whose break, place or use the shared rules are running for. their client ran the same rules to guess
// it, so it already played what the rules play, see SharedContext.sounds
get rules_player() {
return this.#rules_player;
}
#rules_player: ServerPlayer | undefined;
// fn with the shared rules it runs running for player, see rules_player
#as_player<T>(player: ServerPlayer, fn: () => T): T {
const before = this.#rules_player;
this.#rules_player = player;
try {
return fn();
} finally {
this.#rules_player = before;
}
}
// a script pushing a player, see Player.push. their client moves them, so it's added there, unless the server is
// moving them while they're knocked back
push_player(player: ServerPlayer, x: number, y: number, z: number) {
@@ -1294,7 +1329,7 @@ export class GameServer {
}
// creative breaks drop nothing, since placing doesn't use anything up
this.destroy_block(x, y, z, player, { collect: player.creative });
this.#as_player(player, () => this.destroy_block(x, y, z, player, { collect: player.creative }));
player.vitals.add_exhaustion(EXHAUSTION.break_block);
this.mods.after.block_break.emit(event);
}
@@ -1464,7 +1499,7 @@ export class GameServer {
let handled = false;
if (!(sneaking && held_slot.has_item())) {
const interaction = { face, hit: [hit[0], hit[1], hit[2]] as [number, number, number], sneaking };
handled = this.mods.rules.interact(used, x, y, z, interaction, player.yaw);
handled = this.#as_player(player, () => this.mods.rules.interact(used, x, y, z, interaction, player.yaw));
for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) {
if (component.on_interact) {
handled = run_guarded(mod, `${component_id} on_interact`, () =>
@@ -1509,15 +1544,19 @@ export class GameServer {
}
// solid blocks can't go where a mob or player is, the one placing it included, like minecraft
const placing = EverythingRegistry.get<BlockRegistry>("blocks", held.block_id)!;
const ruled_value = this.mods.rules.placement_value(placing, player.yaw, player.pitch, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
sneaking: player.sneaking,
item: held_slot.type_id!,
});
const ruled_value = this.#as_player(
player,
() =>
this.mods.rules.placement_value(placing, player.yaw, player.pitch, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
sneaking: player.sneaking,
item: held_slot.type_id!,
}),
);
// its rules say it can't go there
if (ruled_value === undefined) {
this.#correct(player, tx, ty, tz);
@@ -1539,7 +1578,7 @@ export class GameServer {
const place = this.#place_event(player, { id: held.block_id, x: tx, y: ty, z: tz }, face, hit);
if (!place) return;
this.set_block(tx, ty, tz, held.block_id, player, state);
this.#as_player(player, () => this.set_block(tx, ty, tz, held.block_id!, player, state));
if (!player.creative) held_slot.amount = held_slot.amount! - 1;
this.mods.after.block_place.emit(place);
}
+28
View File
@@ -333,6 +333,8 @@ export class ModRuntime {
fluid_rules: this.fluid_rules,
recipes: () => this.game.recipes,
running: () => this.#shared_setup,
play_sound: (sound, x, y, z, options) =>
this.game.play_sound(sound, x, y, z, { ...options, except: this.game.rules_player }),
});
}
@@ -756,6 +758,9 @@ export class ModRuntime {
const { [field]: _, ...rest } = mob.client_data;
mob.client_data = value === undefined ? rest : { ...rest, [field]: structuredClone(value) };
},
play_sound(sound, options = {}) {
mob.level.play_sound(mob, sound, options);
},
};
return Object.defineProperties(living_ref(mob), Object.getOwnPropertyDescriptors(extra)) as MobRef;
}
@@ -787,6 +792,9 @@ export class ModRuntime {
set_ticking(ticking) {
game.set_tile_ticking(x, y, z, ticking);
},
play_sound(sound, options) {
game.play_sound(sound, x + 0.5, y + 0.5, z + 0.5, options);
},
};
}
@@ -1250,6 +1258,14 @@ export class ModRuntime {
game().world.dirty = true;
},
},
sounds: {
play: (sound, x, y, z, options = {}) => {
const except = options.except && this.#server_players.get(options.except);
if (options.except && !except) throw new Error("a sound's except must be a player");
game().play_sound(sound, ...at_position(x, y, z), { ...options, except });
},
exists: (sound) => EverythingRegistry.get("sounds", sound) !== undefined,
},
log: (...args) => console.log(`[${mod}]`, ...args),
};
return ctx;
@@ -1711,9 +1727,18 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
player.using = undefined;
},
is_using: () => player.using !== undefined,
play_sound(sound, options) {
game.play_sound_to(player, sound, options);
},
};
}
// a position a script gave, checked
function at_position(x: unknown, y: unknown, z: unknown): [number, number, number] {
if (![x, y, z].every(Number.isFinite)) throw new Error("a position is three numbers");
return [x, y, z] as [number, number, number];
}
function known_effect(id: string): EffectType {
const type = effect_type(id);
if (!type) throw new Error(`unknown effect ${id}`);
@@ -1831,5 +1856,8 @@ export function entity_ref(entity: Entity): EntityRef {
if (!item || item.count <= 0) entity.remove();
else entity.item = new_stack(item);
},
play_sound(sound, options = {}) {
entity.level.play_sound(entity, sound, options);
},
};
}
+5
View File
@@ -202,6 +202,11 @@ export class ServerPlayer extends LivingEntity {
return this.inventory.get_item(this.selected_slot);
}
// whether a sound at x y z heard as far as range reaches their ears
hears(x: number, y: number, z: number, range: number) {
return Math.hypot(x - this.x, y - (this.y + this.eye_height), z - this.z) < range;
}
// the short box and low eyes while swimming, so drowning, reach and what they're in the way of match
set_swimming(swimming: boolean) {
this.swimming = swimming;
+4
View File
@@ -392,6 +392,8 @@ export function client_of(game: GameServer, area: Area) {
const rules = new BlockRules((_mod, _what, fn) => fn(), (x, y, z) => at(x, y, z)?.[0]);
const recipes = new RecipeBook();
// the sounds its rules played, as the client would play them
const sounds: { sound: string; x: number; y: number; z: number }[] = [];
const world: SharedWorld = {
get_block: (x, y, z) => at(x, y, z)?.[0],
get_state(x, y, z, name) {
@@ -426,9 +428,11 @@ export function client_of(game: GameServer, area: Area) {
// its recipes aren't looked at here
recipes: () => recipes,
running: () => true,
play_sound: (sound, x, y, z) => sounds.push({ sound, x, y, z }),
}));
return {
sounds,
// what game_mode does when this client places held against face of x y z, at hit
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false, item: id });
+121 -1
View File
@@ -20,7 +20,7 @@ import {
type VoiceSettings,
type Volumes,
} from "@/client/sounds.ts";
import { copy_dir, load_as_player } from "./helpers.ts";
import { copy_dir, load_as_player, stone_floor, test_game, test_mob } 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]);
@@ -256,3 +256,123 @@ Deno.test("at most 64 sounds play at once, and a loop waits for room", () => {
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] }]);
});