Entity and block sounds !

This commit is contained in:
2026-11-22 08:23:11 -03:00
parent da44685f54
commit d18fe19027
17 changed files with 332 additions and 20 deletions
+26
View File
@@ -2,7 +2,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { physics } from "@/common/physics.ts";
import { AIR } from "@/common/constants.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import type { ClientLevel } from "../level/client_level.ts";
import { sounds } from "../sounds.ts";
// how far it walks between steps, in blocks
const STEP_DISTANCE = 1.6;
// a block's step under the block's other sounds, which are as loud as their definitions say
const BLOCK_STEP_VOLUME = 0.15;
// anything that exists in the level and moves, like minecraft's Entity. position is the middle of its feet.
// it's simulated in fixed ticks (common/constants.ts), frames draw it between its last two positions
@@ -44,6 +52,9 @@ export abstract class Entity {
walk_speed = 0;
prev_walk_speed = 0;
// how far it's walked since its last step
#walked = 0;
// which way it hit something on each axis in the last move: 1 or -1, 0 for nothing.
// 1 on y means it's standing on something
colliding_x = 0;
@@ -80,6 +91,21 @@ export abstract class Entity {
this.walk_position += this.walk_speed;
}
// after moving each tick: a step every STEP_DISTANCE it walks with a block under its feet, own when it has its own
// step sound (see ENTITY_SOUNDS), the block's otherwise
play_steps(own: string | undefined) {
const [x, y, z] = [Math.floor(this.x), Math.floor(this.y - 0.2), Math.floor(this.z)];
const nid = this.level.get_block(x, y, z);
const below = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
if (!below) return;
this.#walked += Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
if (this.#walked < STEP_DISTANCE) return;
this.#walked %= STEP_DISTANCE;
const at = { x: this.x, y: this.y, z: this.z };
if (own) sounds.play(own, { at });
else sounds.play_of(below.sounds, "step", { at, volume: BLOCK_STEP_VOLUME });
}
walk_animation(partial_tick: number) {
return {
position: this.walk_position - this.walk_speed * (1 - partial_tick),
+2
View File
@@ -198,6 +198,8 @@ export class LocalPlayer extends Player {
if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0;
if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0;
this.update_swim_animation();
// creeping and flying are quiet
if (this.on_ground && !this.sneaking) this.play_steps(undefined);
this.#send_position(
(this.on_ground && !was_on_ground) || this.swimming !== was_swimming ||
this.holding_sneak !== was_holding_sneak,
+24 -1
View File
@@ -2,12 +2,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import { type EntityJson, sound_of } from "@/common/mod_data.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { wrap_angle } from "@/common/utils.ts";
import { animation_for, type EntityAnimation } from "../rendering/entity_animators.ts";
import type { ClientLevel } from "../level/client_level.ts";
import { Entity } from "./entity.ts";
import { sounds } from "../sounds.ts";
// how many ticks a server position takes to reach, like minecraft's lerpTo
const LERP_TICKS = 3;
@@ -16,6 +17,8 @@ const HURT_TICKS = 10;
const DEATH_TICKS = 20;
// how long its attack swing takes, like minecraft's mobs
const SWING_TICKS = 6;
// how long it goes between its ambient sounds, picked at random each time
const AMBIENT_TICKS = [80, 240];
// an entity the server simulates, like a mob. this only follows where it's told it is and keeps what it was told
// it looks like, for drawing it
@@ -40,6 +43,10 @@ export class RemoteEntity extends Entity {
#target = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0, head_yaw: 0 };
#lerp_ticks = 0;
// what its sounds' ids start with, see ENTITY_SOUNDS
#sounds: string | undefined;
// until its next ambient sound
#ambient_ticks = random_ambient_ticks();
constructor(level: ClientLevel, info: Extract<EntityInfo, { kind: "entity" }>) {
// the size of mods' entities, player sized for kinds the client doesn't know
@@ -47,6 +54,7 @@ export class RemoteEntity extends Entity {
super(level, info.id, json?.width ?? 0.6, json?.height ?? 1.8, json ? json.height * 0.85 : 1.62);
this.type = info.type;
this.data = info.data;
this.#sounds = json?.sounds;
this.set_position(info.x, info.y, info.z);
this.yaw = info.yaw;
this.pitch = info.pitch;
@@ -69,11 +77,14 @@ export class RemoteEntity extends Entity {
on_event(event: EntityEvent) {
if (event === "hurt") {
this.hurt_time = HURT_TICKS;
sounds.play_of(this.#sounds, "hurt", { follow: this.id });
} else if (event === "swing") {
// swinging again halfway through doesn't restart it, like minecraft
if (this.swing_ticks === undefined || this.swing_ticks >= SWING_TICKS / 2) this.swing_ticks = 0;
} else {
this.dead = true;
// where it died, it's gone soon after
sounds.play_of(this.#sounds, "death", { at: { x: this.x, y: this.y, z: this.z } });
}
}
@@ -95,6 +106,13 @@ export class RemoteEntity extends Entity {
}
this.update_walk_animation();
if (this.swing_ticks !== undefined && ++this.swing_ticks >= SWING_TICKS) this.swing_ticks = undefined;
if (!this.dead) {
this.play_steps(sound_of(this.#sounds, "step"));
if (--this.#ambient_ticks <= 0) {
this.#ambient_ticks = random_ambient_ticks();
sounds.play_of(this.#sounds, "ambient", { follow: this.id });
}
}
}
// how far through its attack swing it is, 0 to 1, like minecraft's attackTime. 0 when it isn't swinging
@@ -102,3 +120,8 @@ export class RemoteEntity extends Entity {
return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS);
}
}
function random_ambient_ticks() {
const [low, high] = AMBIENT_TICKS;
return low + Math.floor(Math.random() * (high - low));
}
+1
View File
@@ -58,5 +58,6 @@ export class RemotePlayer extends Player {
this.z += (this.target_z - this.z) * t;
this.update_walk_animation();
this.update_swim_animation();
this.play_steps(undefined);
}
}
+17
View File
@@ -14,8 +14,15 @@ import type { EntityJson } from "@/common/mod_data.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts";
import type { Entity } from "./entity/entity.ts";
import { sounds } from "./sounds.ts";
const CREATIVE_DESTROY_DELAY = 2;
// a block being broken makes its hit sound every this many ticks, under its other sounds
const HIT_SOUND_TICKS = 4;
const HIT_VOLUME = 0.25;
// the middle of the block at x y z, where its sounds come from
const middle = ({ x, y, z }: { x: number; y: number; z: number }) => ({ x: x + 0.5, y: y + 0.5, z: z + 0.5 });
// breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking
// and guesses the results so they feel instant, the server decides what really happens
@@ -26,6 +33,8 @@ export class MultiPlayerGameMode {
destroy_pos: { x: number; y: number; z: number } | undefined;
destroy_progress = 0;
destroy_time = 0;
// ticks spent breaking it, for its hit sound
#hit_ticks = 0;
// ticks left before creative can break another block while the button is held, so holding it doesn't clear a
// line of blocks every tick
destroy_delay = 0;
@@ -52,6 +61,10 @@ export class MultiPlayerGameMode {
const pos = this.destroy_pos;
if (!pos || pos.x !== hit.x || pos.y !== hit.y || pos.z !== hit.z) {
this.destroy_progress = 0;
this.#hit_ticks = 0;
}
if (this.#hit_ticks++ % HIT_SOUND_TICKS === 0) {
sounds.play_of(block_info.sounds, "hit", { at: middle(hit), volume: HIT_VOLUME });
}
this.destroy_pos = { x: hit.x, y: hit.y, z: hit.z };
// blocks without a toughness, like water, can only be broken in creative
@@ -61,6 +74,8 @@ export class MultiPlayerGameMode {
if (this.destroy_progress >= this.destroy_time) {
// show it right away, the server decides drops and corrects us if it disagrees
this.#predict((seq) => {
// the server sends it to everyone else, see GameServer.destroy_block
sounds.play_of(block_info.sounds, "break", { at: middle(hit) });
this.client.level.break_block(hit.x, hit.y, hit.z);
predict_neighbors(hit.x, hit.y, hit.z);
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z, seq });
@@ -145,6 +160,8 @@ export class MultiPlayerGameMode {
below_id,
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
if ((!block_info.interactive || skips_block) && place_id && placeable) {
// the server sends it to everyone else, see GameServer.#use_block
sounds.play_of(place_block!.sounds, "place", { at: middle(target) });
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
predict_neighbors(target.x, target.y, target.z);
if (!this.client.player.creative) {
+7 -1
View File
@@ -5,7 +5,7 @@
// 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 { sound_range, sound_to_play, type SoundCategory, type SoundJson } from "@/common/mod_data.ts";
import { sound_of, 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";
@@ -172,6 +172,12 @@ export class Sounds {
return playing;
}
// the sound a block's or entity's "sounds" prefix has for kind, when it has one, see BLOCK_SOUNDS and ENTITY_SOUNDS
play_of(prefix: string | undefined, kind: string, options: ClientPlayOptions) {
const sound = sound_of(prefix, kind);
if (sound) this.play(sound, options);
}
// before each frame: the player hears from listener, sounds following an entity go where it's drawn
frame(listener: Listener, entity_position: (id: string) => Position | undefined, volumes: Volumes) {
this.#listener = { x: listener.x, y: listener.y, z: listener.z };
+2
View File
@@ -161,6 +161,8 @@ export interface BlockRegistry {
interactive?: boolean;
// the mouse wheel turned while looking at it goes to its components' on_scroll instead of the hotbar
scrollable?: boolean;
// what its sounds' ids start with, see BLOCK_SOUNDS in common/mod_data.ts
sounds?: string;
// placing a block into it replaces it, like water
replaceable?: boolean;
// the blocks (ids or #tags) it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when
+16
View File
@@ -4,11 +4,13 @@
// checks between mods: dependencies, load order, and ids one mod uses from another. pure, so the build, check-mods
// and the server (on .cubi files) all use it
import {
BLOCK_SOUNDS,
type BlockJson,
choice_list,
type ClipJson,
type EffectJson,
entity_category,
ENTITY_SOUNDS,
type EntityJson,
type EntityModelJson,
type FluidJson,
@@ -193,6 +195,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
const textures = new Set<string>(engine_textures);
const sounds = new Set<string>();
// terrain data by kind, then id
const worldgen_owners: Record<string, Map<string, string[]>> = {
noise: new Map(),
@@ -248,6 +251,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
tag_owners.get(json.registry)!.add(json.id);
}
for (const texture of mod.textures) textures.add(texture);
for (const { json } of mod.sounds ?? []) sounds.add(json.id);
}
const mod_ids = new Set(mods.map((mod) => mod.id));
@@ -295,6 +299,16 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
};
// a block's or entity's "sounds" with none of what it can have, which is a typo
const uses_sounds = (file: string, prefix: string, kinds: readonly string[]) => {
check_namespace(file, prefix);
if (!kinds.some((kind) => sounds.has(`${prefix}/${kind}`))) {
errors.push(
`${file}: sounds ${prefix} has none of ${kinds.map((kind) => `${prefix}/${kind}`).join(", ")}`,
);
}
};
for (const { file, json } of mod.blocks) {
if ((block_owners.get(json.id)?.length ?? 0) > 1) {
errors.push(`${file}: block ${json.id} is also defined by ${block_owners.get(json.id)!.join(", ")}`);
@@ -309,6 +323,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (json.item_model) uses(file, json.item_model, "model");
if (json.drops) uses(file, json.drops, "item");
if (json.loot_table) uses(file, json.loot_table, "loot table");
if (json.sounds) uses_sounds(file, json.sounds, BLOCK_SOUNDS);
if (json.waterloggable) {
uses(file, json.waterloggable, "block");
if (block_owners.has(json.waterloggable) && !fluid_blocks.has(json.waterloggable)) {
@@ -391,6 +406,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (json.model !== undefined) uses(file, json.model, "entity model");
uses(file, json.texture, "texture");
if (json.loot_table) uses(file, json.loot_table, "loot table");
if (json.sounds) uses_sounds(file, json.sounds, ENTITY_SOUNDS);
// scripts register behaviors, the server checks them when it starts
if (json.behavior?.includes(":")) check_namespace(file, json.behavior);
}
+20
View File
@@ -69,6 +69,8 @@ const tint_color = z.custom<TintColor>(is_tint_color, 'must be "grass", "foliage
// a texture id, or texture variables mapped to ids
const textures = z.union([id, z.record(z.string(), id)], "must be a texture id or { variable: texture id }");
const stack = z.object({ id, count: z.int().min(1) });
// what a block's or entity's sounds start with, like "my_mod:wood" for my_mod:wood/break
const sound_prefix = z.string('must be a sound id like "my_mod:wood"').regex(TAG_ID_PATTERN);
// the manifest of the mod in the folder folder_name, which is its id
const manifest_schema = (folder_name: string) =>
@@ -118,6 +120,7 @@ export interface BlockJson {
item?: boolean;
interactive?: boolean;
scrollable?: boolean;
sounds?: string;
replaceable?: boolean;
place_on?: string[];
place_in?: string[];
@@ -196,6 +199,8 @@ const block_fields = z.object({
item: z.boolean().optional(),
interactive: z.boolean().optional(),
scrollable: z.boolean().optional(),
// what it sounds like: <sounds>/break, /place, /step and /hit, see BLOCK_SOUNDS
sounds: sound_prefix.optional(),
replaceable: z.boolean().optional(),
place_on: z.array(id_or_tag).min(1).optional(),
place_in: z.array(id_or_tag).min(1).optional(),
@@ -458,6 +463,8 @@ const entity_schema = z.object({
arcane_shielding: z.number().min(0).optional(),
// what it drops when it dies, see common/loot.ts
loot_table: loot_table_id.optional(),
// what it sounds like: <sounds>/hurt, /death, /step and /ambient, see ENTITY_SOUNDS
sounds: sound_prefix.optional(),
});
export type EntityJson = z.infer<typeof entity_schema>;
@@ -638,6 +645,17 @@ export function validate_sound(json: unknown): Problems {
return find_problems(sound_schema, json);
}
// the sounds the engine plays for a block or an entity whose json has "sounds", each after its prefix and a /. a sound
// that isn't defined isn't played
export const BLOCK_SOUNDS = ["break", "place", "step", "hit"] as const;
export const ENTITY_SOUNDS = ["hurt", "death", "step", "ambient"] as const;
// the id of the sound prefix has for kind, undefined when it has none
export function sound_of(prefix: string | undefined, kind: string): string | undefined {
const id = `${prefix}/${kind}`;
return prefix !== undefined && EverythingRegistry.get("sounds", id) ? id : undefined;
}
// how far away a sound is heard at volume 1 when its definition doesn't say
const DEFAULT_SOUND_RANGE = 16;
@@ -796,6 +814,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (block.loot_table !== undefined) json.loot_table = block.loot_table;
if (!has_item) json.item = false;
if (block.interactive) json.interactive = true;
if (block.sounds !== undefined) json.sounds = block.sounds;
if (block.scrollable) json.scrollable = true;
if (!!block.replaceable !== !!block.fluid) json.replaceable = !!block.replaceable;
if (block.place_on) json.place_on = block.place_on;
@@ -848,6 +867,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.loot_table !== undefined) block.loot_table = json.loot_table;
if (json.interactive) block.interactive = true;
if (json.scrollable) block.scrollable = true;
if (json.sounds !== undefined) block.sounds = json.sounds;
if (json.replaceable ?? json.fluid) block.replaceable = true;
if (json.place_on) block.place_on = json.place_on;
if (json.place_in) block.place_in = json.place_in;
+1
View File
@@ -68,6 +68,7 @@ there will be holes in the world behind them.
| `item` | `true` | Also register an item that places it, with the same id. To give that item more, see [Block Items](../items/index.md#block-items). |
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
| `scrollable` | `false` | The mouse wheel turned while looking at it goes to its components' `on_scroll` instead of the hotbar, see [Scrolling](components.md#scrolling). |
| `sounds` | silent | What its sounds' ids start with, see [Sounds](../resources/sounds.md#blocks-and-entities). |
| `replaceable` | `false` | Placing a block into it replaces it, like water. Fluids default to `true`. |
| `place_in` | see meaning | Block ids or [tags](../resources/tags.md) it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | Block ids or [tags](../resources/tags.md) it can stand on, like `["bworld:hoed_dirt"]` for crops or `["#bworld:logs"]`. See [below](#placement). |
+1
View File
@@ -38,6 +38,7 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi
| `physical_shielding` | `0` | Protection from physical damage. Not used yet. |
| `arcane_shielding` | `0` | Protection from arcane damage. Not used yet. |
| `loot_table` | none | A [loot table](../resources/loot_tables.md) it drops from when it dies. |
| `sounds` | silent | What its sounds' ids start with, see [Sounds](../resources/sounds.md#blocks-and-entities). |
`/summon <entity>` spawns one where you stand.
+28
View File
@@ -41,6 +41,34 @@ A sound without a category only follows the player's master volume.
`deno task check-mods` reports a file that isn't there, and warns about an `.ogg` no sound plays.
## Blocks and Entities
A block's or entity's json can name what its sounds' ids start with, and the game plays them without any code:
```json
"sounds": "copper_tools:copper"
```
| For | Sound | When |
| --------- | ---------- | ----------------------------------------------------------------------------------------------------- |
| a block | `/break` | It's broken, by a player or a script's `break_block`. Not when a script replaces it with `set_block`. |
| a block | `/place` | A player or a machine's `use_item_on` places it. |
| a block | `/hit` | Every 4 ticks while a player breaks it, at a quarter of the volume, only on their client. |
| a block | `/step` | Something walks on it with no step sound of its own, every 1.6 blocks, at 0.15 of the volume. |
| an entity | `/hurt` | It's hurt. |
| an entity | `/death` | It dies. |
| an entity | `/step` | It walks on a block, every 1.6 blocks, in place of the block's step. |
| an entity | `/ambient` | Every 4 to 12 seconds while it's alive, timed by each player's client. |
So `"sounds": "copper_tools:copper"` on a block plays `copper_tools:copper/break` when it breaks, and so on. Any of them
can be left out of `sounds.json`, and isn't played. A whole family of blocks usually shares one, like every copper
block, and `check-mods` reports a block or entity whose `sounds` has none of its own, which is usually a typo.
The player breaking or placing a block hears it right away from their own client, and everyone else from the server.
Players step with the blocks they walk on, except the one playing while they sneak or fly. Anything about a mob that
depends on what it's doing is its scripts' to play, see [From the Server](#from-the-server) and
[Lasting Sounds](#lasting-sounds).
## 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
@@ -5,6 +5,7 @@
"model": "dangerous_business:coilhead",
"texture": "dangerous_business:coilhead",
"behavior": "dangerous_business:coilhead",
"sounds": "dangerous_business:coilhead",
"width": 0.8,
"height": 1.9,
"max_health": 40,
@@ -5,6 +5,7 @@
"model": "dangerous_business:jester",
"texture": "dangerous_business:jester",
"behavior": "dangerous_business:jester",
"sounds": "dangerous_business:jester",
"width": 0.8,
"height": 1.9,
"max_health": 40,
+19 -3
View File
@@ -48,7 +48,7 @@ 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, sound_range, sound_to_play } from "@/common/mod_data.ts";
import { type EntityJson, sound_of, 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";
@@ -774,6 +774,13 @@ export class GameServer {
}
}
// a block's sound of kind from the middle of x y z, when it has one, for everyone but heard_by, whose client played
// it already. see BLOCK_SOUNDS
#block_sound(block: BlockRegistry, kind: string, x: number, y: number, z: number, heard_by?: ServerPlayer) {
const sound = sound_of(block.sounds, kind);
if (sound) this.play_sound(sound, x + 0.5, y + 0.5, z + 0.5, { except: heard_by });
}
// 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);
@@ -853,12 +860,13 @@ export class GameServer {
y: number,
z: number,
player?: ServerPlayer,
how: { harvest?: boolean; collect?: boolean } = {},
how: { harvest?: boolean; collect?: boolean; heard_by?: ServerPlayer } = {},
): ItemStack[] | undefined {
const info = this.world.get_block_info(x, y, z);
if (!info) {
return undefined;
}
this.#block_sound(info, "break", x, y, z, how.heard_by);
const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? "");
const tool = held?.tool;
const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0);
@@ -1329,7 +1337,11 @@ export class GameServer {
}
// creative breaks drop nothing, since placing doesn't use anything up
this.#as_player(player, () => this.destroy_block(x, y, z, player, { collect: player.creative }));
// their client played its break sound as it guessed the break
this.#as_player(
player,
() => this.destroy_block(x, y, z, player, { collect: player.creative, heard_by: player }),
);
player.vitals.add_exhaustion(EXHAUSTION.break_block);
this.mods.after.block_break.emit(event);
}
@@ -1579,6 +1591,10 @@ export class GameServer {
if (!place) return;
this.#as_player(player, () => this.set_block(tx, ty, tz, held.block_id!, player, state));
// their client guessed the placing, and played its sound, unless the item or the clicked block might have done
// something else, see MultiPlayerGameMode's #guess_use
const guessed = !held.components && (!info.interactive || player.sneaking);
this.#block_sound(placing, "place", tx, ty, tz, guessed ? player : undefined);
if (!player.creative) held_slot.amount = held_slot.amount! - 1;
this.mods.after.block_place.emit(place);
}
+3
View File
@@ -6,6 +6,7 @@ import { LocalPlayer } from "@/client/entity/local_player.ts";
import { InputManager } from "@/client/input_manager.ts";
import { Options } from "@/client/options.ts";
import type { Client } from "@/client/client.ts";
import { AIR } from "@/common/constants.ts";
type Blocks = (x: number, y: number, z: number) => boolean;
@@ -20,6 +21,8 @@ function setup(ceiling = Infinity, world?: { solid: Blocks; water: Blocks }) {
// its water is all still sources
fluid_at: (x: number, y: number, z: number) =>
world?.water(x, y, z) ? { id: "a:water", height: 1 } : undefined,
// blocks without sounds to step on
get_block: () => AIR,
},
screen: undefined,
options: new Options(),
+163 -15
View File
@@ -12,6 +12,12 @@ 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]);
@@ -264,23 +270,49 @@ export function server(ctx: ServerContext) {
// 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 } });
// 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 });
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 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);
@@ -349,3 +381,119 @@ Deno.test("a shared rule's sound isn't sent to the player whose click ran it, wh
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();
});