Compare commits

...
12 Commits
Author SHA1 Message Date
paula 487d5ae2a9 Animation system mostly done 2026-11-22 09:12:15 -03:00
paula 8a13854f39 Track time on jester windup 2026-11-22 08:58:06 -03:00
paula 5d374091cd Offset on sounds api 2026-11-22 08:35:54 -03:00
paula d18fe19027 Entity and block sounds ! 2026-11-22 08:23:11 -03:00
paula da44685f54 Jester and coilhead sounds 2026-11-22 07:54:31 -03:00
paula 8e587f6446 Sounds on shared and server 2026-11-22 07:44:13 -03:00
paula 47934b272c Sounds on the client 2026-11-22 07:21:29 -03:00
paula f308ab52f1 Jester time 2026-11-21 23:07:42 -03:00
paula 0c711b8163 Animators and coilhead animations 2026-11-21 21:54:02 -03:00
paula 69ad4b80d0 Animation clips 2026-11-21 20:07:10 -03:00
paula 607be76ca6 Jester entity, no ai 2026-11-21 19:35:29 -03:00
paula 4bdf5203d4 Geo renderer improvements 2026-11-21 19:24:09 -03:00
93 changed files with 6927 additions and 183 deletions
+2 -1
View File
@@ -52,7 +52,7 @@ deno task build && deno task server # packs the mods and starts a se
**Entities**
- [Entities](docs/modding/entities/index.md): animals, monsters, custom behaviors and their goals, how mobs get around,
natural spawning, scripted entities and entity models
natural spawning, scripted entities, entity models and their animations
- [Players](docs/modding/entities/players.md): the player API, health and hunger
**Inventories**
@@ -63,6 +63,7 @@ deno task build && deno task server # packs the mods and starts a se
**Resources**
- [Textures](docs/modding/resources/textures.md)
- [Sounds](docs/modding/resources/sounds.md): sound files, and playing them on a player's client
- [Block Models](docs/modding/resources/models.md)
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
+1 -20
View File
@@ -3,7 +3,7 @@
import { load_texture, Texture } from "./renderer/mod.ts";
type Asset = Texture | HTMLAudioElement | string | Record<string, unknown>;
type Asset = Texture | string | Record<string, unknown>;
export class AssetManager {
static instance = new AssetManager();
@@ -29,25 +29,6 @@ export class AssetManager {
});
img.src = src;
this.loading_promises.push(promise);
} else if (src.endsWith(".ogg")) {
const audio = new Audio();
const promise = new Promise<void>((resolve, reject) => {
audio.addEventListener(
"canplaythrough",
() => resolve(),
{ once: true },
);
audio.addEventListener(
"error",
() => reject(new Error(`Failed to load audio: ${src}`)),
{ once: true },
);
});
audio.src = src;
audio.load();
this.assets[key] = audio;
this.loading_promises.push(promise);
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
const promise = async () => {
const resp = await fetch(src);
+183
View File
@@ -0,0 +1,183 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// plays what client/sounds.ts decides on with web audio: a gain per category under master, and a panner for each
// sound that comes from somewhere, fading linearly to nothing at its range
import { SOUND_CATEGORIES, type SoundCategory } from "@/common/mod_data.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "./sounds.ts";
export class WebAudioOutput implements SoundOutput {
#context: AudioContext | undefined;
#master: GainNode | undefined;
#categories = new Map<SoundCategory, GainNode>();
// decoded once, the first time anything plays them. by the bytes, so another server's files never mix in
#buffers = new WeakMap<Uint8Array, Promise<AudioBuffer | undefined>>();
#volumes: Volumes | undefined;
constructor() {
// browsers keep audio off until the player clicks or presses a key, so it starts then
const unlock = () => {
this.#unlock();
if (this.#context?.state === "running") {
removeEventListener("pointerdown", unlock);
removeEventListener("keydown", unlock);
}
};
addEventListener("pointerdown", unlock);
addEventListener("keydown", unlock);
}
#unlock() {
if (!this.#context) {
const context = new AudioContext();
this.#master = context.createGain();
this.#master.connect(context.destination);
for (const category of SOUND_CATEGORIES) {
const gain = context.createGain();
gain.connect(this.#master);
this.#categories.set(category, gain);
}
this.#context = context;
if (this.#volumes) this.set_volumes(this.#volumes);
}
if (this.#context.state === "suspended") this.#context.resume();
}
start(file: SoundFile, settings: VoiceSettings): Voice | undefined {
const context = this.#context;
// sounds played while it's suspended would all come at once when it resumes
if (!context || context.state !== "running") return undefined;
const out = settings.category ? this.#categories.get(settings.category)! : this.#master!;
return new WebVoice(context, this.#buffer(context, file), out, settings);
}
#buffer(context: AudioContext, file: SoundFile) {
let buffer = this.#buffers.get(file.bytes);
if (!buffer) {
// decoding detaches what it's given
buffer = context.decodeAudioData(file.bytes.slice().buffer).catch((e) => {
console.error(`couldn't decode the sound file ${file.id}:`, e);
return undefined;
});
this.#buffers.set(file.bytes, buffer);
}
return buffer;
}
listen(x: number, y: number, z: number, yaw: number, pitch: number) {
const listener = this.#context?.listener;
if (!listener) return;
// the camera's forward and up, see ClientLevel's pick
const forward = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
const up = [Math.sin(yaw) * Math.sin(pitch), Math.cos(pitch), Math.cos(yaw) * Math.sin(pitch)];
// firefox only has the old setters
if (listener.positionX) {
listener.positionX.value = x;
listener.positionY.value = y;
listener.positionZ.value = z;
listener.forwardX.value = forward[0];
listener.forwardY.value = forward[1];
listener.forwardZ.value = forward[2];
listener.upX.value = up[0];
listener.upY.value = up[1];
listener.upZ.value = up[2];
} else {
listener.setPosition(x, y, z);
listener.setOrientation(forward[0], forward[1], forward[2], up[0], up[1], up[2]);
}
}
set_volumes(volumes: Volumes) {
this.#volumes = volumes;
if (!this.#master) return;
this.#master.gain.value = volumes.master;
for (const [category, gain] of this.#categories) gain.gain.value = volumes[category];
}
}
class WebVoice implements Voice {
ended = false;
#source: AudioBufferSourceNode | undefined;
#gain: GainNode;
#panner: PannerNode | undefined;
#stopped = false;
// set may come before the file is decoded
#pitch: number;
constructor(
context: AudioContext,
buffer: Promise<AudioBuffer | undefined>,
out: AudioNode,
settings: VoiceSettings,
) {
this.#pitch = settings.pitch;
this.#gain = new GainNode(context, { gain: Math.min(1, settings.volume) });
if (settings.at) {
this.#panner = new PannerNode(context, {
panningModel: "HRTF",
distanceModel: "linear",
refDistance: 1,
maxDistance: settings.range,
positionX: settings.at.x,
positionY: settings.at.y,
positionZ: settings.at.z,
});
this.#gain.connect(this.#panner).connect(out);
} else {
this.#gain.connect(out);
}
// the first time a file plays it starts once it's decoded
buffer.then((buffer) => {
if (!buffer || this.#stopped) {
this.ended = true;
return;
}
// played with an offset past its end, it would have finished already
if (!settings.loop && settings.offset >= buffer.duration) {
this.stop();
return;
}
const source = new AudioBufferSourceNode(context, {
buffer,
loop: settings.loop,
playbackRate: this.#pitch,
});
source.connect(this.#gain);
source.onended = () => {
this.ended = true;
this.#disconnect();
};
source.start(0, settings.offset % buffer.duration);
this.#source = source;
});
}
move(at: Position) {
if (!this.#panner) return;
this.#panner.positionX.value = at.x;
this.#panner.positionY.value = at.y;
this.#panner.positionZ.value = at.z;
}
set(volume: number, pitch: number, range: number) {
this.#gain.gain.value = Math.min(1, volume);
this.#pitch = pitch;
if (this.#source) this.#source.playbackRate.value = pitch;
if (this.#panner) this.#panner.maxDistance = range;
}
stop() {
this.#stopped = true;
this.ended = true;
this.#source?.stop();
this.#disconnect();
}
#disconnect() {
this.#source?.disconnect();
this.#gain.disconnect();
this.#panner?.disconnect();
}
}
+15 -2
View File
@@ -29,6 +29,7 @@ import { type BlockRegistry, EverythingRegistry } from "@/common/everything_regi
import type { EntityJson } from "@/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
import { sounds } from "./sounds.ts";
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
const USE_REPEAT_MS = 200;
@@ -136,12 +137,14 @@ export class Client {
// leaving on purpose, from the pause screen
disconnect() {
this.#stopped = true;
sounds.stop_all();
this.connection.close();
back_to_title();
}
#stop() {
this.#stopped = true;
sounds.stop_all();
this.level.dispose();
InputManager.set_mouse_grabbed(false);
}
@@ -183,8 +186,18 @@ export class Client {
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
}
if (this.benchmark) this.benchmark.render(this.#pending_time / TICK_DELTA);
else this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
const partial_tick = this.#pending_time / TICK_DELTA;
if (this.benchmark) {
this.benchmark.render(partial_tick);
} else {
this.game_renderer.render(this, partial_tick);
// from where the camera was just put
sounds.frame(
this.camera,
(id) => this.level.entities.get(id)?.render_position(partial_tick),
this.options.volume,
);
}
}
// one step of the game: what the server sent (chunks included), breaking, then every entity
+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,
+38 -2
View File
@@ -2,11 +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;
@@ -15,14 +17,20 @@ 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
export class RemoteEntity extends Entity {
// the entity type, like "cubi:item"
readonly type: string;
// synced data, see EntityData
// synced data, see EntityData. set_data changes it
data: EntityData;
// ticks since this client got it
age = 0;
// its type's animator from a mod, see ClientRender.register_entity_animator
readonly animation: EntityAnimation | undefined;
head_yaw: number;
// counting down after a hurt event, and up after a death one
hurt_time = 0;
@@ -35,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
@@ -42,11 +54,19 @@ 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;
this.head_yaw = info.head_yaw ?? info.yaw;
this.#target = { x: info.x, y: info.y, z: info.z, yaw: info.yaw, pitch: info.pitch, head_yaw: this.head_yaw };
this.animation = animation_for(this);
}
set_data(data: EntityData) {
const before = this.data;
this.data = data;
this.animation?.data_changed(before);
}
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number, head_yaw = yaw) {
@@ -57,15 +77,19 @@ 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 } });
}
}
tick() {
this.age += 1;
if (this.hurt_time > 0) this.hurt_time -= 1;
if (this.dead) this.death_time = Math.min(DEATH_TICKS, this.death_time + 1);
@@ -82,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
@@ -89,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) {
+4
View File
@@ -31,6 +31,8 @@ import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen
import { MainMenuScreen } from "./gui/main_menu.ts";
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
import { profiler } from "./profiler.ts";
import { sounds } from "./sounds.ts";
import { WebAudioOutput } from "./audio_output.ts";
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
@@ -231,6 +233,8 @@ try {
}
InputManager.initialize(game_canvas);
// waits for the first click or key, which the title screen gets
sounds.set_output(new WebAudioOutput());
self.addEventListener("resize", resize_canvas);
resize_canvas();
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
+29
View File
@@ -44,9 +44,12 @@ import { clear_hooks, expose_engine } from "@/common/hooks.ts";
import { common_engine } from "@/common/engine_modules.ts";
import { client_engine } from "./engine_modules.ts";
import { block_visuals } from "./rendering/visuals.ts";
import { entity_animators } from "./rendering/entity_animators.ts";
import { biome_season } from "@/common/worldgen/biomes.ts";
import { clock, farming_day } from "@/common/time.ts";
import type { LootTableJson } from "@/common/loot.ts";
import type { ClipJson } from "@/common/mod_data.ts";
import { sounds } from "./sounds.ts";
// each loaded mod's credits file, for the credits screen
export const mod_credits: { name: string; version: string; text: string }[] = [];
@@ -198,6 +201,7 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
}
const recipes = register_mod_data(mods.map((mod) => ({ id: mod.manifest.id, data: mod.data })));
sounds.set_files(mods.map((mod) => ({ id: mod.manifest.id, sounds: mod.sounds })));
recipe_book = recipes;
inventory_overlays.length = 0;
hud_layers.length = 0;
@@ -206,6 +210,7 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
menu_screens.clear();
net_handlers.clear();
block_visuals.clear();
entity_animators.clear();
mod_names.clear();
for (const listing of listings) mod_names.set(listing.id, listing.name);
@@ -236,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);
@@ -429,6 +436,28 @@ function client_context(listing: ModListing): ClientContext {
if (other) register.fail(`${block} already has a visual, from ${other.mod}`);
block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false });
},
register_entity_animator(type, create) {
register.running("entity animator");
if (!EverythingRegistry.get("entities", type)) throw new Error(`[${mod}] unknown entity ${type}`);
if (typeof create !== "function") {
throw new Error(`[${mod}] an animator needs a function that makes it`);
}
const other = entity_animators.get(type);
if (other) register.fail(`${type} already has an animator, from ${other.mod}`);
entity_animators.set(type, { mod, create });
},
clip(id) {
const json = EverythingRegistry.get<ClipJson>("animations", id);
if (!json) throw new Error(`[${mod}] unknown clip ${id}`);
return Object.freeze({ id, length: json.length, loop: json.loop });
},
},
sounds: {
play(sound, options) {
if (!sounds.exists(sound)) throw new Error(`[${mod}] unknown sound ${sound}`);
return sounds.play(sound, options);
},
exists: (sound) => sounds.exists(sound),
},
log: (...args) => console.log(`[${mod}]`, ...args),
};
+3
View File
@@ -2,10 +2,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { KeyCode } from "./input_manager.ts";
import type { Volumes } from "./sounds.ts";
// the player's settings, like minecraft's Options and its key mappings
export class Options {
render_distance = 16;
// 0 to 1, each sound category's under master's, see client/sounds.ts
volume: Volumes = { master: 1, music: 1, ambient: 1, blocks: 1, entities: 1, players: 1, ui: 1 };
key_forward: KeyCode = "KeyW";
key_back: KeyCode = "KeyS";
+16 -1
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
@@ -145,7 +146,7 @@ export class ClientPacketListener {
case "entity_data": {
const entity = level.entities.get(message.id);
if (entity instanceof RemoteEntity) {
entity.data = message.data;
entity.set_data(message.data);
}
break;
}
@@ -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];
+20 -1
View File
@@ -42,6 +42,8 @@ let canvas_format: GPUTextureFormat;
let pipeline_2d: GPURenderPipeline;
let pipeline_3d: GPURenderPipeline;
// the same, drawing both sides of each face, see set_face_culling
let pipeline_3d_no_cull: GPURenderPipeline;
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline };
// 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes
@@ -76,6 +78,7 @@ let current_texture: GPUTexture | null = null;
export let white_tex: GPUTexture | null = null;
let mode3d = false;
let cull_faces = true;
let camera: Camera | undefined;
@@ -496,6 +499,14 @@ export function set_render_time(ticks: number) {
render_time = ticks % RENDER_TIME_PERIOD;
}
// whether 3d drawing leaves out faces seen from behind, true unless turned off. off draws both sides, like entity
// models do, where a flat cube's one face is seen from either side and an open box shows its inside
export function set_face_culling(cull: boolean) {
if (cull_faces === cull) return;
flush_batch();
cull_faces = cull;
}
export function end_mode_3d() {
if (!mode3d) {
return;
@@ -832,7 +843,7 @@ function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
const render_pass = ensure_pass();
const pipeline = mode3d ? pipeline_3d : pipeline_2d;
const pipeline = mode3d ? (cull_faces ? pipeline_3d : pipeline_3d_no_cull) : pipeline_2d;
if (current_pipeline !== pipeline) {
render_pass.setPipeline(pipeline);
current_pipeline = pipeline;
@@ -1035,6 +1046,14 @@ function create_pipelines() {
primitive: primitive_3d,
depthStencil: depth_3d,
});
pipeline_3d_no_cull = device.createRenderPipeline({
layout,
vertex,
fragment,
multisample,
primitive: { ...primitive_3d, cullMode: "none" },
depthStencil: depth_3d,
});
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
const terrain_layout = device.createPipelineLayout({
+80
View File
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// playing clips (see ClipJson): what one does to the bones it moves at a time into it, sampled the way blockbench's
// timeline does a bedrock animation. what the format means comes from ports/blockbench: reading a file in
// js/formats/bedrock/bedrock_animation.js, picking and blending the keyframes around a time in
// js/animations/timeline_animators.js's interpolate(), the curves in js/animations/keyframe.js, and what that does to
// a bone in displayRotation/Position/Scale. no drawing here, so tests can use it
import type { ClipJson, ClipKeyframe } from "@/common/mod_data.ts";
import { lerp } from "@/common/worldgen/noise.ts";
import type { BoneOffsets, Vec3 } from "./model_math.ts";
// a keyframe this close to the time is the one it's on, in seconds
const ON_KEYFRAME = 1 / 1200;
// a bone nothing has moved
export function rest_offsets(): BoneOffsets {
return { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1] };
}
// adds what clip does seconds into it to each bone's offsets, scaled by weight: rotation and position times weight,
// scale weight of the way from 1. a clip that loops wraps around its length, one that doesn't stays on its last frame
export function sample_clip(clip: ClipJson, seconds: number, offsets: Map<string, BoneOffsets>, weight = 1) {
const time = clip.loop && clip.length > 0 ? ((seconds % clip.length) + clip.length) % clip.length : seconds;
for (const [bone, channels] of Object.entries(clip.bones)) {
let offset = offsets.get(bone);
if (!offset) {
offset = rest_offsets();
offsets.set(bone, offset);
}
for (const channel of ["rotation", "position"] as const) {
const keyframes = channels[channel];
if (!keyframes) continue;
const value = sample_channel(keyframes, time, clip.loop);
for (let i = 0; i < 3; i++) offset[channel][i] += value[i] * weight;
}
if (channels.scale) {
const value = sample_channel(channels.scale, time, clip.loop);
for (let i = 0; i < 3; i++) offset.scale[i] *= 1 + (value[i] - 1) * weight;
}
}
}
// a channel's value at time, from the keyframes around it. on a keyframe it's what it comes in at, and before the
// first or after the last it's that keyframe's
export function sample_channel(keyframes: ClipKeyframe[], time: number, loop: boolean): Vec3 {
let after = keyframes.findIndex((keyframe) => keyframe.time >= time);
if (after === -1) after = keyframes.length;
const from = keyframes[after - 1];
const to = keyframes[after];
if (from && time - from.time < ON_KEYFRAME) return from.pre;
if (to && to.time - time < ON_KEYFRAME) return to.pre;
if (!to) return from.post;
if (!from) return to.pre;
const t = (time - from.time) / (to.time - from.time);
if (!from.smooth && !to.smooth) return [0, 1, 2].map((i) => lerp(t, from.post[i], to.pre[i])) as Vec3;
// through the keyframes either side too, wrapping around a loop of three or more, whose first and last are the same
// moment. where there's none, or the one next to it jumps, the curve starts or ends at the next one's value again
let before: ClipKeyframe | undefined = keyframes[after - 2];
let beyond: ClipKeyframe | undefined = keyframes[after + 1];
if (loop && keyframes.length >= 3) {
before ??= keyframes.at(-2);
beyond ??= keyframes[1];
}
const p0 = before && same(from.pre, from.post) ? before.post : from.post;
const p3 = beyond && same(to.pre, to.post) ? beyond.pre : to.pre;
return [0, 1, 2].map((i) => catmullrom(t, p0[i], from.post[i], to.pre[i], p3[i])) as Vec3;
}
function same(a: Vec3, b: Vec3) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
}
// a uniform catmull-rom spline from p1 at t 0 to p2 at t 1
function catmullrom(t: number, p0: number, p1: number, p2: number, p3: number) {
const v0 = (p2 - p0) / 2;
const v1 = (p3 - p1) / 2;
return (2 * p1 - 2 * p2 + v0 + v1) * t ** 3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t ** 2 + v0 * t + p1;
}
+173
View File
@@ -0,0 +1,173 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// mods' entity animators, see ClientRender.register_entity_animator and docs/modding/entities/index.md#animators. each
// entity of a type with one gets its own, made with the entity, which says what its model's bones do every frame it's
// drawn
import type { AnimatedEntity, Clip, EntityAnimator, EntityPose } from "@/common/mod_api/client.ts";
import type { ClipJson } from "@/common/mod_data.ts";
import type { EntityData } from "@/common/protocol.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { wrap_angle } from "@/common/utils.ts";
import { rest_offsets, sample_clip } from "./animation.ts";
import type { BoneOffsets } from "./model_math.ts";
export interface AnimatorRegistration {
mod: string;
create: (entity: AnimatedEntity) => EntityAnimator;
}
// by entity type
export const entity_animators = new Map<string, AnimatorRegistration>();
// what an animator reads of its entity, a RemoteEntity's
export interface AnimatorSource {
readonly id: string;
readonly type: string;
readonly data: EntityData;
// ticks since this client got it
readonly age: number;
readonly yaw: number;
readonly head_yaw: number;
readonly pitch: number;
walk_animation(partial_tick: number): { position: number; speed: number };
attack_animation(partial_tick: number): number;
}
const DEGREES = 180 / Math.PI;
// one entity's animator, undefined for a type without one
export function animation_for(source: AnimatorSource): EntityAnimation | undefined {
const registration = entity_animators.get(source.type);
return registration && new EntityAnimation(source, registration);
}
export class EntityAnimation {
#source: AnimatorSource;
#mod: string;
#entity: AnimatedEntity;
#animator: EntityAnimator | undefined;
constructor(source: AnimatorSource, { mod, create }: AnimatorRegistration) {
this.#source = source;
this.#mod = mod;
this.#entity = animated_entity(source);
this.#run("create", () => this.#animator = create(this.#entity));
for (const field of Object.keys(client_data(source.data))) this.#on_data(field);
}
// its client data was before and is now the source's
data_changed(before: EntityData) {
const old = client_data(before);
const now = client_data(this.#source.data);
for (const field of new Set([...Object.keys(old), ...Object.keys(now)])) {
if (JSON.stringify(old[field]) !== JSON.stringify(now[field])) this.#on_data(field);
}
}
// what the animator does to the bones at time, undefined when there's no animator (anymore)
pose(time: number): Map<string, BoneOffsets> | undefined {
const animator = this.#animator;
if (!animator) return undefined;
const offsets = new Map<string, BoneOffsets>();
const posed = this.#run("pose", () => animator.pose(entity_pose(offsets, this.#entity), time));
return posed ? offsets : undefined;
}
#on_data(field: string) {
const animator = this.#animator;
if (animator?.on_data) this.#run("on_data", () => animator.on_data!(field, this.#source.age));
}
// false when it threw, which is logged with the mod and the entity, and the animator is gone
#run(what: string, fn: () => void) {
try {
fn();
return true;
} catch (e) {
const { type, id } = this.#source;
console.error(`[${this.#mod}] the animator of ${type} ${id} threw in ${what}, it's removed:`, e);
this.#animator = undefined;
return false;
}
}
}
function client_data(data: EntityData): Record<string, unknown> {
return (data.client_data ?? {}) as Record<string, unknown>;
}
function animated_entity(source: AnimatorSource): AnimatedEntity {
// time is in ticks with the part of the next one, the source's walk and attack take that part
const partial = (time: number) => Math.min(Math.max(time - source.age, 0), 1);
return {
get id() {
return source.id;
},
get type() {
return source.type;
},
get_client_data: (field) => structuredClone(client_data(source.data)[field]) as never,
walk_position: (time) => source.walk_animation(partial(time)).position,
walk_speed: (time) => source.walk_animation(partial(time)).speed,
attack_progress: (time) => source.attack_animation(partial(time)),
// mirrored like a model's rotations, see model_math's own_matrix
get head_pitch() {
return -source.pitch * DEGREES;
},
get head_yaw() {
return -wrap_angle(source.head_yaw - source.yaw) * DEGREES;
},
};
}
// a clip by what ClientRender.clip gave
function clip_json(clip: Clip): ClipJson {
const json = EverythingRegistry.get<ClipJson>("animations", clip?.id);
if (!json) throw new Error(`${clip?.id} isn't a clip, see ctx.render.clip`);
return json;
}
function entity_pose(offsets: Map<string, BoneOffsets>, entity: AnimatedEntity): EntityPose {
const offset = (bone: string) => {
let found = offsets.get(bone);
if (!found) {
found = rest_offsets();
offsets.set(bone, found);
}
return found;
};
const pose: EntityPose = {
play(clip, seconds, weight = 1) {
sample_clip(clip_json(clip), seconds, offsets, weight);
},
play_state(clip, state, time, weight) {
if (state.started) pose.play(clip, state.seconds(time), weight);
},
play_walk(clip, walker, time, speed_scale = 1) {
pose.play(clip, walker.walk_position(time) / 20, Math.min(walker.walk_speed(time) * speed_scale, 1));
},
rotate(bone, x, y, z) {
const rotation = offset(bone).rotation;
rotation[0] += x;
rotation[1] += y;
rotation[2] += z;
},
move(bone, x, y, z) {
const position = offset(bone).position;
position[0] += x;
position[1] += y;
position[2] += z;
},
scale(bone, x, y, z) {
const scale = offset(bone).scale;
scale[0] *= x;
scale[1] *= y;
scale[2] *= z;
},
look(bone) {
pose.rotate(bone, entity.head_pitch, entity.head_yaw, 0);
},
};
return pose;
}
+14 -7
View File
@@ -1,10 +1,11 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no
// animation files yet: the model turns to the entity's yaw, a bone named "head" to where it looks, and bones named
// like minecraft's humanoid ones (right_arm, left_arm, right_leg, left_leg) swing as it walks, the right arm when it
// attacks too. entities without a model are their texture facing the camera, like minecraft's fishing hook
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. the model
// turns to the entity's yaw, and its bones are posed by its type's animator from a mod (see entity_animators.ts). without
// one, a bone named "head" turns to where it looks, and bones named like minecraft's humanoid ones (right_arm, left_arm,
// right_leg, left_leg) swing as it walks, the right arm when it attacks too. entities without a model are their texture
// facing the camera, like minecraft's fishing hook
import { AssetManager } from "@/client/assets.ts";
import type { Camera } from "@/client/camera.ts";
import type { RemoteEntity } from "@/client/entity/remote_entity.ts";
@@ -14,7 +15,7 @@ import type { SpriteRegion } from "@/common/constants.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { EntityBoneJson, EntityJson, EntityModelJson } from "@/common/mod_data.ts";
import { HURT_TINT } from "./player_renderer.ts";
import { IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
import { bone_matrices, IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
import { push_model } from "./model_renderer.ts";
import { entity_tint } from "./entity_light.ts";
@@ -44,8 +45,15 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
};
const offsets = entity.animation?.pose(entity.age + partial_tick);
const pose = offsets ? () => IDENTITY : default_pose(entity, partial_tick);
push_model(model, bone_matrices(model, pose, offsets), atlas, region, to_world, tint);
}
// the head looking and the humanoid swing, for an entity without an animator
function default_pose(entity: RemoteEntity, partial_tick: number) {
const limbs = limb_angles(entity, partial_tick);
const pose = (bone: EntityBoneJson) => {
return (bone: EntityBoneJson) => {
let matrix = IDENTITY;
if (bone.name === "head") {
matrix = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
@@ -54,7 +62,6 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
return matrix;
};
push_model(model, pose, atlas, region, to_world, tint);
}
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
+7 -1
View File
@@ -31,6 +31,7 @@ import {
push_vertex,
render_debug,
set_current_texture,
set_face_culling,
Texture,
use_texture,
view_projection,
@@ -180,10 +181,15 @@ export class LevelRenderer {
for (const entity of level.entities.values()) {
if (entity instanceof ItemEntity && this.#entity_in_view(entity, partial_tick)) {
render_item_entity(entity, partial_tick);
} else if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) {
}
}
set_face_culling(false);
for (const entity of level.entities.values()) {
if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) {
render_mod_entity(entity, camera, partial_tick);
}
}
set_face_culling(true);
render_block_items(level);
flush_batch();
}
+29 -6
View File
@@ -17,20 +17,43 @@ export function model_pivot(bone: EntityBoneJson): Vec3 {
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
}
// what animation does to a bone, in the model's bedrock space like its own pivot and rotation: degrees added to its
// rotation, pixels it moves and how much it's scaled, around its pivot
export type BoneOffsets = { rotation: Vec3; position: Vec3; scale: Vec3 };
// a bone's or a cube's own rotation around its pivot. mirroring x turns x and y rotations the other way
export function own_matrix(part: EntityBoneJson | EntityCubeJson): Matrix {
if (!part.rotation) return IDENTITY;
const [rx, ry, rz] = part.rotation.map((degrees) => degrees * Math.PI / 180);
const [px, py, pz] = part.pivot ?? [0, 0, 0];
return turn_around(part.pivot ?? [0, 0, 0], part.rotation);
}
function turn_around([px, py, pz]: Vec3, degrees: Vec3): Matrix {
const [rx, ry, rz] = degrees.map((n) => n * Math.PI / 180);
return rotation_around([-px, py, pz], -rx, -ry, rz);
}
// every bone's matrix: its own rotation, then pose's for it (like a head looking or a limb swinging), then its
// parent's. parents come before their children in the model
export function bone_matrices(model: EntityModelJson, pose: (bone: EntityBoneJson) => Matrix): Map<string, Matrix> {
// a bone's own rotation with what animation does to it: moved, then turned and scaled around its pivot
function animated_matrix(bone: EntityBoneJson, { rotation, position, scale }: BoneOffsets): Matrix {
const [rx, ry, rz] = bone.rotation ?? [0, 0, 0];
const turned = turn_around(bone.pivot, [rx + rotation[0], ry + rotation[1], rz + rotation[2]]);
const [px, py, pz] = model_pivot(bone);
const [sx, sy, sz] = scale;
const scaled = [sx, 0, 0, px - px * sx, 0, sy, 0, py - py * sy, 0, 0, sz, pz - pz * sz];
const moved = [1, 0, 0, -position[0], 0, 1, 0, position[1], 0, 0, 1, position[2]];
return multiply(moved, multiply(turned, scaled));
}
// every bone's matrix: its own rotation (with offsets' for it, from animation), then pose's for it (like a head
// looking or a limb swinging), then its parent's. parents come before their children in the model
export function bone_matrices(
model: EntityModelJson,
pose: (bone: EntityBoneJson) => Matrix,
offsets?: Map<string, BoneOffsets>,
): Map<string, Matrix> {
const bones = new Map<string, Matrix>();
for (const bone of model.bones) {
let matrix = multiply(pose(bone), own_matrix(bone));
const offset = offsets?.get(bone.name);
let matrix = multiply(pose(bone), offset ? animated_matrix(bone, offset) : own_matrix(bone));
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
bones.set(bone.name, matrix);
}
+6 -7
View File
@@ -5,15 +5,15 @@
import type { Texture } from "@/client/renderer/mod.ts";
import type { SpriteRegion } from "@/common/constants.ts";
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
import { apply, bone_matrices, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
import { apply, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
import { push_box, type VertexSink } from "./player_renderer.ts";
// pose is each bone's turn before its parent's, like a head looking or a limb swinging. to_world takes the model's
// pixels, after the bones are turned, to the world. the texture is region of the atlas, stretched to the model's
// texture size. only picks the bones drawn, all of them when not given. emit gets the vertices, the batch by default
// bones is each bone's matrix, see bone_matrices. to_world takes the model's pixels, after the bones are turned, to the
// world. the texture is region of the atlas, stretched to the model's texture size. only picks the bones drawn, all of
// them when not given. emit gets the vertices, the batch by default
export function push_model(
model: EntityModelJson,
pose: (bone: EntityBoneJson) => Matrix,
bones: Map<string, Matrix>,
atlas: Texture,
region: SpriteRegion,
to_world: (x: number, y: number, z: number) => Vec3,
@@ -25,11 +25,10 @@ export function push_model(
(region.x + u * region.width / model.texture_width) / atlas.width,
(region.y + v * region.height / model.texture_height) / atlas.height,
];
const matrices = bone_matrices(model, pose);
for (const bone of model.bones) {
if (only && !only(bone)) continue;
for (const cube of bone.cubes) {
const matrix = multiply(matrices.get(bone.name)!, own_matrix(cube));
const matrix = multiply(bones.get(bone.name)!, own_matrix(cube));
const transform = (px: number, py: number, pz: number) => to_world(...apply(matrix, px, py, pz));
const inflate = cube.inflate ?? 0;
const [ox, oy, oz] = cube.origin;
+39 -8
View File
@@ -3,6 +3,7 @@
import type { Player } from "@/client/entity/player.ts";
import { push_vertex, type Texture } from "@/client/renderer/mod.ts";
import type { FaceUvs } from "@/common/mod_data.ts";
import type { Vec3 } from "./model_math.ts";
import {
type ModelPart,
@@ -24,40 +25,52 @@ const UV_INSET = 0.01;
// a box's faces, like minecraft's ModelPart.Cube. `rect` is where the face is in the box's texture, which is laid
// out as in a skin: the top and bottom above the sides (right, front, left, back). corners go counter clockwise from
// outside as [x, y, z, u, v], 0 for the low end and 1 for the high one
const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: number[][]; shade: number }[] = [
// outside as [x, y, z, u, v], 0 for the low end and 1 for the high one. `name` is the face's in a bedrock model's per
// face uvs, which go where its box uv would put it except the bottom, which is upside down
const FACES: {
name: keyof FaceUvs;
rect: (w: number, h: number, d: number) => number[];
corners: number[][];
shade: number;
}[] = [
// top
{
name: "up",
rect: (w, _h, d) => [d, 0, w, d],
corners: [[1, 1, 0, 0, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 0], [1, 1, 1, 0, 0]],
shade: 1.0,
},
// bottom, the same way around as the top so it's mirrored from below like in minecraft
{
name: "down",
rect: (w, _h, d) => [d + w, 0, w, d],
corners: [[1, 0, 0, 0, 1], [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 1, 1]],
shade: 0.5,
},
// right
{
name: "east",
rect: (_w, h, d) => [0, d, d, h],
corners: [[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [1, 1, 0, 1, 0], [1, 1, 1, 0, 0]],
shade: 0.6,
},
// front
{
name: "north",
rect: (w, h, d) => [d, d, w, h],
corners: [[1, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 0], [1, 1, 0, 0, 0]],
shade: 0.8,
},
// left
{
name: "west",
rect: (w, h, d) => [d + w, d, d, h],
corners: [[0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 0, 0, 0]],
shade: 0.6,
},
// back
{
name: "south",
rect: (w, h, d) => [2 * d + w, d, w, h],
corners: [[0, 0, 1, 0, 1], [1, 0, 1, 1, 1], [1, 1, 1, 1, 0], [0, 1, 1, 0, 0]],
shade: 0.8,
@@ -87,6 +100,18 @@ export function render_player(skin: Texture, pose: PlayerPose, tint?: Vec3) {
}
}
// where a face is in the texture as [u, v, width, height] in pixels, undefined when per face uvs leave it out
function face_rect(face: typeof FACES[number], [w, h, d]: Vec3, uv: [number, number] | FaceUvs) {
if (Array.isArray(uv)) {
const [rx, ry, rw, rh] = face.rect(w, h, d);
return [uv[0] + rx, uv[1] + ry, rw, rh];
}
const own = uv[face.name];
if (!own) return undefined;
const [[u, v], [rw, rh]] = [own.uv, own.uv_size];
return face.name === "down" ? [u, v + rh, rw, -rh] : [u, v, rw, rh];
}
// what a box's vertices go to: the batch, or something collecting them, like the player in the inventory
export type VertexSink = typeof push_vertex;
@@ -105,13 +130,14 @@ export function push_cube(
push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform, tint, emit);
}
// a box of a model, from low to high, textured like minecraft's box uv from [u, v] for a box of size (in texture
// pixels). to_uv turns texture pixels into the current texture's coordinates, tint multiplies its colors
// a box of a model, from low to high, textured from uv: minecraft's box uv from [u, v] for a box of size (in texture
// pixels), or a bedrock model's per face uvs. to_uv turns texture pixels into the current texture's coordinates, tint
// multiplies its colors
export function push_box(
size: Vec3,
low: Vec3,
high: Vec3,
[u, v]: [number, number],
uv: [number, number] | FaceUvs,
to_uv: (u: number, v: number) => [number, number],
transform: (x: number, y: number, z: number) => Vec3,
tint: Vec3 = [1, 1, 1],
@@ -125,9 +151,14 @@ export function push_box(
points.push(transform(i & 4 ? high[0] : low[0], i & 2 ? high[1] : low[1], i & 1 ? high[2] : low[2]));
}
for (const face of FACES) {
const [rx, ry, rw, rh] = face.rect(w, h, d);
const [u0, v0] = to_uv(u + rx + UV_INSET, v + ry + UV_INSET);
const [u1, v1] = to_uv(u + rx + rw - UV_INSET, v + ry + rh - UV_INSET);
const rect = face_rect(face, size, uv);
if (!rect) continue;
const [rx, ry, rw, rh] = rect;
// inward, which is backwards on a flipped face
const inset_u = Math.sign(rw) * UV_INSET;
const inset_v = Math.sign(rh) * UV_INSET;
const [u0, v0] = to_uv(rx + inset_u, ry + inset_v);
const [u1, v1] = to_uv(rx + rw - inset_u, ry + rh - inset_v);
const r = tint[0] * face.shade;
const g = tint[1] * face.shade;
const b = tint[2] * face.shade;
+4 -3
View File
@@ -11,7 +11,7 @@ import type { Texture } from "@/client/renderer/mod.ts";
import { get_sprite_region } from "@/client/sprites.ts";
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
import { IDENTITY, type Vec3 } from "./model_math.ts";
import { bone_matrices, IDENTITY, type Vec3 } from "./model_math.ts";
import { push_model } from "./model_renderer.ts";
import type { VertexSink } from "./player_renderer.ts";
import { on_part, type PlayerPose, pose_to_world, right_arm, worn_bone_pose, worn_look } from "./player_model.ts";
@@ -34,7 +34,7 @@ export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3
if (!model) continue;
push_model(
model,
worn_bone_pose(pose),
bone_matrices(model, worn_bone_pose(pose)),
atlas,
get_sprite_region(look.texture),
to_world,
@@ -59,6 +59,7 @@ export function render_worn_arm(player: Player, transform: (x: number, y: number
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
if (!model) continue;
const only = (bone: EntityBoneJson) => on_part(model, bone, "right_arm");
push_model(model, () => IDENTITY, atlas, get_sprite_region(look.texture), to_arm, tint, only);
const bones = bone_matrices(model, () => IDENTITY);
push_model(model, bones, atlas, get_sprite_region(look.texture), to_arm, tint, only);
}
}
+250
View File
@@ -0,0 +1,250 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what sounds play on this client, and where from: ctx.sounds.play for client phases. the sounds are the mods'
// 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_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";
export type Volumes = Record<"master" | SoundCategory, number>;
// sounds playing at once at most. past that a new one is dropped, and loops wait for room
const MAX_VOICES = 64;
// what sounds come out of: web audio in the browser, a list in tests
export interface SoundOutput {
// starts a file playing. undefined when nothing can play now, like before the player's first click
start(file: SoundFile, settings: VoiceSettings): Voice | undefined;
// where the player hears from, and which way they look, in radians like the camera
listen(x: number, y: number, z: number, yaw: number, pitch: number): void;
set_volumes(volumes: Volumes): void;
}
// a mod's file, by "<mod id>:<path in its sounds/>"
export interface SoundFile {
readonly id: string;
readonly bytes: Uint8Array;
}
export interface VoiceSettings {
// only master's volume when not given
category: SoundCategory | undefined;
// heard as it is when not given
at: Position | undefined;
// where it's faded to nothing
range: number;
// over 1 is heard further, which range has already, not louder
volume: number;
pitch: number;
loop: boolean;
// seconds into the file it starts at, for one played with an offset or a loop coming back partway. past the file's
// length a loop goes around, and anything else has finished
offset: number;
}
// one file playing
export interface Voice {
// it played to its end
readonly ended: boolean;
move(at: Position): void;
set(volume: number, pitch: number, range: number): void;
stop(): void;
}
// where the player hears from, like the camera
export interface Listener extends Position {
yaw: number;
pitch: number;
}
class Playing implements PlayingSound {
voice: Voice | undefined;
done = false;
#volume: number;
#pitch: number;
constructor(
readonly json: SoundJson,
readonly file: SoundFile,
readonly options: ClientPlayOptions,
readonly started: number,
public at: Position | undefined,
) {
this.#volume = options.volume ?? 1;
this.#pitch = options.pitch ?? 1;
}
get playing() {
return !this.done;
}
stop() {
this.done = true;
this.voice?.stop();
this.voice = undefined;
}
get volume() {
return this.#volume;
}
set volume(volume: number) {
this.#volume = volume;
this.voice?.set(this.total_volume, this.total_pitch, this.range);
}
get pitch() {
return this.#pitch;
}
set pitch(pitch: number) {
this.#pitch = pitch;
this.voice?.set(this.total_volume, this.total_pitch, this.range);
}
get total_volume() {
return (this.json.volume ?? 1) * this.#volume;
}
get total_pitch() {
return (this.json.pitch ?? 1) * this.#pitch;
}
get range() {
return sound_range(this.json, this.#volume);
}
// whether the listener is close enough to hear it, always for one heard as it is
in_range(listener: Position) {
if (!this.at) return true;
const { x, y, z } = this.at;
return Math.hypot(x - listener.x, y - listener.y, z - listener.z) < this.range;
}
}
export class Sounds {
#output: SoundOutput | undefined;
// the mods' files, by "<mod id>:<path>"
#files = new Map<string, SoundFile>();
#playing: Playing[] = [];
#listener: Position = { x: 0, y: 0, z: 0 };
#entity_position: (id: string) => Position | undefined = () => undefined;
// seconds, for how far a loop has got
constructor(readonly clock = () => performance.now() / 1000) {}
set_output(output: SoundOutput) {
this.#output = output;
}
// the loaded mods' sound files, in place of the last server's
set_files(mods: { id: string; sounds?: Map<string, Uint8Array> }[]) {
this.stop_all();
this.#files.clear();
for (const mod of mods) {
for (const [path, bytes] of mod.sounds ?? []) {
const id = `${mod.id}:${path}`;
this.#files.set(id, { id, bytes });
}
}
}
exists(sound: string) {
return EverythingRegistry.get<SoundJson>("sounds", sound) !== undefined;
}
play(sound: string, options: ClientPlayOptions = {}): PlayingSound {
const json = sound_to_play(sound, options);
const offset = options.offset ?? 0;
if (typeof offset !== "number" || !(offset >= 0) || !Number.isFinite(offset)) {
throw new Error("a sound's offset must be 0 or more seconds");
}
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}`);
const at = options.follow !== undefined ? this.#entity_position(options.follow) : options.at;
const playing = new Playing(json, file, { ...options }, this.clock() - offset, at && { ...at });
this.#playing.push(playing);
// an entity this client doesn't have yet, like one whose animator is being made, has until the next frame to
// turn up
if (options.follow !== undefined && !at) return playing;
this.#start(playing);
if (!playing.voice && !options.loop) playing.done = true;
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 };
this.#entity_position = entity_position;
this.#output?.listen(listener.x, listener.y, listener.z, listener.yaw, listener.pitch);
this.#output?.set_volumes(volumes);
for (const playing of this.#playing) {
if (playing.done) continue;
const follow = playing.options.follow;
if (follow !== undefined) {
const at = entity_position(follow);
if (!at) {
playing.stop();
continue;
}
playing.at = { x: at.x, y: at.y, z: at.z };
playing.voice?.move(playing.at);
}
if (playing.voice?.ended) {
playing.voice = undefined;
if (!playing.options.loop) playing.done = true;
}
// loops out of range wait without a voice
if (playing.voice && playing.options.loop && !playing.in_range(this.#listener)) {
playing.voice.stop();
playing.voice = undefined;
}
}
this.#playing = this.#playing.filter((playing) => !playing.done);
for (const playing of this.#playing) {
if (playing.voice) continue;
this.#start(playing);
// one waiting for its entity that can't play now never will
if (!playing.voice && !playing.options.loop) playing.done = true;
}
}
// leaving the server
stop_all() {
for (const playing of this.#playing) playing.stop();
this.#playing = [];
}
// how many are playing now, for tests
get voices() {
return this.#playing.filter((playing) => playing.voice).length;
}
#start(playing: Playing) {
if (!this.#output || !playing.in_range(this.#listener) || this.voices >= MAX_VOICES) return;
playing.voice = this.#output.start(playing.file, {
category: playing.json.category,
at: playing.at,
range: playing.range,
volume: playing.total_volume,
pitch: playing.total_pitch,
loop: playing.options.loop ?? false,
offset: (this.clock() - playing.started) * playing.total_pitch,
});
}
}
// the client's, which ctx.sounds plays on
export const sounds = new Sounds();
+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
+35 -1
View File
@@ -8,17 +8,22 @@ import type { ModelFileJson } from "./block_models.ts";
import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts";
import {
type BlockJson,
type ClipJson,
type EffectJson,
type EntityJson,
type EntityModelJson,
type FluidJson,
is_ogg,
type ItemJson,
type ManifestJson,
type OreJson,
type RecipeJson,
SOUND_PATH_PATTERN,
type SoundJson,
type SpawnJson,
type TagJson,
validate_block,
validate_clip,
validate_effect,
validate_entity,
validate_entity_model,
@@ -28,6 +33,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_sound,
validate_spawn,
validate_tag,
} from "./mod_data.ts";
@@ -69,6 +75,8 @@ export interface Mod {
textures: Map<string, Uint8Array>;
// the .json of the textures that have one, like animated ones, by texture id
texture_json?: Map<string, TextureJson>;
// ogg bytes by path in its sounds/ without .ogg, like jester/stomp_1, what its sounds.json's files name
sounds?: Map<string, Uint8Array>;
credits?: string;
}
@@ -86,6 +94,7 @@ export class ModError extends Error {
// script.js
// textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one
// sounds/<path>.ogg a sound file, see SoundJson
// credits.md
export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
const text = (value: string) => new TextEncoder().encode(value);
@@ -108,6 +117,9 @@ export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
for (const [id, json] of mod.texture_json ?? []) {
files[`textures/${id.split(":")[1]}.json`] = text(JSON.stringify(json));
}
for (const [path, ogg] of mod.sounds ?? []) {
files[`sounds/${path}.ogg`] = ogg;
}
files["manifest.json"] = text(JSON.stringify(manifest, null, "\t"));
files["data.json"] = text(JSON.stringify(mod.data));
@@ -189,6 +201,8 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
validate_entity_model,
problems,
) as EntityModelJson[],
animations: checked(raw_data.animations, "animations", validate_clip, problems) as ClipJson[],
sounds: checked(raw_data.sounds, "sounds", validate_sound, problems) as SoundJson[],
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
fluids: checked(raw_data.fluids, "fluids", validate_fluid, problems) as FluidJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
@@ -228,6 +242,8 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
...data.items,
...data.entities,
...data.entity_models,
...data.animations!,
...data.sounds!,
...data.effects,
...data.fluids,
];
@@ -298,8 +314,26 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
}
}
const sounds = new Map<string, Uint8Array>();
for (const [name, content] of Object.entries(files)) {
const match = name.match(/^sounds\/(.+)\.ogg$/);
if (!match) continue;
if (!SOUND_PATH_PATTERN.test(match[1])) {
problems.push(`${name}: sound paths must be a-z, 0-9 and _ in folders`);
} else if (!is_ogg(content)) {
problems.push(`${name}: isn't an ogg file`);
} else {
sounds.set(match[1], content);
}
}
for (const sound of data.sounds!) {
for (const path of Array.isArray(sound.files) ? sound.files : []) {
if (!sounds.has(path)) problems.push(`sound ${sound.id}: there's no sounds/${path}.ogg`);
}
}
if (problems.length > 0) throw new ModError(file, problems);
return { manifest, data, script, textures, texture_json, credits };
return { manifest, data, script, textures, texture_json, sounds, credits };
}
// the same mod without the terrain's data, its schematics and its config, what players get. the server sends them the world. its
+134
View File
@@ -9,6 +9,7 @@ import type {
ItemStack,
KeyCode,
ModInfo,
PlayOptions,
Position,
RecipeLookup,
Season,
@@ -24,6 +25,7 @@ export type {
ItemStack,
KeyCode,
ModInfo,
PlayOptions,
Position,
Season,
TagApi,
@@ -124,9 +126,43 @@ export interface ClientContext {
tags: TagApi;
// blocks drawn with code, like a shaft that turns, see docs/modding/blocks/visuals.md
render: ClientRender;
// sounds from the mods' sounds.json, played on this client only, see docs/modding/resources/sounds.md
sounds: ClientSounds;
log(...args: unknown[]): void;
}
export interface ClientSounds {
// plays a sound on this client. without at or follow it's heard as it is wherever the player is, like a click in a
// screen. throws for a sound no mod defines
play(sound: Id, options?: ClientPlayOptions): PlayingSound;
exists(sound: Id): boolean;
}
export interface ClientPlayOptions extends PlayOptions {
// where it comes from, fading out with distance until its range
at?: Position;
// an entity's id: it moves with the entity, and stops when the entity goes
follow?: string;
// plays again from the start until it's stopped. one out of the player's range waits silently, and comes back in
// as far into the file as it would have got
loop?: boolean;
// plays as if it had started this many seconds ago, for a sound that goes with something that's been going on a
// while, like a jester that was already winding when the player came. a sound that would have finished by now
// doesn't play. 0 when not given
offset?: number;
}
// a sound ctx.sounds.play started
export interface PlayingSound {
// false once it finished, was stopped, or what it followed went. a sound that couldn't play at all, like one
// played out of range or before the player first clicked, is never playing, unless it loops
readonly playing: boolean;
stop(): void;
// what play was given, changed while it plays, like a machine speeding up
volume: number;
pitch: number;
}
export interface ClientRender {
// every block of this id gets a visual from create while its chunk is shown, like a block entity renderer or
// flywheel's visuals. only during setup, and one per block. replaces_model leaves the block's model out of the
@@ -136,6 +172,104 @@ export interface ClientRender {
create: (block: VisualBlock, instances: Instances) => Visual,
options?: { replaces_model?: boolean },
): void;
// every entity of this type gets an animator from create while the client has it, which poses its model's bones
// each frame instead of the engine's head look and humanoid swing, like a model's setupAnim. only during setup,
// and one per type. see docs/modding/entities/index.md#animations
register_entity_animator(type: Id, create: (entity: AnimatedEntity) => EntityAnimator): void;
// a clip, from a bedrock animation file in animations/: animation.walker.walk in animations/walker.animation.json
// is my_mod:walker/walk. throws when there isn't one, so a typo shows up at setup
clip(id: string): Clip;
}
// what poses one entity. time is its age on this client in ticks, with the part of the next one, the same time
// AnimationState takes. one that throws is removed, with the error in the console, and the entity posed without it
export interface EntityAnimator {
// before each frame the entity is drawn
pose(pose: EntityPose, time: number): void;
// a field of its client data changed (see MobRef.set_client_data in cubi/server), or was already set when the
// animator was made
on_data?(field: string, time: number): void;
}
// the entity an animator poses
export interface AnimatedEntity {
readonly id: string;
readonly type: Id;
// a field of its client data now, a copy, see MobRef.set_client_data in cubi/server
get_client_data<T>(field: string): T | undefined;
// how far it's walked, about 1 a tick at full speed, and how fast it's walking now, 0 to 1. they ease
// toward its movement, so a clip doesn't jump when it starts or stops
walk_position(time: number): number;
walk_speed(time: number): number;
// how far through its attack swing it is, 0 to 1, 0 when it isn't swinging
attack_progress(time: number): number;
// how a bone facing the way its body does turns to where it looks, in degrees, as EntityPose.rotate takes them
readonly head_pitch: number;
readonly head_yaw: number;
}
// a clip from animations/, see ClientRender.clip
export interface Clip {
readonly id: string;
// seconds
readonly length: number;
// one that doesn't stays on its last frame after its length
readonly loop: boolean;
}
// a model's bones for one frame, all at rest until something moves them. what's played and added adds up: rotations
// and positions add, scales multiply. bones are the model's by name, ones it doesn't have do nothing
export interface EntityPose {
// clip at seconds into it. weight scales what it does, 1 when not given
play(clip: Clip, seconds: number, weight?: number): void;
// clip from when state started, nothing while it's stopped
play_state(clip: Clip, state: AnimationState, time: number, weight?: number): void;
// clip as it walks, like neoforge's applyWalk: as far through as it's walked (a second of clip for 20 of
// walk_position) and as strongly as it's walking, times speed_scale, at most 1
play_walk(clip: Clip, entity: AnimatedEntity, time: number, speed_scale?: number): void;
// on top of the clips, in degrees, pixels and how much it's scaled, like the clips. bedrock's +x, like the model
rotate(bone: string, x: number, y: number, z: number): void;
move(bone: string, x: number, y: number, z: number): void;
scale(bone: string, x: number, y: number, z: number): void;
// turns a bone to where the entity looks, like the engine does a bone named head without an animator
look(bone: string): void;
}
// when something an animator plays started, like neoforge's AnimationState. time is in ticks, see EntityAnimator
export class AnimationState {
#started: number | undefined;
get started() {
return this.#started !== undefined;
}
start(time: number) {
this.#started = time;
}
stop() {
this.#started = undefined;
}
start_if_stopped(time: number) {
if (this.#started === undefined) this.#started = time;
}
// starts it when condition holds and it's stopped, and stops it when it doesn't
animate_when(condition: boolean, time: number) {
if (condition) this.start_if_stopped(time);
else this.stop();
}
// seconds since it started, at 20 ticks a second. 0 while it's stopped
seconds(time: number) {
return this.#started === undefined ? 0 : (time - this.#started) / 20;
}
// whether a clip that doesn't loop has played to its end since this started. never for one that loops
finished(clip: Clip, time: number) {
return this.started && !clip.loop && this.seconds(time) >= clip.length;
}
}
// the block a visual draws
+32
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
@@ -180,6 +194,12 @@ export interface LivingRef {
// cause is for events and the death message, like "magic"
damage(amount: number, cause?: string): void;
heal(amount: number): void;
// its stats, like Player's: "cubi:movement_speed", "cubi:attack_damage"... a mob's modifiers are saved with it
attribute(id: Id): number;
// replaces one with the same id on that attribute
add_modifier(attribute: Id, modifier: AttributeModifier): void;
// whether it had it
remove_modifier(attribute: Id, id: string): boolean;
}
export interface ComponentRegistry {
@@ -284,6 +304,13 @@ export interface MobRef extends LivingRef {
jump(): void;
// swings its arm and hits target with its attack_damage, wherever target is
attack(target: Player | MobRef): void;
// what clients see of its state, like BlockRef's: what its animator reads (see register_entity_animator in
// cubi/client). each field is any json value, saved with it, and sent to clients when it changes. undefined
// 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
@@ -559,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 {
@@ -623,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;
+14
View File
@@ -116,6 +116,14 @@ export interface Position {
z: number;
}
// how a sound plays, on top of what its definition in sounds.json says. see docs/modding/resources/sounds.md
export interface PlayOptions {
// multiplies the sound's own. over 1 it's heard further away, not louder
volume?: number;
// multiplies the sound's own: 2 is an octave up and twice as fast
pitch?: number;
}
export type Face = "west" | "east" | "bottom" | "top" | "north" | "south";
// KeyboardEvent.code values, like "KeyE" or "Digit1"
@@ -182,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
+26
View File
@@ -4,10 +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,
@@ -15,6 +18,7 @@ import {
type OreJson,
type RecipeJson,
SHARED_TAG_NAMESPACE,
type SoundJson,
type SpawnJson,
type TagJson,
type TagRegistry,
@@ -64,6 +68,10 @@ export interface LoadedMod {
spawns: { file: string; json: SpawnJson }[];
entities: { file: string; json: EntityJson }[];
entity_models: { file: string; json: EntityModelJson }[];
// clips, see ClipJson
animations: { file: string; json: ClipJson }[];
// its sounds.json, see docs/modding/resources/sounds.md
sounds: { file: string; json: SoundJson }[];
effects: { file: string; json: EffectJson }[];
fluids: { file: string; json: FluidJson }[];
tags: { file: string; json: TagJson }[];
@@ -85,6 +93,8 @@ export interface LoadedMod {
texture_files: Map<string, string>;
// textures/<name>.json by texture id, for the textures that have one (see texture_animation.ts)
texture_json: Map<string, TextureJson>;
// absolute paths of its sounds/ files by path in sounds/ without .ogg, like jester/stomp_1
sound_files: Map<string, string>;
}
// what a mod's data files hold, as packed into its .cubi
@@ -98,6 +108,8 @@ export function mod_data(mod: LoadedMod): ModData {
spawns: mod.spawns.map((s) => s.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
animations: mod.animations.map((a) => a.json),
sounds: mod.sounds.map((s) => s.json),
effects: mod.effects.map((e) => e.json),
fluids: mod.fluids.map((f) => f.json),
tags: mod.tags.map((t) => t.json),
@@ -183,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(),
@@ -238,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));
@@ -285,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(", ")}`);
@@ -299,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)) {
@@ -381,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);
}
+285 -2
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,
@@ -67,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) =>
@@ -116,6 +120,7 @@ export interface BlockJson {
item?: boolean;
interactive?: boolean;
scrollable?: boolean;
sounds?: string;
replaceable?: boolean;
place_on?: string[];
place_in?: string[];
@@ -194,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(),
@@ -456,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>;
@@ -506,11 +515,29 @@ const fluid_schema = z.object({
export type FluidJson = z.infer<typeof fluid_schema>;
// a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES
const uv_pair = z.tuple([z.number(), z.number()]);
// where one face of a cube is in the texture, from uv to uv + uv_size. a negative size flips it
const face_uv = z.object({ uv: uv_pair, uv_size: uv_pair });
// a cube's faces, by the way they face. one that isn't here isn't drawn
const face_uvs = z.object({
north: face_uv.optional(),
east: face_uv.optional(),
south: face_uv.optional(),
west: face_uv.optional(),
up: face_uv.optional(),
down: face_uv.optional(),
});
export type FaceUvs = z.infer<typeof face_uvs>;
// a box from origin to origin + size. its uv is either [u, v], where a box's texture starts laid out like minecraft's
// box uv (see the renderer's FACES), or where each face is
const entity_cube = z.object({
origin: vec3,
size: vec3,
uv: z.tuple([z.number(), z.number()], "must be [u, v], per face uvs aren't supported"),
uv: z.union([uv_pair, face_uvs]),
// grows the box this many pixels each way without moving its texture
inflate: z.number().optional(),
// what rotation turns the box around, inside its bone
@@ -556,6 +583,107 @@ const entity_model_schema = z.object({
export type EntityModelJson = z.infer<typeof entity_model_schema>;
// a channel's value at a time in seconds. pre is what it comes into the keyframe at and post what it leaves at, the
// same unless it jumps there. smooth is catmullrom to and from it, linear otherwise
const clip_keyframe = z.object({ time: z.number().min(0), pre: vec3, post: vec3, smooth: z.boolean() });
export type ClipKeyframe = z.infer<typeof clip_keyframe>;
const clip_channel = z.array(clip_keyframe).min(1).refine(
(keyframes) => keyframes.every((keyframe, i) => i === 0 || keyframes[i - 1].time <= keyframe.time),
"keyframes must be in time order",
);
// an entity model animation (one of those in animations/<name>.animation.json) with only what the engine uses, see
// docs/modding/entities/index.md#clips. values are as bedrock has them, mirrored on x from the engine's like models: rotation in degrees,
// added to a bone's own, position in pixels, and scale multiplying
const clip_schema = z.object({
id: z.string('must be a clip id like "my_mod:thing/walk"').regex(TAG_ID_PATTERN),
// seconds
length: z.number().min(0),
loop: z.boolean(),
bones: z.record(
z.string(),
z.object({
rotation: clip_channel.optional(),
position: clip_channel.optional(),
scale: clip_channel.optional(),
}),
),
});
export type ClipJson = z.infer<typeof clip_schema>;
// which volume slider a sound follows, each under the player's master volume. see docs/modding/resources/sounds.md
export const SOUND_CATEGORIES = ["music", "ambient", "blocks", "entities", "players", "ui"] as const;
export type SoundCategory = typeof SOUND_CATEGORIES[number];
// a path in a mod's sounds/ without .ogg, like jester/stomp_1, and a sound's name in sounds.json
export const SOUND_PATH_PATTERN = /^[a-z0-9_]+(\/[a-z0-9_]+)*$/;
// one of the sounds in a mod's sounds.json, with its id: the key "jester/step" in dangerous_business's is
// dangerous_business:jester/step
const sound_schema = z.object({
id: z.string('must be a sound id like "my_mod:thing/step"').regex(TAG_ID_PATTERN),
// paths in the mod's own sounds/, one picked at random each time it plays
files: z.array(
z.string('must be a path in sounds/ without .ogg, like "thing/step_1"').regex(SOUND_PATH_PATTERN),
).min(1),
// at most 1, plays multiply it. 1 when not given
volume: z.number().min(0).max(1).optional(),
// 1 when not given
pitch: z.number().gt(0).optional(),
// how far away it's heard at volume 1, in blocks. 16 when not given
range: z.number().gt(0).optional(),
// only the master volume when not given
category: z.enum(SOUND_CATEGORIES).optional(),
});
export type SoundJson = z.infer<typeof sound_schema>;
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;
// 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 {
return bytes.length >= 4 && bytes[0] === 0x4f && bytes[1] === 0x67 && bytes[2] === 0x67 && bytes[3] === 0x53;
}
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
const tag_entry = z.union(
[id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })],
@@ -686,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;
@@ -738,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;
@@ -964,6 +1094,159 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti
return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems };
}
export function validate_clip(json: unknown): Problems {
return find_problems(clip_schema, json);
}
// what a bedrock animation can have that clips leave to an animator's code
const ANIMATOR_FIELDS = [
"anim_time_update",
"blend_weight",
"start_delay",
"loop_delay",
"override_previous_animation",
"sound_effects",
"particle_effects",
"timeline",
];
// an animations/<name>.animation.json, as blockbench exports it for bedrock, to its clips. each is <file_id>/ and the
// last part of its name, so animation.jester.walk in dangerous_business:jester is dangerous_business:jester/walk.
// warnings are what it has that clips don't use
export function clips_from_bedrock(
json: unknown,
file_id: string,
): { clips: ClipJson[]; problems: Problems; warnings: Problems } {
const problems: Problems = [];
const warnings: Problems = [];
if (!is_object(json) || !is_object(json.animations)) {
problems.push('must be a bedrock animation file: { "animations": { "animation.thing.walk": { ... } } }');
return { clips: [], problems, warnings };
}
const clips: ClipJson[] = [];
for (const [name, animation] of Object.entries(json.animations)) {
const problem = (message: string) => problems.push(`${name}: ${message}`);
const id = `${file_id}/${name.split(".").at(-1)!.toLowerCase()}`;
if (clips.some((clip) => clip.id === id)) {
problem(`its id ${id} is another animation's too`);
continue;
}
if (!is_object(animation)) {
problem("must be an object");
continue;
}
for (const field of ANIMATOR_FIELDS) {
if (field in animation) warnings.push(`${name}: ${field} isn't used, an animator does that in code`);
}
if (![undefined, true, false, "hold_on_last_frame"].includes(animation.loop as string)) {
problem('loop must be true, false or "hold_on_last_frame"');
}
const length = animation.animation_length;
if (length !== undefined && (typeof length !== "number" || length < 0)) {
problem("animation_length must be a number of seconds");
}
const bones: ClipJson["bones"] = {};
let last = 0;
for (const [bone, channels] of Object.entries(is_object(animation.bones) ? animation.bones : {})) {
if (!is_object(channels)) {
problem(`${bone} must be an object of channels`);
continue;
}
const read: ClipJson["bones"][string] = {};
for (const [channel, value] of Object.entries(channels)) {
if (channel !== "rotation" && channel !== "position" && channel !== "scale") {
warnings.push(`${name}: ${bone}'s ${channel} isn't used`);
continue;
}
const keyframes = read_channel(value, (message) => problem(`${bone} ${channel}: ${message}`));
if (!keyframes) continue;
read[channel] = keyframes;
last = Math.max(last, keyframes.at(-1)!.time);
}
bones[bone] = read;
}
const clip = { id, length: typeof length === "number" ? length : last, loop: animation.loop === true, bones };
for (const message of validate_clip(clip)) problem(message);
clips.push(clip);
}
return { clips: problems.length === 0 ? clips : [], problems, warnings };
}
// a channel: one value for the whole clip, or keyframes by time in seconds
function read_channel(value: unknown, problem: (message: string) => void): ClipKeyframe[] | undefined {
const single = !is_object(value) || "pre" in value || "post" in value || "vector" in value;
if (single) {
const keyframe = read_keyframe(0, value, problem);
return keyframe && [keyframe];
}
const keyframes: ClipKeyframe[] = [];
for (const [time, keyframe_value] of Object.entries(value)) {
const seconds = Number(time);
if (time.trim() === "" || !(seconds >= 0)) {
problem(`${time} isn't a time in seconds`);
return undefined;
}
const keyframe = read_keyframe(seconds, keyframe_value, (message) => problem(`at ${time}: ${message}`));
if (!keyframe) return undefined;
keyframes.push(keyframe);
}
if (keyframes.length === 0) {
problem("has no keyframes");
return undefined;
}
return keyframes.sort((a, b) => a.time - b.time);
}
// a value, { "pre": value, "post": value, "lerp_mode": ... } with either of pre and post, or geckolib's older
// { "vector": value, "easing": ... }
function read_keyframe(time: number, value: unknown, problem: (message: string) => void): ClipKeyframe | undefined {
if (!is_object(value)) {
const vector = read_vector(value, problem);
return vector && { time, pre: vector, post: vector, smooth: false };
}
const lerp = "vector" in value ? value.easing : value.lerp_mode;
if (lerp !== undefined && lerp !== "linear" && lerp !== "catmullrom") {
problem(`${"vector" in value ? "easing" : "lerp_mode"} ${JSON.stringify(lerp)} isn't supported`);
return undefined;
}
if ("vector" in value) {
const vector = read_vector(value.vector, problem);
return vector && { time, pre: vector, post: vector, smooth: lerp === "catmullrom" };
}
if (value.pre === undefined && value.post === undefined) {
problem("needs pre or post");
return undefined;
}
const pre = read_vector(value.pre ?? value.post, problem);
const post = read_vector(value.post ?? value.pre, problem);
return pre && post && { time, pre, post, smooth: lerp === "catmullrom" };
}
// [x, y, z], or one number for all three. numbers can be written as text, but not expressions, which are code
function read_vector(value: unknown, problem: (message: string) => void): [number, number, number] | undefined {
if (!Array.isArray(value)) {
const number = read_number(value, problem);
return number === undefined ? undefined : [number, number, number];
}
if (value.length !== 3) {
problem("must be [x, y, z] or a number");
return undefined;
}
const numbers = value.map((part) => read_number(part, problem));
return numbers.every((number) => number !== undefined) ? numbers as [number, number, number] : undefined;
}
function read_number(value: unknown, problem: (message: string) => void): number | undefined {
const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
if (typeof number === "number" && Number.isFinite(number)) return number;
problem(
typeof value === "string"
? `${JSON.stringify(value)} is an expression, which clips can't run: an animator does that in code`
: "must be [x, y, z] or a number",
);
return undefined;
}
// a tag file's contents, with the registry and id its path gives it
export function validate_tag(json: unknown): Problems {
return find_problems(tag_schema, json);
+12
View File
@@ -10,6 +10,7 @@ import {
choice_ids,
choice_list,
choice_problems,
ClipJson,
EffectJson,
EntityJson,
EntityModelJson,
@@ -23,6 +24,7 @@ import {
ModRecipeJson,
OreJson,
RecipeJson,
SoundJson,
SpawnJson,
stack_problems,
TagJson,
@@ -59,6 +61,10 @@ export interface ModData {
spawns: SpawnJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// clips, see ClipJson. missing from mods packed before there were any
animations?: ClipJson[];
// its sounds.json, see docs/modding/resources/sounds.md. the files are in the .cubi's sounds/
sounds?: SoundJson[];
// status effects, see EffectJson
effects: EffectJson[];
// kinds of fluid, see FluidJson
@@ -224,6 +230,12 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const model of data.entity_models) {
EverythingRegistry.register<EntityModelJson>("entity_models", model.id, model);
}
for (const clip of data.animations ?? []) {
EverythingRegistry.register<ClipJson>("animations", clip.id, clip);
}
for (const json of data.sounds ?? []) {
EverythingRegistry.register<SoundJson>("sounds", json.id, json);
}
for (const json of data.entities) {
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
+13 -2
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;
@@ -52,7 +52,8 @@ export type EntityInfo =
};
// what an entity looks like that can change, like minecraft's SynchedEntityData: custom_name, custom_name_visible,
// glowing, on_fire, silent, left_handed, equipment (slot to item). only what's set is there
// glowing, on_fire, silent, left_handed, equipment (slot to item), and client_data (a mod's fields, see
// MobRef.set_client_data). only what's set is there
export type EntityData = Record<string, unknown>;
// what happens to an entity that clients show, see entity_event
@@ -266,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));
+2
View File
@@ -98,6 +98,8 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
spawns: [],
entities: [],
entity_models: [],
animations: [],
sounds: [],
effects: [],
fluids: [],
loot_tables: [],
+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). |
+4
View File
@@ -82,6 +82,10 @@ interface LivingRef {
effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined;
damage(amount: number, cause?: string): void; // cause is for events and the death message
heal(amount: number): void;
// its attributes and their modifiers, like a player's (see players.md). a mob's modifiers are saved with it
attribute(id: Id): number;
add_modifier(attribute: Id, modifier: AttributeModifier): void;
remove_modifier(attribute: Id, id: string): boolean;
}
```
+88 -5
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.
@@ -169,10 +170,19 @@ interface MobRef extends LivingRef {
look_at(x: number, y: number, z: number): void; // for a couple of ticks, so call it every tick
jump(): void; // this tick, or swims up in water
attack(target: Player | MobRef): void; // swings and hits with its attack_damage
// what clients see of its state, for its animator, see Animators
get_client_data<T>(field: string): T | undefined;
set_client_data(field: string, value: unknown): void;
}
```
Each mob has one `MobRef`, so `mob.target === player` works.
Each mob has one `MobRef`, so `mob.target === player` works. Like any living entity, it has attributes that modifiers
change, so a mob that speeds up the longer it chases can do it with a modifier on its speed:
```ts
mob.add_modifier("cubi:movement_speed", { id: "my_mod:rush", amount: 0.4, operation: "add_multiplied_total" });
mob.remove_modifier("cubi:movement_speed", "my_mod:rush");
```
## Getting Around
@@ -322,11 +332,13 @@ get the id `<mod id>:<name>`. From the file's first geometry, bworld uses:
- each bone's `name`, `parent`, `pivot` and `rotation`,
- each cube's `origin`, `size`, `uv`, `inflate`, `pivot` and `rotation`.
Cubes need box UV: per face UV isn't supported. A bone's parent has to come before it. The model faces -z, 16 pixels to
a block with its feet at 0, and shows the way Blockbench shows it.
Cubes can use box UV (`"uv": [u, v]`) or per face UV (`"uv": { "north": { "uv": [u, v], "uv_size": [w, h] }, ... }`),
where a face that's left out isn't drawn and a negative size flips it. Faces are drawn from both sides, like Bedrock's
`entity_alphatest` material, so a flat cube needs only one textured face. A bone's parent has to come before it. The
model faces -z, 16 pixels to a block with its feet at 0, and shows the way Blockbench shows it.
There are no animation files yet. The whole model turns with the entity, and bones with Minecraft's humanoid names move
on their own:
The whole model turns with the entity. An entity type with an [animator](#animations) has its bones posed by that.
Without one, bones with Minecraft's humanoid names move on their own:
- `head` turns to where the entity looks.
- `right_arm`, `left_arm`, `right_leg` and `left_leg` swing as it walks, each arm with the opposite leg.
@@ -334,3 +346,74 @@ on their own:
Without a model, the whole texture is drawn facing the camera, 16 pixels to a block, centered on the middle of the
entity's box.
## Animations
Animations are keyframes made in Blockbench, played by code in the mod's client script. This is how NeoForge does it
too: JSON keyframes, applied by the model's own `setupAnim`. Bedrock's Molang expressions and animation controllers
aren't used, since the animator does both in TypeScript.
### Clips
`animations/<name>.animation.json` are animation files as Blockbench exports them for Bedrock. Each animation in one is
a clip, named after the file and the last part of the animation's name: `animation.coilhead.walk` in
`animations/coilhead.animation.json` is `<mod id>:coilhead/walk`. From each animation, bworld uses:
- `animation_length`, in seconds, or the last keyframe's time without it,
- `loop`: `true` loops. `false`, no `loop` and `"hold_on_last_frame"` all stay on the last frame after the clip's end,
- each bone's `rotation` (degrees, added to the bone's own), `position` (pixels) and `scale`, as one value for the whole
clip or keyframes by time. A keyframe is a number for all three axes, `[x, y, z]`, `{ "pre": ..., "post": ... }`, and
can be `"lerp_mode": "catmullrom"` for a smooth curve.
A value that's a Molang expression, like `"math.cos(query.life_time * 180) * 2.5"`, is an error: do it in the animator
with `pose.rotate` or `pose.move`. `deno task check-mods` warns about what the animator does instead, like
`sound_effects` and `anim_time_update`.
### Animators
The client phase registers an animator for an entity type. Each entity of that type the client has gets its own, and
before each frame it's drawn, the animator plays clips and moves bones. A coilhead that bobs as it walks, looks around,
and plays `stop` once when it freezes:
```ts
import { AnimationState, type ClientContext } from "cubi/client";
export function client(ctx: ClientContext) {
const walk = ctx.render.clip("my_mod:coilhead/walk");
const stop = ctx.render.clip("my_mod:coilhead/stop");
ctx.render.register_entity_animator("my_mod:coilhead", (coilhead) => {
const frozen = new AnimationState();
return {
on_data(field, time) {
if (field === "frozen") frozen.animate_when(coilhead.get_client_data("frozen") === true, time);
},
pose(pose, time) {
if (frozen.started && !frozen.finished(stop, time)) pose.play_state(stop, frozen, time);
else pose.play_walk(walk, coilhead, time);
pose.look("head");
},
};
});
}
```
- `time` is the entity's age on this client in ticks, with the part of the next one.
- `pose.play(clip, seconds, weight)` plays a clip at some point in it. Clips played together add up, and `weight` scales
one, so blending from one to another is turning one down while the other goes up.
- `pose.play_state(clip, state, time)` plays it from when an `AnimationState` started. An animator keeps one for each
clip it starts on its own, and starts and stops it with `start`, `stop` and `animate_when`.
- `pose.play_walk(clip, entity, time)` plays it as far through as the entity has walked, as strongly as it's walking.
- `pose.rotate`, `pose.move` and `pose.scale` add to a bone on top of the clips, in the clips' units.
- `pose.look(bone)` turns a bone to where the entity looks.
An animator that throws is removed, with the error in the console, and its entity goes back to the humanoid pose.
What the animator knows of the mob's state comes from its client data, which the server side sets:
```ts
mob.set_client_data("frozen", true);
mob.set_client_data("frozen", undefined); // removes it
```
Client data is saved with the mob and sent to players when it changes. The animator's `on_data` hears about each field
as it changes, and about the ones already set when the entity first shows up.
+4 -1
View File
@@ -32,6 +32,8 @@ mods/
schematics/*.cbsm # schematics, never sent to players. see misc/schematics.md
textures/*.png
textures/*.json # animations, see resources/textures.md
sounds/**/*.ogg # sound files, see resources/sounds.md
sounds.json # the sounds they make up
scripts/
main.ts # the mod's script, its exports are its phases. sent to players, see concepts/sides.md
*.ts # whatever else it imports
@@ -116,10 +118,11 @@ deno task build # packs every mod in mods/ into server_mo
```
copper_tools.cubi
manifest.json # with main and credits pointing into the zip
data.json # every block, model, item, entity, recipe, ore, tag, loot table and schematic, and the config
data.json # every block, model, item, entity, recipe, ore, tag, loot table, sound and schematic, and the config
script.js # the script bundled into one module
textures/<name>.png
textures/<name>.json # for animated textures
sounds/<path>.ogg
credits.md
```
+207
View File
@@ -0,0 +1,207 @@
# 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
Any `.ogg` (Vorbis or Opus) in `sounds/`, in folders if you like. Its path without `.ogg` is what `sounds.json` names it
by, so `sounds/walker/step_1.ogg` is `walker/step_1`. Paths are a-z, 0-9 and `_`.
Mono and stereo files both work, from a point in the world or not.
## `sounds.json`
```json
{
"format_version": 1,
"sounds": {
"walker/step": {
"files": ["walker/step_1", "walker/step_2", "walker/step_3"],
"category": "entities"
},
"walker/theme": { "files": ["walker/theme"], "category": "entities", "range": 32 },
"click": { "files": ["click"], "category": "ui", "volume": 0.5 }
}
}
```
Each key is a sound, whose id is `<mod id>:<key>`, so `walker/step` in `copper_tools` is `copper_tools:walker/step`. Any
mod can play any sound by its id.
| Field | What it does |
| ---------- | ----------------------------------------------------------------------------------------------------------- |
| `files` | The files it plays, one picked at random each time. A file listed twice comes up twice as often. |
| `volume` | 0 to 1, 1 if not given. Every play multiplies it. |
| `pitch` | 1 if not given. Every play multiplies it. |
| `range` | How far away it's heard at volume 1, in blocks. 16 if not given. |
| `category` | Which volume the player's settings play it at: `music`, `ambient`, `blocks`, `entities`, `players` or `ui`. |
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
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
export function client(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({
on_render(g) {
if (g.button("Ring", 4, 4, 40, 18)) ctx.sounds.play("copper_tools:click");
},
});
}
```
With nothing but its id it's heard as it is wherever the player is, like a click in a screen. The options:
| Option | What it does |
| -------- | --------------------------------------------------------------------------------------------------- |
| `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. |
| `pitch` | Multiplies the sound's own. 2 is an octave up, and twice as fast. |
| `offset` | Plays as if it had started this many seconds ago. One that would have finished by now doesn't play. |
`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 });
hum.pitch = 1.5; // the machine sped up
if (!hum.playing) ctx.log("it's done");
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
- **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.
- **More than 64 at once.** A new sound past that is dropped, and a loop waits for room.
Either way `playing` is false for a sound that never played. A file plays a moment late the first time, since it's only
decoded once something plays it.
## Lasting Sounds
A sound that lasts as long as something does, like a machine's hum while it runs or a monster's music while it's in a
state, goes with what the client already knows. Start it when that begins and stop it when it ends, like in an entity's
animator when its [client data](../entities/index.md) changes:
```ts
ctx.render.register_entity_animator("copper_tools:walker", (walker) => {
let theme: PlayingSound | undefined;
return {
on_data(field) {
if (field !== "angry") return;
if (walker.get_client_data<boolean>("angry")) {
theme ??= ctx.sounds.play("copper_tools:walker/theme", { follow: walker.id, loop: true });
} else {
theme?.stop();
theme = undefined;
}
},
pose(pose, time) {/* ... */},
};
});
```
A player who comes near after it started hears it too, since the animator gets the data when it's made. It starts from
the beginning for them though, which is fine for a hum but not for music counting down to something. For that, the
server puts when it started in the client data too, and the animator plays it with an `offset`:
```ts
// server, when it gets angry
mob.set_client_data("angry_since", ctx.world.time);
// client, in on_data. world time is in ticks
const since = walker.get_client_data<number>("angry_since") ?? ctx.world.time;
theme ??= ctx.sounds.play("copper_tools:walker/theme", {
follow: walker.id,
loop: true,
offset: (ctx.world.time - since) / 20,
});
```
Play it as a loop even when it's longer than what it goes with: a sound that isn't a loop and is played out of range is
dropped, while a loop waits for the player to come near and comes in where it would be by then.
+19 -2
View File
@@ -68,6 +68,10 @@ plain object mods can hook. See [Engine Access](modding/misc/engine.md). The cod
chestplate on other players, wide and slim, and on the first person arm with its equip and swing.
- Blockbench's `mirror` isn't supported in entity models, so the giant chestplate's left sleeve has the right one's
texture unflipped.
- With entity animators (see [Animations](modding/entities/index.md#animations)), switching from one state's clips to
another's is instant, where Bedrock's controllers fade over their `blend_transition`.
- Without an animator, the engine still poses bones named like a humanoid's (`head`, `right_arm`, ...). That belongs in
the mods, and moves there once mods can share code with each other.
## Planned API
@@ -279,6 +283,21 @@ Worn items are drawn by `render_worn`, which puts an item's `worn` model on a pl
- **Glint and glowing overlays**, as `glint` and a full bright `overlay_texture` in `worn`, once the renderer has a
glint pass.
### Entity Animations
Clips and animators are built, see [Animations](modding/entities/index.md#animations). Still to come:
- **Events**, for one-off moments that aren't a state, like a roar. `MobRef.event(id)` sends an `entity_event` with a
mod's id, and the animator gets `on_event?(id, time)`. `EntityEvent` becomes the engine's three or an id, so
`PROTOCOL_VERSION` goes up. Nothing needs it yet.
- **Sounds**, like a Bedrock clip's `sound_effects`, once client scripts can play a sound: an animator plays one when a
state's seconds pass its time. The jester's crank, music, pop and scream are in lethal3's `jester.animation.json`.
- **An importer**, `deno task import animation`, for whole Bedrock packs. It copies each file, leaves out the channels
with Molang expressions, and lists them with a JS version for the animator: `math.cos` and `math.sin` take degrees,
`query.life_time` is `time / 20`, `query.anim_time` is the clip's seconds, `query.modified_distance_moved` is
`walk_position`, and `query.target_x_rotation` and `target_y_rotation` are `head_pitch` and `head_yaw`. It lists the
animation controllers and client entity files as left for an animator to do, with their states.
### HUD, Keybinds and Mod Channels
- `ctx.hud.register(id, { on_render(g, hud) })` draws every frame after the world, under open screens. Built, see
@@ -401,8 +420,6 @@ saved before any of this plays exactly the same.
waits a round trip. Components could get optional handlers that clients run to predict.
- **Engine access versions.** Tying engine access mods to one minor version is simple but strict.
- **Game API versions.** Only breaking with the game's major version needs deprecation warnings and a changelog.
- **Entities.** Mods can define simple animals, but there's no API for entity types with their own behavior, animations,
or natural spawning.
- **Hot reload.** Restarting the server and rejoining is the answer for now.
- **Biome rules or multi-noise?** Biome sources are ordered rules, which kept the old biomes exactly, but mods inserting
rules can step on each other in ways that are hard to see. Minecraft's multi-noise is easier to merge but would move
@@ -0,0 +1,302 @@
{
"format_version": "1.8.0",
"animations": {
"animation.CoilHead.idle": {
"loop": true,
"animation_length": 1,
"bones": {
"coilhead": {
"rotation": {
"vector": [0, 0, 0]
},
"position": {
"vector": [0, 0, 0]
},
"scale": {
"vector": [1, 1, 1]
}
}
}
},
"animation.CoilHead.stop": {
"animation_length": 0.75,
"bones": {
"spring": {
"rotation": {
"0.0": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [-22.5, 0, 0]
},
"0.5417": {
"vector": [12.5, 0, 0]
},
"0.75": {
"vector": [0, 0, 0]
}
},
"position": {
"0.0": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.5417": {
"vector": [0, 0, 0]
},
"0.75": {
"vector": [0, 0, 0]
}
},
"scale": {
"0.0": {
"vector": [1, 1, 1]
},
"0.25": {
"vector": [1, 1, 1]
},
"0.5417": {
"vector": [1, 1, 1]
},
"0.75": {
"vector": [1, 1, 1]
}
}
},
"head": {
"rotation": {
"0.0": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [-17.5, 0, 0]
},
"0.5417": {
"vector": [32.5, 0, 0]
},
"0.75": {
"vector": [0, 0, 0]
}
},
"position": {
"0.0": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.5417": {
"vector": [0, 0, 0]
},
"0.75": {
"vector": [0, 0, 0]
}
},
"scale": {
"0.0": {
"vector": [1, 1, 1]
},
"0.25": {
"vector": [1, 1, 1]
},
"0.5417": {
"vector": [1, 1, 1]
},
"0.75": {
"vector": [1, 1, 1]
}
}
}
}
},
"animation.CoilHead.walk": {
"loop": true,
"animation_length": 0.5,
"bones": {
"coilhead": {
"rotation": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [0, 0, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"position": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [0, -1.3, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [0, -1.3, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"scale": {
"0.0": {
"vector": [1, 1, 1]
},
"0.125": {
"vector": [1, 1, 1]
},
"0.25": {
"vector": [1, 1, 1]
},
"0.375": {
"vector": [1, 1, 1]
},
"0.5": {
"vector": [1, 1, 1]
}
}
},
"left_leg": {
"rotation": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [-20, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [25, 0, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"position": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [0, 0, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"scale": {
"0.0": {
"vector": [1, 1, 1]
},
"0.125": {
"vector": [1, 1, 1]
},
"0.25": {
"vector": [1, 1, 1]
},
"0.375": {
"vector": [1, 1, 1]
},
"0.5": {
"vector": [1, 1, 1]
}
}
},
"right_leg": {
"rotation": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [25, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [-12.5, 0, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"position": {
"0.0": {
"vector": [0, 0, 0]
},
"0.125": {
"vector": [0, 0, 0]
},
"0.25": {
"vector": [0, 0, 0]
},
"0.375": {
"vector": [0, 0, 0]
},
"0.5": {
"vector": [0, 0, 0]
}
},
"scale": {
"0.0": {
"vector": [1, 1, 1]
},
"0.125": {
"vector": [1, 1, 1]
},
"0.25": {
"vector": [1, 1, 1]
},
"0.375": {
"vector": [1, 1, 1]
},
"0.5": {
"vector": [1, 1, 1]
}
}
},
"spring": {
"rotation": {
"vector": [-22.5, 0, 0]
},
"position": {
"vector": [0, 0, 0]
},
"scale": {
"vector": [1, 1, 1]
}
},
"head": {
"rotation": {
"vector": [-17.5, 0, 0]
},
"position": {
"vector": [0, 0, 0]
},
"scale": {
"vector": [1, 1, 1]
}
}
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -87,7 +87,11 @@
},
"interactive": true,
"components": {
"dangerous_business:door": { "pairs_with": "dangerous_business:door" }
"dangerous_business:door": {
"pairs_with": "dangerous_business:door",
"open_sound": "dangerous_business:door/open",
"close_sound": "dangerous_business:door/close"
}
}
}
}
@@ -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,
@@ -0,0 +1,18 @@
{
"format_version": 1,
"entity": {
"id": "dangerous_business:jester",
"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,
"movement_speed": 0.23,
"jumps": false,
"max_fall": 0,
"attack_damage": 99999,
"physical_shielding": 3
}
}
+126 -60
View File
@@ -20,12 +20,24 @@
"parent": "coilhead",
"pivot": [0, 0, 0],
"cubes": [
{"origin": [-4, 19, 1.3], "size": [8, 5, 6], "uv": [0, 25]},
{"origin": [-4.5, 24, 0.8], "size": [9, 3, 7], "uv": [0, 15]},
{"origin": [-5.5, 27, 0.3], "size": [11, 7, 8], "uv": [0, 0]},
{"origin": [-20.5, 24, 2.3], "size": [8, 3, 3], "pivot": [0, 0, 0], "rotation": [0, 0, 45], "uv": [35, 12]},
{"origin": [11.5, 24, 2.3], "size": [9, 3, 3], "pivot": [0, 0, 0], "rotation": [0, 0, -45], "uv": [30, 0]},
{"origin": [-4.5, 33.3, 1.3], "size": [9, 2, 6], "uv": [26, 19]}
{ "origin": [-4, 19, 1.3], "size": [8, 5, 6], "uv": [0, 25] },
{ "origin": [-4.5, 24, 0.8], "size": [9, 3, 7], "uv": [0, 15] },
{ "origin": [-5.5, 27, 0.3], "size": [11, 7, 8], "uv": [0, 0] },
{
"origin": [-20.5, 24, 2.3],
"size": [8, 3, 3],
"pivot": [0, 0, 0],
"rotation": [0, 0, 45],
"uv": [35, 12]
},
{
"origin": [11.5, 24, 2.3],
"size": [9, 3, 3],
"pivot": [0, 0, 0],
"rotation": [0, 0, -45],
"uv": [30, 0]
},
{ "origin": [-4.5, 33.3, 1.3], "size": [9, 2, 6], "uv": [26, 19] }
]
},
{
@@ -34,11 +46,38 @@
"pivot": [3, 20, 4.7],
"rotation": [7.5, 0, 0],
"cubes": [
{"origin": [1.5, 0, -2], "size": [3, 2, 3], "uv": [33, 55]},
{"origin": [1.5, 0, 0.5], "size": [3, 2, 3], "inflate": -0.1, "pivot": [-2.5, 0, 0], "rotation": [17.5, 0, 0], "uv": [21, 54]},
{"origin": [1.5, 0.9, 1.5], "size": [3, 7, 3], "pivot": [-2.5, -0.2, 0], "rotation": [5, 0, 0], "uv": [44, 39]},
{"origin": [1.5, 7.8, 0.7], "size": [3, 5, 3], "inflate": 0.2, "pivot": [-2.5, -0.2, 0], "rotation": [0, 0, 0], "uv": [12, 48]},
{"origin": [1, 12.5, -3.7], "size": [4, 8, 4], "inflate": 0.2, "pivot": [-2.5, -0.2, 0], "rotation": [-17.5, 0, 0], "uv": [16, 36]}
{ "origin": [1.5, 0, -2], "size": [3, 2, 3], "uv": [33, 55] },
{
"origin": [1.5, 0, 0.5],
"size": [3, 2, 3],
"inflate": -0.1,
"pivot": [-2.5, 0, 0],
"rotation": [17.5, 0, 0],
"uv": [21, 54]
},
{
"origin": [1.5, 0.9, 1.5],
"size": [3, 7, 3],
"pivot": [-2.5, -0.2, 0],
"rotation": [5, 0, 0],
"uv": [44, 39]
},
{
"origin": [1.5, 7.8, 0.7],
"size": [3, 5, 3],
"inflate": 0.2,
"pivot": [-2.5, -0.2, 0],
"rotation": [0, 0, 0],
"uv": [12, 48]
},
{
"origin": [1, 12.5, -3.7],
"size": [4, 8, 4],
"inflate": 0.2,
"pivot": [-2.5, -0.2, 0],
"rotation": [-17.5, 0, 0],
"uv": [16, 36]
}
]
},
{
@@ -47,8 +86,8 @@
"pivot": [3.8, 6, 1.7],
"rotation": [64.46949, 11.31255, -5.35254],
"cubes": [
{"origin": [2.8, 6, 0.7], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [2.3, 8, 0.2], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [2.8, 6, 0.7], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [2.3, 8, 0.2], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -57,8 +96,8 @@
"pivot": [4.5, 14.7, 1.9],
"rotation": [74.30716, -16.88547, 4.6653],
"cubes": [
{"origin": [3.5, 14.7, 0.9], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [3, 16.7, 0.4], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [3.5, 14.7, 0.9], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [3, 16.7, 0.4], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -67,11 +106,38 @@
"pivot": [-3, 20, 4.7],
"rotation": [7.5, 0, 0],
"cubes": [
{"origin": [-4.5, 0, -2], "size": [3, 2, 3], "uv": [53, 24]},
{"origin": [-4.5, 0, 0.5], "size": [3, 2, 3], "inflate": -0.1, "pivot": [2.5, 0, 0], "rotation": [17.5, 0, 0], "uv": [50, 7]},
{"origin": [-4.5, 0.9, 1.5], "size": [3, 7, 3], "pivot": [2.5, -0.2, 0], "rotation": [5, 0, 0], "uv": [32, 39]},
{"origin": [-4.5, 7.8, 0.7], "size": [3, 5, 3], "inflate": 0.2, "pivot": [2.5, -0.2, 0], "rotation": [0, 0, 0], "uv": [0, 48]},
{"origin": [-5, 12.5, -3.7], "size": [4, 8, 4], "inflate": 0.2, "pivot": [2.5, -0.2, 0], "rotation": [-17.5, 0, 0], "uv": [0, 36]}
{ "origin": [-4.5, 0, -2], "size": [3, 2, 3], "uv": [53, 24] },
{
"origin": [-4.5, 0, 0.5],
"size": [3, 2, 3],
"inflate": -0.1,
"pivot": [2.5, 0, 0],
"rotation": [17.5, 0, 0],
"uv": [50, 7]
},
{
"origin": [-4.5, 0.9, 1.5],
"size": [3, 7, 3],
"pivot": [2.5, -0.2, 0],
"rotation": [5, 0, 0],
"uv": [32, 39]
},
{
"origin": [-4.5, 7.8, 0.7],
"size": [3, 5, 3],
"inflate": 0.2,
"pivot": [2.5, -0.2, 0],
"rotation": [0, 0, 0],
"uv": [0, 48]
},
{
"origin": [-5, 12.5, -3.7],
"size": [4, 8, 4],
"inflate": 0.2,
"pivot": [2.5, -0.2, 0],
"rotation": [-17.5, 0, 0],
"uv": [0, 36]
}
]
},
{
@@ -80,8 +146,8 @@
"pivot": [-3.2, 3.2, 1.8],
"rotation": [75.65143, 69.40933, -13.46639],
"cubes": [
{"origin": [-4.2, 3.2, 0.8], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-4.7, 5.2, 0.3], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-4.2, 3.2, 0.8], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-4.7, 5.2, 0.3], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -90,8 +156,8 @@
"pivot": [-1.8, 15, 1.5],
"rotation": [63.60782, 18.05776, -8.74472],
"cubes": [
{"origin": [-2.8, 15, 0.5], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-3.3, 17, 0], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-2.8, 15, 0.5], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-3.3, 17, 0], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -100,8 +166,8 @@
"pivot": [-4.1, 19.5, 3.7],
"rotation": [29.03199, 61.09544, -57.62441],
"cubes": [
{"origin": [-5.1, 19.5, 2.7], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-5.6, 21.5, 2.2], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-5.1, 19.5, 2.7], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-5.6, 21.5, 2.2], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -109,26 +175,26 @@
"parent": "body",
"pivot": [0, 35.3, 4.5],
"cubes": [
{"origin": [1.5, 35.3, 1.8], "size": [1, 1, 5], "uv": [52, 33]},
{"origin": [-2.4, 36.2, 1.6], "size": [1, 1, 5], "uv": [51, 44]},
{"origin": [-2.7, 35.8, 5.7], "size": [5, 1, 1], "uv": [56, 4]},
{"origin": [-2.7, 36.6, 1.7], "size": [5, 1, 1], "uv": [56, 2]},
{"origin": [-2.7, 38.6, 1.7], "size": [5, 1, 1], "uv": [0, 56]},
{"origin": [1.5, 37.3, 1.8], "size": [1, 1, 5], "uv": [50, 18]},
{"origin": [-2.7, 37.8, 5.7], "size": [5, 1, 1], "uv": [56, 0]},
{"origin": [-2.4, 38.2, 1.6], "size": [1, 1, 5], "uv": [50, 50]},
{"origin": [-2.7, 40.6, 1.7], "size": [5, 1, 1], "uv": [53, 39]},
{"origin": [1.5, 39.3, 1.8], "size": [1, 1, 5], "uv": [31, 49]},
{"origin": [-2.7, 39.8, 5.7], "size": [5, 1, 1], "uv": [54, 12]},
{"origin": [-2.4, 40.2, 1.6], "size": [1, 1, 5], "uv": [43, 49]},
{"origin": [-2.7, 42.6, 1.7], "size": [5, 1, 1], "uv": [30, 6]},
{"origin": [1.5, 41.3, 1.8], "size": [1, 1, 5], "uv": [24, 48]},
{"origin": [-2.7, 41.8, 5.7], "size": [5, 1, 1], "uv": [53, 29]},
{"origin": [-2.4, 42.2, 1.6], "size": [1, 1, 5], "uv": [49, 1]},
{"origin": [-2.7, 44.6, 1.7], "size": [5, 1, 1], "uv": [22, 27]},
{"origin": [1.5, 43.3, 1.8], "size": [1, 1, 5], "uv": [38, 6]},
{"origin": [-2.7, 43.8, 5.7], "size": [5, 1, 1], "uv": [22, 29]},
{"origin": [-2.4, 44.2, 1.6], "size": [1, 1, 5], "uv": [46, 27]}
{ "origin": [1.5, 35.3, 1.8], "size": [1, 1, 5], "uv": [52, 33] },
{ "origin": [-2.4, 36.2, 1.6], "size": [1, 1, 5], "uv": [51, 44] },
{ "origin": [-2.7, 35.8, 5.7], "size": [5, 1, 1], "uv": [56, 4] },
{ "origin": [-2.7, 36.6, 1.7], "size": [5, 1, 1], "uv": [56, 2] },
{ "origin": [-2.7, 38.6, 1.7], "size": [5, 1, 1], "uv": [0, 56] },
{ "origin": [1.5, 37.3, 1.8], "size": [1, 1, 5], "uv": [50, 18] },
{ "origin": [-2.7, 37.8, 5.7], "size": [5, 1, 1], "uv": [56, 0] },
{ "origin": [-2.4, 38.2, 1.6], "size": [1, 1, 5], "uv": [50, 50] },
{ "origin": [-2.7, 40.6, 1.7], "size": [5, 1, 1], "uv": [53, 39] },
{ "origin": [1.5, 39.3, 1.8], "size": [1, 1, 5], "uv": [31, 49] },
{ "origin": [-2.7, 39.8, 5.7], "size": [5, 1, 1], "uv": [54, 12] },
{ "origin": [-2.4, 40.2, 1.6], "size": [1, 1, 5], "uv": [43, 49] },
{ "origin": [-2.7, 42.6, 1.7], "size": [5, 1, 1], "uv": [30, 6] },
{ "origin": [1.5, 41.3, 1.8], "size": [1, 1, 5], "uv": [24, 48] },
{ "origin": [-2.7, 41.8, 5.7], "size": [5, 1, 1], "uv": [53, 29] },
{ "origin": [-2.4, 42.2, 1.6], "size": [1, 1, 5], "uv": [49, 1] },
{ "origin": [-2.7, 44.6, 1.7], "size": [5, 1, 1], "uv": [22, 27] },
{ "origin": [1.5, 43.3, 1.8], "size": [1, 1, 5], "uv": [38, 6] },
{ "origin": [-2.7, 43.8, 5.7], "size": [5, 1, 1], "uv": [22, 29] },
{ "origin": [-2.4, 44.2, 1.6], "size": [1, 1, 5], "uv": [46, 27] }
]
},
{
@@ -136,7 +202,7 @@
"parent": "spring",
"pivot": [0, 45.5, 2.2],
"cubes": [
{"origin": [-3.2, 45.4, 1.3], "size": [6, 6, 6], "uv": [28, 27]}
{ "origin": [-3.2, 45.4, 1.3], "size": [6, 6, 6], "uv": [28, 27] }
]
},
{
@@ -145,8 +211,8 @@
"pivot": [-0.6, 22.4, 2.2],
"rotation": [82.32005, 12.39135, -1.6575],
"cubes": [
{"origin": [-1.6, 22.4, 1.2], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-2.1, 24.4, 0.7], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-1.6, 22.4, 1.2], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-2.1, 24.4, 0.7], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -155,8 +221,8 @@
"pivot": [3.9, 31.6, 1.6],
"rotation": [97.7614, -14.8687, -2.00307],
"cubes": [
{"origin": [2.9, 31.6, 0.6], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [2.4, 33.6, 0.1], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [2.9, 31.6, 0.6], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [2.4, 33.6, 0.1], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -165,8 +231,8 @@
"pivot": [0.9, 31.6, 7.4],
"rotation": [-97.7614, 14.8687, -2.00307],
"cubes": [
{"origin": [-0.1, 31.6, 7.4], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-0.6, 33.6, 6.9], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-0.1, 31.6, 7.4], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-0.6, 33.6, 6.9], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -175,8 +241,8 @@
"pivot": [-1.5, 22.5, 6.2],
"rotation": [-97.7614, 14.8687, -2.00307],
"cubes": [
{"origin": [-2.5, 22.5, 6.2], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-3, 24.5, 5.7], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-2.5, 22.5, 6.2], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-3, 24.5, 5.7], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -185,8 +251,8 @@
"pivot": [-3.4, 33.5, 1.2],
"rotation": [98.44236, 27.24513, 3.88714],
"cubes": [
{"origin": [-4.4, 33.5, 0.2], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-4.9, 35.5, -0.3], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-4.4, 33.5, 0.2], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-4.9, 35.5, -0.3], "size": [2, 1, 2], "uv": [0, 0] }
]
},
{
@@ -195,11 +261,11 @@
"pivot": [-4, 33.5, 6.1],
"rotation": [10, 0, -30],
"cubes": [
{"origin": [-5, 33.5, 5.1], "size": [1, 2, 1], "uv": [0, 3]},
{"origin": [-5.5, 35.5, 4.6], "size": [2, 1, 2], "uv": [0, 0]}
{ "origin": [-5, 33.5, 5.1], "size": [1, 2, 1], "uv": [0, 3] },
{ "origin": [-5.5, 35.5, 4.6], "size": [2, 1, 2], "uv": [0, 0] }
]
}
]
}
]
}
}
@@ -0,0 +1,317 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.jester",
"texture_width": 128,
"texture_height": 128,
"visible_bounds_width": 3,
"visible_bounds_height": 3.5,
"visible_bounds_offset": [0, 1.25, 0]
},
"bones": [
{
"name": "root",
"pivot": [0, 0, 0]
},
{
"name": "waist",
"parent": "root",
"pivot": [0, 12, 0]
},
{
"name": "box",
"parent": "waist",
"pivot": [0, 12, 0],
"cubes": [
{
"origin": [-8, 12, -8],
"size": [16, 16, 16],
"uv": {
"north": { "uv": [22, 60], "uv_size": [16, 16] },
"east": { "uv": [0, 64], "uv_size": [16, 16] },
"south": { "uv": [68, 0], "uv_size": [16, 16] },
"west": { "uv": [68, 16], "uv_size": [16, 16] },
"up": { "uv": [68, 32], "uv_size": [16, 16] },
"down": { "uv": [68, 64], "uv_size": [16, -16] }
}
}
]
},
{
"name": "box_lid",
"parent": "box",
"pivot": [0, 28, 8],
"cubes": [
{
"origin": [-8, 28, -8],
"size": [16, 1, 16],
"uv": {
"north": { "uv": [98, 65], "uv_size": [16, 1] },
"east": { "uv": [61, 103], "uv_size": [16, 1] },
"south": { "uv": [103, 102], "uv_size": [16, 1] },
"west": { "uv": [103, 103], "uv_size": [16, 1] },
"up": { "uv": [68, 64], "uv_size": [16, 16] },
"down": { "uv": [16, 92], "uv_size": [16, -16] }
}
}
]
},
{
"name": "tendrils",
"parent": "box",
"pivot": [-0.3709, 28.03888, 1.72961],
"cubes": [
{
"origin": [-4.75, 27, -2],
"size": [8, 28, 7],
"pivot": [-0.75, 27.5, 0.5],
"rotation": [11.5, 0, 0],
"uv": {
"north": { "uv": [84, 66], "uv_size": [8, 28] },
"east": { "uv": [24, 92], "uv_size": [7, 28] },
"south": { "uv": [16, 92], "uv_size": [8, 28] },
"west": { "uv": [84, 94], "uv_size": [7, 28] },
"up": { "uv": [32, 76], "uv_size": [8, 7] },
"down": { "uv": [98, 65], "uv_size": [8, -7] }
}
},
{
"origin": [-6.025, 25.63246, -6.50605],
"size": [12, 28, 0],
"pivot": [-0.75, 39.63246, -7.58105],
"rotation": [12.91186, -8.38903, -9.73581],
"uv": {
"north": { "uv": [44, 0], "uv_size": [12, 28] },
"east": { "uv": [0, 0], "uv_size": [0, 28] },
"south": { "uv": [44, 28], "uv_size": [12, 28] },
"west": { "uv": [0, 0], "uv_size": [0, 28] },
"up": { "uv": [0, 0], "uv_size": [12, 0] },
"down": { "uv": [0, 0], "uv_size": [12, 0] }
}
},
{
"origin": [-6.75, 25.33246, -8.85605],
"size": [12, 28, 0],
"pivot": [-0.75, 39.63246, -7.58105],
"rotation": [169.98699, 25.84107, -179.13668],
"uv": {
"north": { "uv": [56, 0], "uv_size": [12, 28] },
"east": { "uv": [0, 0], "uv_size": [0, 28] },
"south": { "uv": [56, 28], "uv_size": [12, 28] },
"west": { "uv": [0, 0], "uv_size": [0, 28] },
"up": { "uv": [0, 0], "uv_size": [12, 0] },
"down": { "uv": [0, 0], "uv_size": [12, 0] }
}
},
{
"origin": [-5.475, 25.63246, -6.50605],
"size": [12, 28, 0],
"pivot": [-0.75, 39.63246, -7.58105],
"rotation": [15.7096, 19.35594, 8.37709],
"uv": {
"north": { "uv": [44, 56], "uv_size": [12, 28] },
"east": { "uv": [0, 0], "uv_size": [0, 28] },
"south": { "uv": [56, 56], "uv_size": [12, 28] },
"west": { "uv": [0, 0], "uv_size": [0, 28] },
"up": { "uv": [0, 0], "uv_size": [12, 0] },
"down": { "uv": [0, 0], "uv_size": [12, 0] }
}
}
]
},
{
"name": "skull",
"parent": "tendrils",
"pivot": [-0.1784, 51.63803, -2.36963],
"cubes": [
{
"origin": [-11, 44.38084, -20.73926],
"size": [22, 20, 22],
"uv": {
"north": { "uv": [22, 0], "uv_size": [22, 20] },
"east": { "uv": [22, 20], "uv_size": [22, 20] },
"south": { "uv": [22, 40], "uv_size": [22, 20] },
"west": { "uv": [0, 44], "uv_size": [22, 20] },
"up": { "uv": [0, 0], "uv_size": [22, 22] },
"down": { "uv": [0, 44], "uv_size": [22, -22] }
}
},
{
"origin": [-9.375, 47, -19],
"size": [16, 16, 16],
"pivot": [-1.375, 50, -11],
"rotation": [0, 0, 11.75],
"uv": {
"north": { "uv": [0, 80], "uv_size": [16, 16] },
"east": { "uv": [68, 80], "uv_size": [16, 16] },
"south": { "uv": [84, 0], "uv_size": [16, 16] },
"west": { "uv": [84, 16], "uv_size": [16, 16] },
"up": { "uv": [32, 84], "uv_size": [16, 16] },
"down": { "uv": [84, 48], "uv_size": [16, -16] }
}
}
]
},
{
"name": "jaw",
"parent": "skull",
"pivot": [0, 44.18195, -1.85535],
"cubes": [
{
"origin": [-7, 39.68195, -19.85535],
"size": [14, 5, 18],
"uv": {
"north": { "uv": [0, 96], "uv_size": [14, 5] },
"east": { "uv": [62, 96], "uv_size": [18, 5] },
"south": { "uv": [98, 53], "uv_size": [14, 5] },
"west": { "uv": [98, 48], "uv_size": [18, 5] },
"up": { "uv": [48, 84], "uv_size": [14, 18] },
"down": { "uv": [84, 66], "uv_size": [14, -18] }
}
},
{
"origin": [-6.5, 44.68195, -19.35535],
"size": [13, 2, 17],
"uv": {
"north": { "uv": [0, 101], "uv_size": [13, 2] },
"east": { "uv": [91, 100], "uv_size": [17, 2] },
"south": { "uv": [41, 102], "uv_size": [13, 2] },
"west": { "uv": [62, 101], "uv_size": [17, 2] },
"up": { "uv": [92, 66], "uv_size": [13, 17] },
"down": { "uv": [92, 100], "uv_size": [13, -17] }
}
}
]
},
{
"name": "left_arm",
"parent": "box",
"pivot": [8, 15, 0],
"cubes": [
{
"origin": [8, 13, -2],
"size": [10, 4, 4],
"uv": {
"north": { "uv": [31, 100], "uv_size": [10, 4] },
"east": { "uv": [95, 102], "uv_size": [4, 4] },
"south": { "uv": [100, 36], "uv_size": [10, 4] },
"west": { "uv": [99, 102], "uv_size": [4, 4] },
"up": { "uv": [100, 40], "uv_size": [10, 4] },
"down": { "uv": [100, 48], "uv_size": [10, -4] }
}
}
]
},
{
"name": "left_forearm",
"parent": "left_arm",
"pivot": [18, 15, 0],
"cubes": [
{
"origin": [18, 13, -2],
"size": [10, 4, 4],
"uv": {
"north": { "uv": [31, 100], "uv_size": [10, 4] },
"east": { "uv": [95, 102], "uv_size": [4, 4] },
"south": { "uv": [100, 36], "uv_size": [10, 4] },
"west": { "uv": [99, 102], "uv_size": [4, 4] },
"up": { "uv": [100, 40], "uv_size": [10, 4] },
"down": { "uv": [100, 48], "uv_size": [10, -4] }
}
}
]
},
{
"name": "crank",
"parent": "box",
"pivot": [8.5, 20, 0],
"cubes": [
{
"origin": [8, 19, -1],
"size": [3, 2, 2],
"uv": {
"north": { "uv": [41, 100], "uv_size": [3, 2] },
"east": { "uv": [42, 60], "uv_size": [2, 2] },
"south": { "uv": [44, 100], "uv_size": [3, 2] },
"west": { "uv": [42, 62], "uv_size": [2, 2] },
"up": { "uv": [8, 103], "uv_size": [3, 2] },
"down": { "uv": [77, 105], "uv_size": [3, -2] }
}
}
]
},
{
"name": "handle",
"parent": "crank",
"pivot": [11, 20, -0.125],
"cubes": [
{
"origin": [11, 19.5, -5],
"size": [3, 1, 6],
"uv": {
"north": { "uv": [104, 9], "uv_size": [3, 1] },
"east": { "uv": [32, 83], "uv_size": [6, 1] },
"south": { "uv": [104, 10], "uv_size": [3, 1] },
"west": { "uv": [104, 0], "uv_size": [6, 1] },
"up": { "uv": [13, 101], "uv_size": [3, 6] },
"down": { "uv": [54, 108], "uv_size": [3, -6] }
}
},
{
"origin": [14, 19, -5.75],
"size": [3, 2, 2],
"uv": {
"north": { "uv": [104, 1], "uv_size": [3, 2] },
"east": { "uv": [20, 64], "uv_size": [2, 2] },
"south": { "uv": [104, 3], "uv_size": [3, 2] },
"west": { "uv": [42, 64], "uv_size": [2, 2] },
"up": { "uv": [104, 5], "uv_size": [3, 2] },
"down": { "uv": [104, 9], "uv_size": [3, -2] }
}
}
]
},
{
"name": "right_leg",
"parent": "root",
"pivot": [-3, 12, 0],
"cubes": [
{
"origin": [-5, 0, -2],
"size": [4, 12, 4],
"uv": {
"north": { "uv": [80, 96], "uv_size": [4, 12] },
"east": { "uv": [100, 0], "uv_size": [4, 12] },
"south": { "uv": [100, 12], "uv_size": [4, 12] },
"west": { "uv": [100, 24], "uv_size": [4, 12] },
"up": { "uv": [0, 103], "uv_size": [4, 4] },
"down": { "uv": [4, 107], "uv_size": [4, -4] }
}
}
]
},
{
"name": "left_leg",
"parent": "root",
"pivot": [2, 12, 0],
"cubes": [
{
"origin": [1, 0, -2],
"size": [4, 12, 4],
"uv": {
"north": { "uv": [38, 60], "uv_size": [4, 12] },
"east": { "uv": [16, 64], "uv_size": [4, 12] },
"south": { "uv": [40, 72], "uv_size": [4, 12] },
"west": { "uv": [62, 84], "uv_size": [4, 12] },
"up": { "uv": [57, 102], "uv_size": [4, 4] },
"down": { "uv": [91, 106], "uv_size": [4, -4] }
}
}
]
}
]
}
]
}
+35 -2
View File
@@ -1,5 +1,6 @@
// the coilhead: it goes after players like any monster, but can't move while one of them is looking at it
import type { MobRef, Player, Position, ScriptGoal, ServerContext } from "cubi/server";
import { AnimationState, type ClientContext } from "cubi/client";
import { DOOR, type DoorParams, set_door_open } from "./shared.ts";
// how far away a player still freezes it
@@ -21,11 +22,18 @@ export function register_coilhead(ctx: ServerContext) {
const nearest_player = builtin.nearest_attackable_player();
ctx.entities.register_behavior("dangerous_business:coilhead", (mob, goals) => {
// takes every control from the goals after it, so it doesn't walk, turn, jump or hit while seen
// takes every control from the goals after it, so it doesn't walk, turn, jump or hit while seen. clients see it
// frozen, for its animator
goals.add(0, {
flags: ["move", "look", "jump"],
can_use: () => ctx.players.all().some((player) => sees(ctx, player, mob)),
start: () => mob.stop(),
start: () => {
mob.stop();
mob.set_client_data("frozen", true);
mob.play_sound("dangerous_business:coilhead/stop");
mob.play_sound("dangerous_business:coilhead/seen");
},
stop: () => mob.set_client_data("frozen", undefined),
});
goals.add(1, chase);
goals.add(2, stroll);
@@ -36,6 +44,31 @@ export function register_coilhead(ctx: ServerContext) {
});
}
// bobs as it walks and stands still otherwise. when it freezes its head springs back and forth once, and it looks
// where it's looking
export function register_coilhead_animator(ctx: ClientContext) {
const idle = ctx.render.clip("dangerous_business:coilhead/idle");
const walk = ctx.render.clip("dangerous_business:coilhead/walk");
const stop = ctx.render.clip("dangerous_business:coilhead/stop");
ctx.render.register_entity_animator("dangerous_business:coilhead", (coilhead) => {
const frozen = new AnimationState();
return {
on_data(field, time) {
if (field === "frozen") frozen.animate_when(coilhead.get_client_data("frozen") === true, time);
},
pose(pose, time) {
if (frozen.started && !frozen.finished(stop, time)) {
pose.play_state(stop, frozen, time);
} else {
pose.play(idle, time / 20);
pose.play_walk(walk, coilhead, time);
}
pose.look("head");
},
};
});
}
// opens a door on the mob's way after it's stood at it for ticks. without flags, so the goal going after its target
// keeps its way and the mob stays at the door. the door's in the mobs_path_through tag, so its way goes through it
export function opens_doors(ctx: ServerContext, mob: MobRef, ticks: number): ScriptGoal {
@@ -4,6 +4,8 @@ import type { Position, Schematic } from "cubi/server";
// placed, so a plan that comes out too small can be tried again without touching the world
export const DOORWAY = "dangerous_business:doorway";
// where the surface is placed, high above the interior. anyone higher than it is outside the facility
export const SURFACE_Y = 150;
export const VENT_SPOT = "dangerous_business:vent_spot";
// a marker block in a tile, a doorway or a vent spot, with its facing state: 0 north, 1 east, 2 south, 3 west. in a
@@ -40,6 +42,10 @@ export interface TileType extends TileRules {
vent_spots: Marker[];
}
export function in_facility(position: Position) {
return position.y <= SURFACE_Y;
}
export interface PlacedTile {
tile: string;
// where the schematic's lowest corner goes, before it's turned around it
+270
View File
@@ -0,0 +1,270 @@
// the jester: a box on legs that wanders until it sees a player. it follows them for a while, stops to wind its crank,
// and pops open, then runs down every player in the facility, faster and faster, until there's nobody left inside
import type { MobRef, Player, ScriptGoal, ServerContext } from "cubi/server";
import {
type AnimatedEntity,
AnimationState,
type ClientContext,
type Clip,
type EntityPose,
type PlayingSound,
} from "cubi/client";
import { opens_doors } from "./coilhead.ts";
import { in_facility } from "./interior.ts";
const JESTER = "dangerous_business:jester";
// its "state" client data, what its animator plays
const ROAMING = 1;
const CRANKING = 2;
const AGGRO = 3;
// how far away it notices a player it can see
const SEE_RANGE = 24;
// how close it comes to the player it's following
const FOLLOW_DISTANCE = 3;
// seconds after it first notices someone before it starts cranking, shorter with more players around
const COUNTDOWN_ALONE = [25, 42];
const COUNTDOWN_TOGETHER = [13, 21];
const CRANK_TICKS = 40 * 20;
// how long it stands after popping before it goes
const POP_TICKS = 2 * 20;
// it chases a fifth faster than it walks, and another fifth every SPEED_UP_TICKS, up to twice as fast
const SPEED_STEP = 0.2;
const SPEED_UP_TICKS = 120;
const MAX_SPEED_STEPS = 8;
const CHASE_SPEED = "dangerous_business:jester_chase";
// it only waits a moment at a closed door
const OPEN_DOOR_TICKS = 20;
// the crank turns once a second while it cranks, clicking this many ticks into each, where its crank clip has it
const CRANK_CLICK_TICK = 12;
export function register_jester(ctx: ServerContext) {
const builtin = ctx.entities.goals;
const chase = builtin.melee_attack();
const stroll = builtin.random_stroll();
const look_around = builtin.random_look_around();
ctx.entities.register_behavior(JESTER, (mob, goals) => {
let state = mob.get_client_data<number>("state") ?? ROAMING;
// ticks in its state, going on from where one that was saved had got to
let ticks = Math.max(0, ctx.world.time - (mob.get_client_data<number>("since") ?? ctx.world.time));
// ticks left until it cranks, from when it first noticed someone
let countdown: number | undefined;
let followed: Player | undefined;
const set_state = (next: number) => {
state = next;
ticks = 0;
// when it started, by the world's time, so a client that comes upon it partway knows how far it's got
mob.set_client_data("since", ctx.world.time);
mob.set_client_data("state", next);
if (next === AGGRO) mob.play_sound("dangerous_business:jester/pop");
};
// what it's doing, which the goals after it follow
goals.add(0, {
can_use: () => true,
tick: () => {
ticks++;
if (state === ROAMING) {
if (followed && (followed.health <= 0 || !in_facility(followed.position))) followed = undefined;
followed ??= ctx.players.all().find((player) => can_see(ctx, mob, player));
if (followed && countdown === undefined) {
const [low, high] = ctx.players.all().length > 1 ? COUNTDOWN_TOGETHER : COUNTDOWN_ALONE;
countdown = Math.round((low + (high - low) * mob.random()) * 20);
}
if (countdown !== undefined && --countdown <= 0) {
countdown = undefined;
followed = undefined;
set_state(CRANKING);
}
} else if (state === CRANKING) {
if (ticks % 20 === CRANK_CLICK_TICK) mob.play_sound("dangerous_business:jester/turn_crank");
if (ticks >= CRANK_TICKS) set_state(AGGRO);
} else {
const target = nearest_player(ctx, mob);
if (!target) {
mob.target = undefined;
mob.remove_modifier("cubi:movement_speed", CHASE_SPEED);
set_state(ROAMING);
return;
}
if (ticks < POP_TICKS) return;
mob.target = target;
const steps = Math.min(MAX_SPEED_STEPS, 1 + Math.floor((ticks - POP_TICKS) / SPEED_UP_TICKS));
mob.add_modifier("cubi:movement_speed", {
id: CHASE_SPEED,
amount: steps * SPEED_STEP,
operation: "add_multiplied_total",
});
}
},
});
// stands still while it cranks and while it pops
goals.add(1, {
flags: ["move", "look", "jump"],
can_use: () => state === CRANKING || (state === AGGRO && ticks < POP_TICKS),
start: () => mob.stop(),
});
goals.add(2, chase);
goals.add(3, follow(mob, () => state === ROAMING ? followed : undefined));
goals.add(4, stroll);
goals.add(5, look_around);
goals.add(6, opens_doors(ctx, mob, OPEN_DOOR_TICKS));
});
}
// keeps close to who(), looking at them, and stands by them once it's there instead of wandering off. it goes a new
// way only once they've moved to another block
function follow(mob: MobRef, who: () => Player | undefined): ScriptGoal {
let block = "";
return {
flags: ["move", "look"],
can_use: () => who() !== undefined,
start: () => block = "",
stop: () => mob.stop(),
tick: () => {
// the goal deciding what the jester does can let them go this tick
const player = who();
if (!player) return;
const { x, y, z } = player.position;
mob.look_at(x, y + 1.5, z);
const at = mob.position;
if (Math.hypot(x - at.x, y - at.y, z - at.z) <= FOLLOW_DISTANCE) {
if (block !== "") mob.stop();
block = "";
return;
}
const now = `${Math.floor(x)},${Math.floor(y)},${Math.floor(z)}`;
if (now === block) return;
block = now;
mob.move_to(x, y, z);
},
};
}
// whether it can see the player's eyes from its own, close enough to notice them, in the facility
function can_see(ctx: ServerContext, mob: MobRef, player: Player) {
if (player.health <= 0 || !in_facility(player.position)) return false;
const from = mob.eye_position;
const to = player.eye_position;
if (Math.hypot(to.x - from.x, to.y - from.y, to.z - from.z) > SEE_RANGE) return false;
return ctx.world.raycast(from, to) === undefined;
}
// the closest living player in the facility, however far
function nearest_player(ctx: ServerContext, mob: MobRef) {
const at = mob.position;
const distance = ({ position: { x, y, z } }: Player) => Math.hypot(x - at.x, y - at.y, z - at.z);
const inside = ctx.players.all().filter((player) => player.health > 0 && in_facility(player.position));
return inside.sort((a, b) => distance(a) - distance(b))[0] as Player | undefined;
}
// what bedrock's animation controller did: idle and walk while it roams, crank, then pop, then its chase. what its
// clips did with expressions is here as code. its music box plays while it cranks, and it screams while it's popped.
// a player who comes upon it partway sees and hears it from as far as it's got, by when its state started
export function register_jester_animator(ctx: ClientContext) {
const clip = (name: string) => ctx.render.clip(`dangerous_business:jester/${name}`);
const idle = clip("idle");
const walk = clip("walk");
const crank = clip("crank");
const pop = clip("pop");
const aggro_idle = clip("aggro_idle");
const aggro_walk = clip("aggro_walk");
const attack = clip("attack");
ctx.render.register_entity_animator(JESTER, (jester) => {
const cranking = new AnimationState();
const popped = new AnimationState();
const attacking = new AnimationState();
let theme: PlayingSound | undefined;
let scream: PlayingSound | undefined;
return {
on_data(field, time) {
if (field !== "state" && field !== "since") return;
const state = jester.get_client_data<number>("state");
const since = jester.get_client_data<number>("since");
// ticks it's been in its state
const ticks = since === undefined ? 0 : Math.max(0, ctx.world.time - since);
cranking.animate_when(state === CRANKING, time - ticks);
popped.animate_when(state === AGGRO, time - ticks);
// loops, so one played out of range comes in where it would be when the player comes near. the music box
// is longer than the cranking, so it never goes around
const play = (sound: string) =>
ctx.sounds.play(sound, { follow: jester.id, loop: true, offset: ticks / 20 });
theme = sound_while(state === CRANKING, theme, () => play("dangerous_business:jester/theme"));
scream = sound_while(state === AGGRO, scream, () => play("dangerous_business:jester/scream"));
},
pose(pose, time) {
if (cranking.started) {
pose.play_state(crank, cranking, time);
} else if (popped.started && !popped.finished(pop, time)) {
pose.play_state(pop, popped, time);
} else if (popped.started) {
const swinging = jester.attack_progress(time) > 0;
if (swinging && (!attacking.started || attacking.finished(attack, time))) attacking.start(time);
if (attacking.started && !attacking.finished(attack, time)) {
pose.play_state(attack, attacking, time);
} else {
// its walk goes half as fast as when it roams
walking(pose, jester, time, aggro_walk, 40, (weight) => {
pose.play(aggro_idle, time / 20, weight);
sway(pose, time, weight, true);
});
}
} else {
walking(pose, jester, time, walk, 20, (weight) => {
pose.play(idle, time / 20, weight);
sway(pose, time, weight, false);
});
// both clips hide them, which blended halfway would only shrink them
pose.scale("tendrils", 0, 0, 0);
}
},
};
});
}
// a sound that goes with a state: played once it holds, stopped once it doesn't
function sound_while(holds: boolean, sound: PlayingSound | undefined, play: () => PlayingSound) {
if (!holds) {
sound?.stop();
return undefined;
}
return sound ?? play();
}
// clip as it walks, a second of it for ticks of walk_position, and standing as strongly as it isn't walking
function walking(
pose: EntityPose,
jester: AnimatedEntity,
time: number,
clip: Clip,
ticks: number,
standing: (weight: number) => void,
) {
const speed = Math.min(jester.walk_speed(time), 1);
pose.play(clip, jester.walk_position(time) / ticks, speed);
standing(1 - speed);
}
// the box bobbing and the arm swaying as it stands, and once it's popped the lid, skull, jaw and crank too
function sway(pose: EntityPose, time: number, weight: number, popped: boolean) {
// bedrock's math.cos and math.sin of life_time (seconds) times degrees a second
const seconds = time / 20;
const cos = (degrees_a_second: number) => Math.cos(seconds * degrees_a_second * Math.PI / 180) * weight;
const sin = (degrees_a_second: number) => Math.sin(seconds * degrees_a_second * Math.PI / 180) * weight;
pose.rotate("box", cos(180) * 2.5, 0, 0);
pose.rotate("left_arm", (-1.6248 * weight) + cos(90) * 5, -22.22485 * weight, 70.78761 * weight);
pose.rotate("left_forearm", cos(180) * 5, 62.5 * weight, 0);
if (!popped) {
pose.move("box", 0, -weight + cos(180), 0);
pose.move("left_arm", 0, 3 * weight - cos(180), 0);
return;
}
pose.rotate("tendrils", sin(180) * 2.5, 0, 0);
pose.rotate("box_lid", -127.5 * weight + sin(180) * 5, 0, 0);
pose.rotate("skull", cos(180) * -2.5, 0, 0);
pose.rotate("jaw", 10 * weight + sin(180) * 5, 0, 0);
pose.rotate("crank", sin(180) * 2.5, 0, 0);
}
+16 -3
View File
@@ -2,8 +2,18 @@ import type { ClientContext, Color } from "cubi/client";
import type { ServerContext } from "cubi/server";
import { DOOR, FACILITY_DOOR } from "./shared.ts";
import { Alea } from "@paulaboks/rng";
import { register_coilhead } from "./coilhead.ts";
import { DOORWAY, MAIN_TILE, type Marker, type PlacedTile, plan_interior, tile_type, TILES } from "./interior.ts";
import { register_coilhead, register_coilhead_animator } from "./coilhead.ts";
import { register_jester, register_jester_animator } from "./jester.ts";
import {
DOORWAY,
MAIN_TILE,
type Marker,
type PlacedTile,
plan_interior,
SURFACE_Y,
tile_type,
TILES,
} from "./interior.ts";
export { shared } from "./shared.ts";
@@ -15,10 +25,13 @@ export function server(ctx: ServerContext) {
register_death(ctx);
register_commands(ctx);
register_coilhead(ctx);
register_jester(ctx);
}
export function client(ctx: ClientContext) {
register_hud(ctx);
register_coilhead_animator(ctx);
register_jester_animator(ctx);
}
// a small 5x5 ring in the middle of the screen to aim with, its corners and middle left empty, in gui pixels
@@ -141,7 +154,7 @@ function clear_map(ctx: ServerContext) {
function place_surface(ctx: ServerContext) {
ctx.schematics.place(
"dangerous_business:assurance",
{ position: { x: -80, y: 150, z: -80 } },
{ position: { x: -80, y: SURFACE_Y, z: -80 } },
);
}
+11 -5
View File
@@ -110,13 +110,16 @@ function register_facility_door(ctx: SharedContext) {
});
}
// the door component's params: "pairs_with" is the tag of doors it makes double doors with
// the door component's params: "pairs_with" is the tag of doors it makes double doors with, and the sounds it makes
// opening and closing
export interface DoorParams {
pairs_with: string;
open_sound: string;
close_sound: string;
}
// what set_door_open needs, which shared, server and client phases all have
type DoorContext = Pick<SharedContext, "tags"> & {
// what set_door_open needs, which shared and server phases both have
type DoorContext = Pick<SharedContext, "tags" | "sounds"> & {
world: Pick<SharedContext["world"], "get_block" | "get_state" | "set_state">;
};
@@ -128,11 +131,14 @@ function door_at(ctx: DoorContext, x: number, y: number, z: number, params: Door
}
// opens (open 1) or closes (open 0) the door with a half at x y z: both its halves, and the other door of a double
// door with it when it's open or closed like this one. players do it by clicking, monsters from their goals. returns
// whether it changed
// door with it when it's open or closed like this one, with its sound. players do it by clicking, monsters from their
// goals. returns whether it changed
export function set_door_open(ctx: DoorContext, x: number, y: number, z: number, open: number, params: DoorParams) {
const lower = ctx.world.get_state(x, y, z, "half") ? y - 1 : y;
const state = (name: string, at_x = x, at_z = z) => ctx.world.get_state(at_x, lower, at_z, name);
if (state("open") !== open) {
ctx.sounds.play(open ? params.open_sound : params.close_sound, x + 0.5, lower + 1, z + 0.5);
}
// both halves of the door whose lower half is at x z
const set_halves = (at_x: number, at_z: number) => {
if (ctx.world.get_block(at_x, lower + 1, at_z) === ctx.world.get_block(at_x, lower, at_z)) {
+29
View File
@@ -0,0 +1,29 @@
{
"format_version": 1,
"sounds": {
"jester/step": { "files": ["jester/stomp_1", "jester/stomp_2", "jester/stomp_3"], "category": "entities" },
"jester/turn_crank": {
"files": ["jester/turn_crank_1", "jester/turn_crank_2", "jester/turn_crank_3"],
"category": "entities"
},
"jester/theme": { "files": ["jester/theme"], "category": "entities", "range": 32 },
"jester/pop": { "files": ["jester/pop"], "category": "entities", "range": 32 },
"jester/scream": { "files": ["jester/scream"], "category": "entities", "range": 32 },
"coilhead/step": {
"files": ["coilhead/footstep_1", "coilhead/footstep_2", "coilhead/footstep_3", "coilhead/footstep_4"],
"category": "entities"
},
"coilhead/stop": {
"files": ["coilhead/spring_1", "coilhead/spring_2", "coilhead/spring_3"],
"category": "entities",
"range": 24
},
"coilhead/seen": {
"files": ["coilhead/spring_wobble_1", "coilhead/spring_wobble_2"],
"category": "entities",
"range": 24
},
"door/open": { "files": ["door/door_close_1", "door/door_close_2"], "category": "blocks" },
"door/close": { "files": ["door/door_open_1", "door/door_open_2"], "category": "blocks" }
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

+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);
}
+3 -1
View File
@@ -287,7 +287,9 @@ export class MeleeAttackGoal extends Goal {
override tick() {
const mob = this.mob;
const target = mob.target!;
// a script's goal ticking before this one can have let it go, it stops next tick
const target = mob.target;
if (!target) return;
mob.look_control.look_at_entity(target);
this.#recalculate -= 1;
const block = `${Math.floor(target.x)},${Math.floor(target.y)},${Math.floor(target.z)}`;
+8
View File
@@ -13,6 +13,7 @@ import type { EntityData } from "@/common/protocol.ts";
import type { ItemStack } from "@/common/inventory.ts";
import { wrap_angle } from "@/common/utils.ts";
import { TICK_DELTA } from "@/common/constants.ts";
import { is_object } from "@/common/schema.ts";
import { physics } from "@/common/physics.ts";
// minecraft's despawning distances: gone at once past the first, maybe after a while past the second
@@ -40,6 +41,7 @@ export interface SavedMob extends SavedLivingEntity {
home_pos?: [number, number, number];
home_radius?: number;
drop_chances?: Partial<Record<EquipmentSlot, number>>;
client_data?: Record<string, unknown>;
}
// what natural spawning counts a mob as, like minecraft's MobCategory
@@ -52,6 +54,9 @@ export abstract class Mob extends LivingEntity {
persistence_required = false;
can_pick_up_loot = false;
left_handed = false;
// what clients see of a mod's mob's state, see MobRef.set_client_data. replaced rather than changed, so a save never
// shares it
client_data: Record<string, unknown> = {};
// where it stays around, see is_within_home. no home when the radius is -1
home: { x: number; y: number; z: number } | undefined;
home_radius = -1;
@@ -265,6 +270,7 @@ export abstract class Mob extends LivingEntity {
override synced_data(): EntityData {
const data = super.synced_data();
if (this.left_handed) data.left_handed = true;
if (Object.keys(this.client_data).length) data.client_data = this.client_data;
return data;
}
@@ -281,6 +287,7 @@ export abstract class Mob extends LivingEntity {
saved.home_radius = this.home_radius;
}
if (Object.keys(this.drop_chances).length) saved.drop_chances = { ...this.drop_chances };
if (Object.keys(this.client_data).length) saved.client_data = this.client_data;
}
override load_additional(saved: SavedMob) {
@@ -289,6 +296,7 @@ export abstract class Mob extends LivingEntity {
this.persistence_required = saved.persistence_required === true;
this.can_pick_up_loot = saved.can_pick_up_loot === true;
this.left_handed = saved.left_handed === true;
this.client_data = is_object(saved.client_data) ? structuredClone(saved.client_data) : {};
if (Array.isArray(saved.home_pos) && typeof saved.home_radius === "number") {
const [x, y, z] = saved.home_pos.map((n) => finite(n, 0));
this.restrict_to(x, y, z, saved.home_radius);
+70 -15
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_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";
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,47 @@ 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 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);
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) {
@@ -818,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);
@@ -1294,7 +1337,11 @@ export class GameServer {
}
// creative breaks drop nothing, since placing doesn't use anything up
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);
}
@@ -1464,7 +1511,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 +1556,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 +1590,11 @@ 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));
// 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);
}
+54 -12
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 }),
});
}
@@ -750,6 +752,15 @@ export class ModRuntime {
mob.level.entity_event(mob, "swing");
mob.do_hurt_target(entity);
},
get_client_data: (field) => structuredClone(mob.client_data[field]) as never,
set_client_data(field, value) {
if (typeof field !== "string" || field === "") throw new Error("a client data field needs a name");
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;
}
@@ -781,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);
},
};
}
@@ -1244,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;
@@ -1675,18 +1697,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
}
player.vitals.add_exhaustion(amount);
},
attribute: (id) => player.attribute(known_attribute(id)),
add_modifier(attribute, modifier) {
const type = known_attribute(attribute);
const { id, amount, operation } = modifier;
if (typeof id !== "string" || typeof amount !== "number" || !Number.isFinite(amount)) {
throw new Error("a modifier needs a string id and a number amount");
}
if (!MODIFIER_OPERATIONS.includes(operation)) throw new Error(`unknown modifier operation ${operation}`);
player.attributes.get(type)?.add_modifier({ id, amount, operation });
},
remove_modifier: (attribute, id) =>
player.attributes.get(known_attribute(attribute))?.remove_modifier(id) ?? false,
...attributes_api(player),
add_effect(id, duration, options = {}) {
const type = known_effect(id);
if (!Number.isInteger(duration) || (duration < 1 && duration !== -1)) {
@@ -1716,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}`);
@@ -1742,8 +1762,27 @@ function look_direction(yaw: number, pitch: number): Position {
return { x: -Math.sin(yaw) * cos_pitch, y: Math.sin(pitch), z: -Math.cos(yaw) * cos_pitch };
}
// a player's or a mob's attribute, add_modifier and remove_modifier
function attributes_api(entity: LivingEntity): Pick<LivingRef, "attribute" | "add_modifier" | "remove_modifier"> {
return {
attribute: (id) => entity.attribute(known_attribute(id)),
add_modifier(attribute, modifier) {
const type = known_attribute(attribute);
const { id, amount, operation } = modifier;
if (typeof id !== "string" || typeof amount !== "number" || !Number.isFinite(amount)) {
throw new Error("a modifier needs a string id and a number amount");
}
if (!MODIFIER_OPERATIONS.includes(operation)) throw new Error(`unknown modifier operation ${operation}`);
entity.attributes.get(type)?.add_modifier({ id, amount, operation });
},
remove_modifier: (attribute, id) =>
entity.attributes.get(known_attribute(attribute))?.remove_modifier(id) ?? false,
};
}
export function living_ref(entity: LivingEntity): LivingRef {
return {
...attributes_api(entity),
id: entity.id,
get health() {
return entity.health;
@@ -1817,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;
+3
View File
@@ -222,6 +222,8 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
spawns: entries(mod.data.spawns),
entities: entries(mod.data.entities),
entity_models: entries(mod.data.entity_models),
animations: entries(mod.data.animations ?? []),
sounds: entries(mod.data.sounds ?? []),
effects: entries(mod.data.effects),
fluids: entries(mod.data.fluids),
tags: entries(mod.data.tags),
@@ -238,5 +240,6 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
textures: [...mod.textures.keys()],
texture_files: new Map(),
texture_json: new Map(mod.texture_json),
sound_files: new Map(),
};
}
+342
View File
@@ -0,0 +1,342 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// clips: bedrock animation files read into them, sampled at a time, and what they do to a model's bones
import { assert, assertAlmostEquals, assertEquals, assertStringIncludes } from "@std/assert";
import { type ClipJson, clips_from_bedrock, entity_model_from_geo, type EntityModelJson } from "@/common/mod_data.ts";
import { sample_channel, sample_clip } from "@/client/rendering/animation.ts";
import { apply, bone_matrices, type BoneOffsets, IDENTITY, type Vec3 } from "@/client/rendering/model_math.ts";
import { create_mod } from "@/tools/new_mod.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { type AnimatedEntity, AnimationState, type Clip, type EntityAnimator } from "@/common/mod_api/client.ts";
import { animation_for, type AnimatorSource, entity_animators } from "@/client/rendering/entity_animators.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { EntityData } from "@/common/protocol.ts";
import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts";
// the one clip a file with one animation reads into
function one_clip(animation: unknown): ClipJson {
const { clips, problems } = clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test");
assertEquals(problems, []);
return clips[0];
}
function problems_of(animation: unknown) {
return clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test").problems;
}
const key = (time: number, value: Vec3, smooth = false, post = value) => ({ time, pre: value, post, smooth });
Deno.test("every way bedrock writes a value reads into the same keyframe", () => {
const at_zero = (value: unknown) => one_clip({ bones: { arm: { rotation: { "0.0": value } } } }).bones.arm.rotation;
const expected = [key(0, [5, 5, 5])];
for (const value of [5, "5", [5, 5, 5], ["5", 5, 5.0], { post: [5, 5, 5] }, { pre: 5 }, { vector: [5, 5, 5] }]) {
assertEquals(at_zero(value), expected, JSON.stringify(value));
}
// a value for the whole clip, without times
for (const value of [5, [5, 5, 5], { post: 5 }, { vector: 5 }]) {
assertEquals(one_clip({ bones: { arm: { rotation: value } } }).bones.arm.rotation, expected);
}
assertEquals(at_zero({ pre: [1, 2, 3], post: [4, 5, 6], lerp_mode: "catmullrom" }), [
key(0, [1, 2, 3], true, [4, 5, 6]),
]);
assertEquals(at_zero({ vector: [1, 2, 3], easing: "catmullrom" }), [key(0, [1, 2, 3], true)]);
});
Deno.test("a clip's keyframes are in time order, its length is the last one's without animation_length", () => {
const clip = one_clip({ bones: { arm: { position: { "1.5": [1, 0, 0], "0.25": [2, 0, 0] }, scale: 0 } } });
assertEquals(clip.bones.arm.position!.map((keyframe) => keyframe.time), [0.25, 1.5]);
assertEquals(clip.length, 1.5);
assertEquals(clip.loop, false);
assertEquals(one_clip({ animation_length: 4, loop: true, bones: {} }).length, 4);
assertEquals(one_clip({ loop: true, bones: {} }).loop, true);
assertEquals(one_clip({ loop: "hold_on_last_frame", bones: {} }).loop, false);
});
Deno.test("a file's animations are clips named after their last part", () => {
const file = { animations: { "animation.Walker.WALK": { bones: {} }, "animation.walker.idle": { bones: {} } } };
const { clips } = clips_from_bedrock(file, "a:walker");
assertEquals(clips.map((clip) => clip.id), ["a:walker/walk", "a:walker/idle"]);
const twice = { animations: { "animation.one.walk": { bones: {} }, "animation.two.walk": { bones: {} } } };
const { problems } = clips_from_bedrock(twice, "a:walker");
assertStringIncludes(problems.join(), "a:walker/walk is another animation's too");
assertStringIncludes(clips_from_bedrock({ format_version: "1.8.0" }, "a:b").problems.join(), "animation file");
});
Deno.test("expressions are problems, and what an animator does instead is a warning", () => {
const expression = problems_of({ bones: { box: { rotation: ["math.cos(query.life_time * 180) * 2.5", 0, 0] } } });
assertEquals(expression.length, 1);
assertStringIncludes(expression[0], "box rotation");
assertStringIncludes(expression[0], "an animator does that in code");
assertStringIncludes(
problems_of({ bones: { box: { scale: { "0": { post: 1, lerp_mode: "bezier" } } } } }).join(),
"bezier",
);
assertStringIncludes(problems_of({ loop: "sometimes", bones: {} }).join(), "loop");
assertStringIncludes(problems_of({ bones: { box: { rotation: { soon: 0 } } } }).join(), "soon isn't a time");
const file = {
animations: {
"animation.box.crank": {
sound_effects: { "0.5": { effect: "turn" } },
bones: { box: { rotation: 0, relative_to: { rotation: "entity" } } },
},
},
};
const { clips, warnings } = clips_from_bedrock(file, "a:box");
assertEquals(clips.length, 1);
assertEquals(warnings.length, 2);
assertStringIncludes(warnings.join(), "sound_effects");
assertStringIncludes(warnings.join(), "relative_to");
});
Deno.test("check-mods reads a mod's animation files into its clips", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" });
create_mod("walkers", "Walkers", dir);
Deno.mkdirSync(`${dir}/walkers/animations/monsters`, { recursive: true });
const animation = { animations: { "animation.walker.walk": { loop: true, bones: { leg: { rotation: 5 } } } } };
Deno.writeTextFileSync(`${dir}/walkers/animations/monsters/walker.animation.json`, JSON.stringify(animation));
const broken = { animations: { "animation.broken.walk": { bones: { leg: { rotation: "q.anim_time" } } } } };
Deno.writeTextFileSync(`${dir}/walkers/animations/broken.animation.json`, JSON.stringify(broken));
const mod = (await load_and_check(dir)).find((mod) => mod.id === "walkers")!;
assertEquals(mod.animations.map((clip) => clip.json.id), ["walkers:monsters/walker/walk"]);
const clip_errors = mod.report.errors.filter((error) => error.startsWith("animations/"));
assertEquals(clip_errors.length, 1);
assertStringIncludes(clip_errors[0], "animations/broken.animation.json");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("between keyframes it's linear, and on or past them it's theirs", () => {
const keyframes = [key(1, [0, 0, 0]), key(2, [10, 20, 30], false, [100, 100, 100]), key(3, [0, 0, 0])];
assertEquals(sample_channel(keyframes, 1.5, false), [5, 10, 15]);
assertEquals(sample_channel(keyframes, 0, false), [0, 0, 0]);
// on a keyframe that jumps it's what it comes in at, and after it what it leaves at
assertEquals(sample_channel(keyframes, 2, false), [10, 20, 30]);
assertEquals(sample_channel(keyframes, 2.5, false), [50, 50, 50]);
assertEquals(sample_channel(keyframes, 9, false), [0, 0, 0]);
});
Deno.test("catmullrom passes through its keyframes, and wraps around for its neighbours in a loop", () => {
const keyframes = [key(0, [0, 0, 0], true), key(1, [10, 10, 10], true), key(2, [0, 0, 0], true)];
for (const keyframe of keyframes) assertEquals(sample_channel(keyframes, keyframe.time, false), keyframe.pre);
const curve = sample_channel(keyframes, 0.5, false)[0];
assert(curve > 5, `${curve} curves up toward the peak, past the straight line`);
// in a loop the keyframe before the first is the one before the last, so the trough at the seam is flatter
assert(sample_channel(keyframes, 0.25, true)[0] < sample_channel(keyframes, 0.25, false)[0]);
});
Deno.test("a clip that loops wraps around its length, and one that doesn't stays on its last frame", () => {
const bones = { arm: { rotation: [key(0, [0, 0, 0]), key(1, [10, 0, 0])] } };
const rotation = (clip: ClipJson, seconds: number) => {
const offsets = new Map<string, BoneOffsets>();
sample_clip(clip, seconds, offsets);
return offsets.get("arm")!.rotation[0];
};
const looping: ClipJson = { id: "a:b/c", length: 2, loop: true, bones };
const once: ClipJson = { ...looping, loop: false };
assertAlmostEquals(rotation(looping, 2.5), rotation(looping, 0.5));
assertAlmostEquals(rotation(looping, -1.5), rotation(looping, 0.5));
assertEquals(rotation(once, 2.5), 10);
assertEquals(rotation(once, 50), 10);
});
Deno.test("clips add up, scaled by their weight", () => {
const clip = (rotation: Vec3, scale: Vec3): ClipJson => ({
id: "a:b/c",
length: 1,
loop: false,
bones: { arm: { rotation: [key(0, rotation)], scale: [key(0, scale)] } },
});
const offsets = new Map<string, BoneOffsets>();
sample_clip(clip([10, 0, 0], [3, 1, 1]), 0, offsets, 0.5);
assertEquals(offsets.get("arm"), { rotation: [5, 0, 0], position: [0, 0, 0], scale: [2, 1, 1] });
sample_clip(clip([0, 20, 0], [1, 1, 0]), 0, offsets);
assertEquals(offsets.get("arm"), { rotation: [5, 20, 0], position: [0, 0, 0], scale: [2, 1, 0] });
});
// a model with an arm and a hand on it, the arm turned by rotation
function arm_model(rotation?: Vec3): EntityModelJson {
const cubes = [{ origin: [0, 0, 0], size: [1, 1, 1], uv: [0, 0] }];
const arm = { name: "arm", pivot: [2, 3, 4], cubes, ...(rotation ? { rotation } : {}) };
const geometry = {
description: { texture_width: 16, texture_height: 16 },
bones: [arm, { name: "hand", parent: "arm", pivot: [2, 0, 4], cubes }],
};
return entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:arm").model!;
}
function offsets_for(bone: string, offsets: Partial<BoneOffsets>) {
const full = { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1], ...offsets } as BoneOffsets;
return new Map([[bone, full]]);
}
function assert_matrices_equal(actual: Map<string, number[]>, expected: Map<string, number[]>) {
for (const [bone, matrix] of expected) {
matrix.forEach((n, i) => assertAlmostEquals(actual.get(bone)![i], n, 1e-9, `${bone}[${i}]`));
}
}
Deno.test("a clip turning a bone turns it like the same rotation in the model, its children with it", () => {
const turned = bone_matrices(arm_model([30, -45, 60]), () => IDENTITY);
const animated = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { rotation: [30, -45, 60] }));
assert_matrices_equal(animated, turned);
// added to the model's own rotation
const added = bone_matrices(arm_model([10, -45, 0]), () => IDENTITY, offsets_for("arm", { rotation: [20, 0, 60] }));
assert_matrices_equal(added, turned);
});
Deno.test("a clip moves bones in the model's pixels, and scales them around their pivot", () => {
const point: Vec3 = [5, 7, 9];
const still = bone_matrices(arm_model(), () => IDENTITY);
const moved = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { position: [1, 2, 3] }));
// bedrock's +x is the engine's -x, like the pivots
for (const bone of ["arm", "hand"]) {
const [x, y, z] = apply(still.get(bone)!, ...point);
assertEquals(apply(moved.get(bone)!, ...point), [x - 1, y + 2, z + 3]);
}
const scaled = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { scale: [2, 3, 0.5] }));
const pivot = [-2, 3, 4];
assertEquals(apply(scaled.get("arm")!, ...point), point.map((n, i) => pivot[i] + (n - pivot[i]) * [2, 3, 0.5][i]));
});
Deno.test("an animation state counts seconds from when it started, and knows when a clip has played through", () => {
const once: Clip = { id: "a:b/once", length: 1, loop: false };
const state = new AnimationState();
assertEquals([state.started, state.seconds(100), state.finished(once, 100)], [false, 0, false]);
state.animate_when(true, 10);
state.animate_when(true, 15);
assertEquals(state.seconds(20), 0.5);
assert(!state.finished(once, 29));
assert(state.finished(once, 30));
assert(!state.finished({ ...once, loop: true }, 300));
state.animate_when(false, 40);
assertEquals(state.started, false);
state.start_if_stopped(50);
state.start_if_stopped(60);
assertEquals(state.seconds(70), 1);
});
// an entity the way an animator sees it, standing still and looking ahead
function animated(type: string, data: EntityData = {}): AnimatorSource & { data: EntityData } {
return {
id: "e1",
type,
data,
age: 0,
yaw: 0,
head_yaw: 0,
pitch: 0,
walk_animation: () => ({ position: 0, speed: 0 }),
attack_animation: () => 0,
};
}
// registers an animator for a new entity type, and a clip turning the arm up to 90 degrees over a second
function animator_type(name: string, create: (entity: AnimatedEntity) => EntityAnimator) {
const type = `test:${name}`;
entity_animators.set(type, { mod: "test", create });
const clip_id = `test:${name}/raise`;
if (!EverythingRegistry.get("animations", clip_id)) {
EverythingRegistry.register<ClipJson>("animations", clip_id, {
id: clip_id,
length: 1,
loop: false,
bones: { arm: { rotation: [key(0, [0, 0, 0]), key(1, [90, 0, 0])] } },
});
}
return { type, raise: { id: clip_id, length: 1, loop: false } };
}
Deno.test("an animator hears about each client data field as it changes, and the ones there from the start", () => {
const heard: string[] = [];
const { type } = animator_type("listener", () => ({ pose() {}, on_data: (field) => heard.push(field) }));
const entity = animated(type, { client_data: { mood: 1 }, glowing: true });
const animation = animation_for(entity)!;
assertEquals(heard, ["mood"]);
const before = entity.data;
entity.data = { client_data: { mood: 1, state: 2 } };
animation.data_changed(before);
assertEquals(heard, ["mood", "state"]);
const again = entity.data;
entity.data = { client_data: { state: 3 } };
animation.data_changed(again);
assertEquals(heard, ["mood", "state", "mood", "state"]);
assertEquals(animation_for(animated("test:no_animator")), undefined);
});
Deno.test("an animator's pose plays clips and moves bones", () => {
const { type, raise } = animator_type("poser", () => ({
pose(pose, time) {
pose.play(raise, time / 20, 0.5);
pose.move("arm", 1, 2, 3);
pose.scale("leg", 2, 2, 2);
pose.look("head");
},
}));
const entity = { ...animated(type), head_yaw: Math.PI / 2, pitch: -Math.PI / 4 };
const offsets = animation_for(entity)!.pose(10)!;
assertEquals(offsets.get("arm"), { rotation: [22.5, 0, 0], position: [1, 2, 3], scale: [1, 1, 1] });
assertEquals(offsets.get("leg")!.scale, [2, 2, 2]);
// mirrored like a model's own rotations
const head = offsets.get("head")!.rotation;
assertAlmostEquals(head[0], 45);
assertAlmostEquals(head[1], -90);
});
Deno.test("a clip plays from when its state started, and with walking as strongly as it walks", () => {
const state = new AnimationState();
state.start(10);
const { type, raise } = animator_type("stateful", (entity) => ({
pose(pose, time) {
pose.play_state(raise, state, time);
pose.play_walk(raise, entity, time);
},
}));
// half a second of clip walked, at half speed
const animation = animation_for({ ...animated(type), walk_animation: () => ({ position: 10, speed: 0.5 }) })!;
// a quarter of a second into the state is 22.5 degrees, and walking half of 45
assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5 + 22.5);
state.stop();
assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5);
});
Deno.test("an animator that throws is removed, and the entity is posed without it", async () => {
const { type } = animator_type("thrower", () => ({
pose(pose) {
pose.play({ id: "test:nowhere/nothing", length: 1, loop: false }, 0);
},
}));
const animation = animation_for(animated(type))!;
const errors = await errors_during(() => assertEquals(animation.pose(0), undefined));
assertEquals(errors.length, 1);
assertStringIncludes(errors[0], "[test] the animator of test:thrower e1 threw in pose");
assertStringIncludes(errors[0], "test:nowhere/nothing isn't a clip");
assertEquals(animation.pose(1), undefined);
});
Deno.test("a mob's client data goes to the players who see it, and is saved with it", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_client_data_" });
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
const t = await test_game(dir);
t.join(1, "alice");
const mob = test_mob(t.game, {}, 0.5, 100, 0.5);
const ref = t.game.mods.mob(mob);
t.game.tick();
t.take(1);
ref.set_client_data("state", { mood: 3 });
assertEquals(ref.get_client_data("state"), { mood: 3 });
t.game.tick();
const sent = t.take(1).find((m) => m.type === "entity_data" && m.id === mob.id);
assertEquals(sent && "data" in sent ? sent.data.client_data : undefined, { state: { mood: 3 } });
const copy = test_mob(t.game, {}, 2.5, 100, 0.5);
copy.load(mob.save());
assertEquals(t.game.mods.mob(copy).get_client_data("state"), { mood: 3 });
ref.set_client_data("state", undefined);
assertEquals(mob.synced_data().client_data, undefined);
Deno.removeSync(dir, { recursive: true });
});
+223 -2
View File
@@ -9,7 +9,12 @@ import { ItemStack } from "@/common/inventory.ts";
import { get_state_value, set_state_value } from "@/common/utils.ts";
import { create_entity } from "@/server/game/entity/entity_types.ts";
import type { Mob } from "@/server/game/entity/mob.ts";
import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts";
import { copy_dir, errors_during, ListOutput, load_as_player, test_game, test_mob, VOLUMES } from "./helpers.ts";
import { animation_for } from "@/client/rendering/entity_animators.ts";
import { sounds } from "@/client/sounds.ts";
import { set_mods_client } from "@/client/mods.ts";
import type { Client } from "@/client/client.ts";
import type { EntityData } from "@/common/protocol.ts";
const HALF = "dangerous_business:concrete_wall_slab";
const CONNECTS = "dangerous_business:floor_grate";
@@ -18,6 +23,7 @@ const FLOOR = "dangerous_business:concrete_floor";
const DEATH = "dangerous_business:death";
const PIPE = "dangerous_business:double_steel_pipes";
const COILHEAD = "dangerous_business:coilhead";
const JESTER = "dangerous_business:jester";
const FACTORY_DOOR = "dangerous_business:factory_door";
// alice on a concrete floor at y 100, south of 0 100 0 and looking north, holding each of the blocks. it's a game of
@@ -138,15 +144,38 @@ function spawn_coilhead(t: Awaited<ReturnType<typeof setup>>["t"]) {
Deno.test("a coilhead can't move while a player looks at it, and comes for them once they look away", async () => {
const { t } = await setup();
const coilhead = spawn_coilhead(t);
const coilhead = spawn_coilhead(t) as Mob;
for (let i = 0; i < 100; i++) t.game.tick();
assertAlmostEquals(coilhead.x, 0.5, 1e-6);
assertAlmostEquals(coilhead.z, -2.5, 1e-6);
// what its animator reads
assertEquals(coilhead.client_data.frozen, true);
// looking south, with it behind her
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: Math.PI, pitch: 0 });
for (let i = 0; i < 100; i++) t.game.tick();
assert(coilhead.z > 0, `it only got to z ${coilhead.z}`);
assertEquals(coilhead.client_data.frozen, undefined);
});
// the sounds conn was sent since last asked, as [sound, where]: the entity it follows, or the point it's at
const sounds_sent = (t: Awaited<ReturnType<typeof setup>>["t"], conn: number): [string, unknown][] =>
t.take(conn).filter((m) => m.type === "sound").map((m) => [m.sound, m.entity ?? m.at]);
Deno.test("a coilhead springs once when a player's look freezes it", async () => {
const { t } = await setup();
// looking south, away from it
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: Math.PI, pitch: 0 });
const coilhead = spawn_coilhead(t);
for (let i = 0; i < 5; i++) t.game.tick();
assertEquals(sounds_sent(t, 1), []);
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: 0, pitch: 0 });
for (let i = 0; i < 40; i++) t.game.tick();
assertEquals(sounds_sent(t, 1), [
["dangerous_business:coilhead/stop", coilhead.id],
["dangerous_business:coilhead/seen", coilhead.id],
]);
});
Deno.test("a player can't stop a coilhead through a wall", async () => {
@@ -251,3 +280,195 @@ Deno.test("a coilhead seen while it waits at a closed door stops waiting, and do
assert(!open(), "it opened the door while it was seen");
assertEquals(coilhead.navigation.blocked_by, undefined);
});
Deno.test("a factory door sounds as it opens and closes, for everyone but the player whose click their client heard", async () => {
const { t, state } = await setup();
const { open } = door_in_wall(t, state);
t.join(2, "bob");
t.send(2, { type: "move", x: 1.5, y: 100, z: 2.5, yaw: 0, pitch: 0 });
t.game.tick();
t.take(1);
t.take(2);
const click = () => t.send(1, { type: "use_block", x: 0, y: 100, z: 0, face: "south", hit: [0.5, 0.5, 1] });
click();
assert(open());
assertEquals(sounds_sent(t, 1), []);
assertEquals(sounds_sent(t, 2), [["dangerous_business:door/open", [0.5, 101, 0.5]]]);
click();
assertEquals(sounds_sent(t, 2), [["dangerous_business:door/close", [0.5, 101, 0.5]]]);
});
// a jester 6 blocks north of alice, in a state from its client data like one that was saved
function spawn_jester(t: Awaited<ReturnType<typeof setup>>["t"], state?: number) {
const jester = create_entity(t.game.entities, JESTER)! as Mob;
jester.set_position(0.5, 100, -2.5);
if (state !== undefined) jester.client_data = { state };
t.game.entities.add_entity(jester);
return jester;
}
Deno.test("a jester follows a player it sees without hurting them, then winds its crank standing still", async () => {
const { t } = await setup();
const alice = t.game.players()[0];
const jester = spawn_jester(t);
for (let i = 0; i < 100; i++) t.game.tick();
assert(jester.z > -1, `it stayed at z ${jester.z}, away from her`);
assertEquals(alice.health, alice.max_health);
for (let i = 0; i < 2000 && jester.client_data.state !== 2; i++) t.game.tick();
assertEquals(jester.client_data.state, 2);
const at = [jester.x, jester.z];
t.send(1, { type: "move", x: -2.5, y: 100, z: 3.5, yaw: 0, pitch: 0 });
for (let i = 0; i < 100; i++) t.game.tick();
assertEquals([jester.x, jester.z], at);
});
Deno.test("a popped jester runs down the nearest player faster and faster, and boxes up once they're out", async () => {
const { t } = await setup();
const alice = t.game.players()[0];
const jester = spawn_jester(t, 3);
const speed = () => t.game.mods.mob(jester).attribute("cubi:movement_speed");
const walking = speed();
for (let i = 0; i < 200 && alice.health === alice.max_health; i++) t.game.tick();
assert(alice.health < alice.max_health, "it never got to her");
assert(speed() > walking);
const chasing = speed();
for (let i = 0; i < 300; i++) t.game.tick();
assert(speed() > chasing, "it didn't get any faster");
// up on the surface, out of the facility
alice.set_position(0.5, 160, 3.5);
t.game.tick();
assertEquals(jester.client_data.state, 1);
assertEquals(speed(), walking);
});
Deno.test("a jester saved while it winds goes on from where it got to", async () => {
const { t } = await setup();
const jester = spawn_jester(t, 2);
// 39.5 seconds in
jester.client_data = { state: 2, since: t.game.world.time - 790 };
for (let i = 0; i < 5; i++) t.game.tick();
assertEquals(jester.client_data.state, 2);
for (let i = 0; i < 15; i++) t.game.tick();
assertEquals(jester.client_data.state, 3);
});
Deno.test("a jester's crank clicks once a second while it winds, and it pops once", async () => {
const { t } = await setup();
const jester = spawn_jester(t, 2);
for (let i = 0; i < 100; i++) t.game.tick();
const cranking = sounds_sent(t, 1);
assertEquals(cranking.length, 5);
assertEquals(new Set(cranking.map(([sound]) => sound)), new Set(["dangerous_business:jester/turn_crank"]));
for (let i = 0; i < 1000 && jester.client_data.state !== 3; i++) t.game.tick();
assertEquals(sounds_sent(t, 1).filter(([sound]) => sound !== "dangerous_business:jester/turn_crank"), [
["dangerous_business:jester/pop", jester.id],
]);
});
// last, since it loads the mod the way a player gets it, in place of the server's
Deno.test("a coilhead's head springs back and forth when it freezes, and stays still when it stands", async () => {
const dir = Deno.makeTempDirSync({ prefix: "dangerous_business_client_" });
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
await load_as_player(dir);
const coilhead = (frozen: boolean) => ({
id: "e1",
type: COILHEAD,
data: frozen ? { client_data: { frozen: true } } : {},
age: 0,
yaw: 0,
head_yaw: 0,
pitch: 0,
walk_animation: () => ({ position: 0, speed: 0 }),
attack_animation: () => 0,
});
const head = (frozen: boolean, time: number) => animation_for(coilhead(frozen))!.pose(time)!.get("head")?.rotation;
assertNotEquals(head(true, 5), [0, 0, 0]);
assertEquals(head(false, 5), [0, 0, 0]);
// it's over in under a minute
assertEquals(head(true, 1200), head(false, 1200));
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a jester keeps its tendrils in the box until it pops, and turns its crank while it winds", async () => {
const dir = Deno.makeTempDirSync({ prefix: "dangerous_business_client_" });
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
await load_as_player(dir);
const pose = (state: number | undefined, time: number) => {
const jester = {
id: "e1",
type: JESTER,
data: state === undefined ? {} : { client_data: { state } },
age: 0,
yaw: 0,
head_yaw: 0,
pitch: 0,
walk_animation: () => ({ position: 0, speed: 0 }),
attack_animation: () => 0,
};
return animation_for(jester)!.pose(time)!;
};
assertEquals(pose(undefined, 10).get("tendrils")!.scale, [0, 0, 0]);
assertNotEquals(pose(3, 100).get("tendrils")!.scale, [0, 0, 0]);
assertNotEquals(pose(2, 5).get("crank")!.rotation, pose(2, 15).get("crank")!.rotation);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a jester's music box and scream play from as far as it's got, for a player who comes upon it partway", async () => {
const dir = Deno.makeTempDirSync({ prefix: "dangerous_business_client_" });
copy_dir("mods/dangerous_business", `${dir}/dangerous_business`);
await load_as_player(dir);
// the world's time on this client, in ticks
const level = { time: 10_000 };
set_mods_client({ level } as unknown as Client);
const output = new ListOutput();
sounds.set_output(output);
const jester = {
id: "e1",
type: JESTER,
// winding for 30 seconds already
data: { client_data: { state: 2, since: 10_000 - 600 } } as EntityData,
age: 0,
yaw: 0,
head_yaw: 0,
pitch: 0,
walk_animation: () => ({ position: 0, speed: 0 }),
attack_animation: () => 0,
};
const frame = () =>
sounds.frame(
{ x: 0, y: 0, z: 0, yaw: 0, pitch: 0 },
(id) => id === "e1" ? { x: 0, y: 0, z: 3 } : undefined,
VOLUMES,
);
const set_state = (state: number) => {
const before = jester.data;
jester.data = { client_data: { state, since: level.time } };
animation.data_changed(before);
frame();
};
const animation = animation_for(jester)!;
frame();
const [theme] = output.playing;
assertEquals(theme.file.id, "dangerous_business:jester/theme");
assert(theme.settings.loop);
// and a moment of the real clock since it was played
assertAlmostEquals(theme.settings.offset, 30, 0.1);
level.time += 200;
set_state(3);
assert(theme.stopped);
const [scream] = output.playing;
assertEquals(scream.file.id, "dangerous_business:jester/scream");
assert(scream.settings.loop);
assertAlmostEquals(scream.settings.offset, 0, 0.1);
set_state(1);
assertEquals(output.playing, []);
sounds.stop_all();
set_mods_client(undefined as unknown as Client);
Deno.removeSync(dir, { recursive: true });
});
+43
View File
@@ -36,6 +36,8 @@ import { RecipeBook } from "@/common/mod_loader.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import { mod_entity_factory } from "@/server/game/entity/mod_entity.ts";
import type { Mob } from "@/server/game/entity/mob.ts";
import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "@/client/sounds.ts";
import type { Position } from "@/common/mod_api/shared.ts";
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
// mods/ is kept, since tests change the temporary folders they make between games
@@ -392,6 +394,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 +430,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 });
@@ -478,3 +484,40 @@ export async function errors_during(fn: () => unknown): Promise<string[]> {
}
return errors;
}
// a client's sound output that only keeps what it was told, see client/sounds.ts
export class ListVoice implements Voice {
ended = false;
stopped = false;
constructor(readonly file: SoundFile, public settings: VoiceSettings) {}
move(at: Position) {
this.settings = { ...this.settings, at };
}
set(volume: number, pitch: number, range: number) {
this.settings = { ...this.settings, volume, pitch, range };
}
stop() {
this.stopped = true;
}
}
export class ListOutput implements SoundOutput {
// false like a browser before the player's first click
ready = true;
voices: ListVoice[] = [];
start(file: SoundFile, settings: VoiceSettings) {
if (!this.ready) return undefined;
const voice = new ListVoice(file, settings);
this.voices.push(voice);
return voice;
}
listen() {}
set_volumes() {}
// the ones still going
get playing() {
return this.voices.filter((voice) => !voice.stopped && !voice.ended);
}
}
// every sound category at full volume
export const VOLUMES: Volumes = { master: 1, music: 1, ambient: 1, blocks: 1, entities: 1, players: 1, ui: 1 };
+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(),
+70 -8
View File
@@ -8,10 +8,11 @@ import {
entity_model_from_geo,
type EntityBoneJson,
type EntityJson,
type EntityModelJson,
validate_entity,
} from "@/common/mod_data.ts";
import type { Texture } from "@/client/renderer/mod.ts";
import { IDENTITY } from "@/client/rendering/model_math.ts";
import { bone_matrices, IDENTITY } from "@/client/rendering/model_math.ts";
import { push_model } from "@/client/rendering/model_renderer.ts";
import { Mob } from "@/server/game/entity/mob.ts";
import { create_entity } from "@/server/game/entity/entity_types.ts";
@@ -33,8 +34,8 @@ Deno.test("a bedrock geo.json becomes an entity model with only what the engine
],
});
// per face uvs and parents that come later aren't supported
const per_face = { origin: [0, 0, 0], size: [1, 1, 1], uv: { north: { uv: [0, 0], uv_size: [1, 1] } } };
// parents that come later and uvs that are neither box nor per face aren't supported
const bad_uv = { origin: [0, 0, 0], size: [1, 1, 1], uv: { north: { uv: [0, 0] } } };
const geo_problems = (bones: unknown[]) => {
const geometry = { description: { texture_width: 16, texture_height: 16 }, bones };
const { model, problems } = entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:b");
@@ -43,11 +44,63 @@ Deno.test("a bedrock geo.json becomes an entity model with only what the engine
};
const late_parent = geo_problems([{ name: "leg", parent: "body" }, { name: "body" }]);
assert(late_parent.some((p) => p.includes("parent body must be a bone before it")), String(late_parent));
const per_face_problems = geo_problems([{ name: "leg", cubes: [per_face] }]);
assert(per_face_problems.some((p) => p.includes("per face uvs aren't supported")), String(per_face_problems));
const uv_problems = geo_problems([{ name: "leg", cubes: [bad_uv] }]);
assert(uv_problems.some((p) => p.includes("uv.north.uv_size is required")), String(uv_problems));
assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined);
});
// every vertex of the model's bones as [x, y, z, u, v], in texture pixels
function model_vertices(model: EntityModelJson, only?: (bone: EntityBoneJson) => boolean) {
const out: number[][] = [];
const atlas = { width: model.texture_width, height: model.texture_height } as Texture;
const region = { x: 0, y: 0, width: model.texture_width, height: model.texture_height };
push_model(model, bone_matrices(model, () => IDENTITY), atlas, region, (x, y, z) => [x, y, z], undefined, only, (
x,
y,
z,
u,
v,
) => {
out.push([x, y, z, u * model.texture_width, v * model.texture_height]);
});
return out;
}
Deno.test("per face uvs texture a cube like box uv does when they're where box uv puts each face", () => {
const [u, v] = [4, 2];
const [w, h, d] = [3, 5, 2];
const face = (fu: number, fv: number, fw: number, fh: number) => ({ uv: [u + fu, v + fv], uv_size: [fw, fh] });
// the way blockbench writes a box uv cube out per face: the bottom upside down
const per_face = {
north: face(d, d, w, h),
east: face(0, d, d, h),
south: face(2 * d + w, d, w, h),
west: face(d + w, d, d, h),
up: face(d, 0, w, d),
down: face(d + w, d, w, -d),
};
const geometry = {
description: { texture_width: 32, texture_height: 32 },
bones: [
{ name: "box", pivot: [0, 0, 0], cubes: [{ origin: [1, 2, 3], size: [w, h, d], uv: [u, v] }] },
{ name: "per_face", pivot: [0, 0, 0], cubes: [{ origin: [1, 2, 3], size: [w, h, d], uv: per_face }] },
{
name: "top_only",
pivot: [0, 0, 0],
cubes: [{ origin: [1, 2, 3], size: [w, h, d], uv: { up: per_face.up } }],
},
],
};
const { model, problems } = entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:b");
assertEquals(problems, []);
const box = model_vertices(model!, (bone) => bone.name === "box");
const per_face_vertices = model_vertices(model!, (bone) => bone.name === "per_face");
assertEquals(per_face_vertices.length, box.length);
per_face_vertices.forEach((vertex, i) => vertex.forEach((n, j) => assertAlmostEquals(n, box[i][j], 1e-9)));
// faces it leaves out aren't drawn
assertEquals(model_vertices(model!, (bone) => bone.name === "top_only"), box.slice(0, 6));
});
Deno.test("a cube's rotation turns it around its pivot like the same rotation on its bone", () => {
const pivot = [1, 2, 3];
const rotation = [30, -45, 60];
@@ -67,9 +120,18 @@ Deno.test("a cube's rotation turns it around its pivot like the same rotation on
const atlas = { width: 16, height: 16 } as Texture;
const region = { x: 0, y: 0, width: 16, height: 16 };
const only = (bone: EntityBoneJson) => bone.name === name;
push_model(model!, () => IDENTITY, atlas, region, (x, y, z) => [x, y, z], undefined, only, (x, y, z) => {
out.push(x, y, z);
});
push_model(
model!,
bone_matrices(model!, () => IDENTITY),
atlas,
region,
(x, y, z) => [x, y, z],
undefined,
only,
(x, y, z) => {
out.push(x, y, z);
},
);
return out;
};
const turned = points("turned_cube");
+13
View File
@@ -4,6 +4,7 @@
// mobs following paths, see server/game/entity/navigation.ts
import { assert, assertEquals } from "@std/assert";
import { test_game, test_mob } from "./helpers.ts";
import { MeleeAttackGoal } from "@/server/game/entity/goals.ts";
// two rooms on a stone floor at y 99, split by a wall at x 3 with a doorway 2 high at z 4. a goal-less mob in the
// west room at 0.5 100 0.5, and alice in its corner, so it thinks
@@ -81,3 +82,15 @@ Deno.test("a script's mob walks its way, and stops when told", async () => {
assert(Math.hypot(ref.position.x - x, ref.position.z - z) < 0.5);
assertEquals(ref.blocked_by, undefined);
});
Deno.test("a mob going after its target stops when a script lets the target go partway through its thinking", async () => {
const { game, mob } = await rooms();
const melee = new MeleeAttackGoal(mob);
mob.target = game.players()[0];
assert(melee.can_use());
melee.start();
melee.tick();
mob.target = undefined;
melee.tick();
assert(!melee.can_continue_to_use());
});
+520
View File
@@ -0,0 +1,520 @@
// 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();
});
+60
View File
@@ -5,10 +5,14 @@
// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks their scripts
import * as z from "zod";
import {
clips_from_bedrock,
data_file,
entity_model_from_geo,
FORMAT_VERSION,
is_ogg,
type OreJson,
SOUND_PATH_PATTERN,
type SoundJson,
type SpawnJson,
type TagJson,
validate_block,
@@ -20,6 +24,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_sound,
validate_spawn,
validate_tag,
} from "@/common/mod_data.ts";
@@ -131,6 +136,8 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
spawns: [],
entities: [],
entity_models: [],
animations: [],
sounds: [],
effects: [],
fluids: [],
tags: [],
@@ -146,6 +153,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
textures: [],
texture_files: new Map(),
texture_json: new Map(),
sound_files: new Map(),
};
const error = (message: string) => mod.report.errors.push(message);
@@ -229,6 +237,20 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
if (model) mod.entity_models.push({ file: path, json: model });
}
// animations/<name>.animation.json, as blockbench exports them for bedrock. each animation in one is a clip
for (const file of walk(`${dir}/animations`, ".animation.json")) {
const path = `animations/${file}`;
const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`));
if (json === undefined) continue;
const { clips, problems, warnings } = clips_from_bedrock(
json,
`${id}:${file.replace(/\.animation\.json$/, "")}`,
);
for (const problem of problems) error(`${path}: ${problem}`);
for (const warning of warnings) mod.report.warnings.push(`${path}: ${warning}`);
for (const clip of clips) mod.animations.push({ file: path, json: clip });
}
// tags/<registry>/<namespace>/<path>.json is the tag <namespace>:<path>, in any namespace: tags are shared
for (const file of walk(`${dir}/tags`, ".json")) {
const path = `tags/${file}`;
@@ -290,6 +312,44 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
if (problems.length === 0) mod.schematics.push({ file: path, json });
}
// sounds/<path>.ogg, the files sounds.json's sounds play
for (const file of walk(`${dir}/sounds`, ".ogg")) {
const path = file.replace(/\.ogg$/, "");
if (!SOUND_PATH_PATTERN.test(path)) {
error(`sounds/${file}: sound paths must be a-z, 0-9 and _ in folders`);
} else if (!is_ogg(Deno.readFileSync(`${dir}/sounds/${file}`))) {
error(`sounds/${file}: isn't an ogg file`);
} else {
mod.sound_files.set(path, `${dir}/sounds/${file}`);
}
}
// sounds.json: each key is the sound <mod id>:<key>
const used_sound_files = new Set<string>();
if (exists(`${dir}/sounds.json`)) {
const sounds = read_data("sounds.json", "sounds", z.record(z.string(), json_object), '{ "name": { ... } }') ??
{};
for (const [key, sound] of Object.entries(sounds)) {
const json = { ...sound, id: `${id}:${key}` };
const problems = SOUND_PATH_PATTERN.test(key)
? validate_sound(json)
: [`sound names must be a-z, 0-9 and _ in folders, like "thing/step"`];
for (const file of Array.isArray(sound.files) ? sound.files : []) {
if (typeof file !== "string") continue;
used_sound_files.add(file);
if (!mod.sound_files.has(file) && SOUND_PATH_PATTERN.test(file)) {
problems.push(`there's no sounds/${file}.ogg`);
}
}
for (const problem of problems) error(`sounds.json: ${key}: ${problem}`);
if (problems.length === 0) mod.sounds.push({ file: "sounds.json", json: json as SoundJson });
}
}
for (const path of mod.sound_files.keys()) {
if (!used_sound_files.has(path)) {
mod.report.warnings.push(`sounds/${path}.ogg: no sound in sounds.json plays it`);
}
}
if (exists(`${dir}/config.json`)) {
mod.config = read_data("config.json", "config", json_object, "{ ... }");
}
+6 -1
View File
@@ -3,7 +3,7 @@
// deno task pack-mod mods/copper_tools [copper_tools.cubi]
// builds a mod folder into a .cubi: its data merged into data.json, its script bundled into one module, and its
// textures and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md
// textures, sounds and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md
import { basename, dirname, resolve } from "@std/path";
import { MOD_EXTENSION, write_mod } from "@/common/mod.ts";
import type { ManifestJson } from "@/common/mod_data.ts";
@@ -20,6 +20,10 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
textures.set(id, Deno.readFileSync(path));
}
const texture_json = new Map([...mod.texture_json].sort(([a], [b]) => a.localeCompare(b)));
const sounds = new Map<string, Uint8Array>();
for (const [path, file] of [...mod.sound_files].sort(([a], [b]) => a.localeCompare(b))) {
sounds.set(path, Deno.readFileSync(file));
}
// without what the content phase registered, which the server registers again when it loads the .cubi
const data = mod_data(mod);
@@ -30,6 +34,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
script,
textures,
texture_json,
sounds,
credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined,
});
}