Merge pull request #315 from ludovic111/feat/minecart-sounds

Minecarts roll and rattle when ridden, and hits on vehicles sound
This commit is contained in:
Ludovic Marie
2026-10-15 12:32:32 +02:00
committed by GitHub
10 changed files with 324 additions and 17 deletions
@@ -131,6 +131,7 @@ fn main() {
let tick = TickContext {
player_underwater: ambience.was_underwater(),
player_removed: removed,
..TickContext::default()
};
engine.tick(false, &tick, &mut backend);
}
@@ -5,7 +5,7 @@
mod common;
use common::{Fake, d, describe, f, flush, result_name};
use horizon_client::sound_engine::{
Attenuation, Backend, InstanceId, SoundEngine, SoundInstance, TickContext,
Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext,
};
use horizon_client::sound_events::SoundRegistry;
use horizon_core::random::LegacyRandom;
@@ -19,6 +19,9 @@ fn main() {
let mut backend = Fake::default();
let mut ctx = TickContext::default();
let mut instances: BTreeMap<String, InstanceId> = BTreeMap::new();
// Script cart names to entity ids (a removed cart leaves the level).
let mut cart_ids: BTreeMap<String, u32> = BTreeMap::new();
let mut removed: BTreeMap<u32, CartSound> = BTreeMap::new();
let input = std::fs::read_to_string(&args[2]).expect("input");
let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output"));
for line in input.lines() {
@@ -49,6 +52,21 @@ fn main() {
"loop" => SoundInstance::biome_loop(&event, random),
"uloop" => SoundInstance::under_liquid_loop(&event, random),
"usub" => SoundInstance::under_liquid_sub(&event, random),
"cart" | "rcart" | "rcartu" => {
let id = cart_ids[a[3]];
let cart = ctx
.carts
.iter()
.find(|c| c.id == id)
.or_else(|| removed.get(&id))
.copied()
.expect("cart");
if a[2] == "cart" {
SoundInstance::minecart(&cart, random)
} else {
SoundInstance::riding_minecart(&cart, a[2] == "rcartu", random)
}
}
_ => panic!("{line}"),
};
if let Some(old) = instances.remove(a[1]) {
@@ -92,6 +110,26 @@ fn main() {
ctx.player_underwater = a[1] == "1";
ctx.player_removed = a[2] == "1";
}
"cart" => {
let next = cart_ids.len() as u32 + 1;
let id = *cart_ids.entry(a[1].to_owned()).or_insert(next);
ctx.carts.retain(|c| c.id != id);
let cart = CartSound {
id,
position: [d(a[2]), d(a[3]), d(a[4])],
// Vec3.horizontalDistance.
speed: (d(a[5]) * d(a[5]) + d(a[7]) * d(a[7])).sqrt(),
};
if a[8] == "1" {
// Out of the level, still there for a later play.
removed.insert(id, cart);
} else {
removed.remove(&id);
ctx.carts.push(cart);
}
}
"ride" => ctx.vehicle = cart_ids.get(a[1]).copied(),
"freeze" => ctx.frozen = a[1] == "1",
"tick" => engine.tick(a[1] == "1", &ctx, &mut backend),
"forget" => {
if let Some(id) = instances.remove(a[1]) {
+4
View File
@@ -393,6 +393,10 @@ impl FixedStep {
pub fn frozen(&self) -> bool {
self.manager.base.is_frozen()
}
/// `runsNormally` as of the last `world_runs`.
pub fn runs_normally(&self) -> bool {
self.manager.base.runs_normally()
}
pub fn set_frozen(&mut self, frozen: bool) {
self.manager.base.set_frozen(frozen);
}
+35 -10
View File
@@ -752,6 +752,10 @@ struct Game<'a> {
ambience: horizon_client::ambience::Ambience,
/// The sound engine was told the game paused (pauseAllExcept).
sound_paused: bool,
/// Minecarts whose `MinecartSoundInstance` is playing.
cart_sounds: HashSet<u32>,
/// The minecart the riding sounds were started for (`LocalPlayer.startRiding`).
riding_cart_sounds: Option<u32>,
dropped: Vec<ItemEntity>,
next_entity: u32,
particles: horizon_client::particles::ParticleEngine,
@@ -5463,6 +5467,33 @@ impl Game<'_> {
}
best
}
/// `Player.getAttackStrengthScale(0.5)`.
fn attack_strength_scale(&self) -> f32 {
let speed = self
.held()
.and_then(|h| self.res.items.get(&h.item))
.map_or(0.0, |i| i.attack_speed);
let delay = 20.0 / (4.0 + speed).max(0.1);
((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0)
}
/// `Player.attack`'s sounds when a vehicle takes the hit (it always does,
/// and can't be hit critically): knockback when sprinting at full
/// strength, then strong or weak. Before `swing_arm` resets the charge.
pub(super) fn vehicle_attack_sounds(&mut self) {
let full = self.attack_strength_scale() > 0.9;
let player = self.player.as_ref();
let from = player.map(|p| [p.position.x, p.position.y, p.position.z]);
if full && player.is_some_and(|p| p.sprinting) {
self.audio
.play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0);
}
let sound = if full {
"minecraft:entity.player.attack.strong"
} else {
"minecraft:entity.player.attack.weak"
};
self.audio.play(sound, from, 1.0, 1.0);
}
/// Player.attack with the attack-strength charge, crits and knockback.
fn attack(&mut self) -> bool {
if self.spectator() {
@@ -5509,16 +5540,8 @@ impl Game<'_> {
return false;
}
}
let held = self.held().cloned();
let modifiers = held
.as_ref()
.and_then(|h| self.res.items.get(&h.item))
.map(|i| (i.attack_damage, i.attack_speed))
.unwrap_or((0.0, 0.0));
let damage = 1.0 + modifiers.0 + self.effect_attack_bonus();
let speed = (4.0 + modifiers.1).max(0.1);
let delay = 20.0 / speed;
let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
let damage = hand_damage + self.effect_attack_bonus();
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
@@ -9639,6 +9662,8 @@ pub fn run() -> Result<()> {
music: Default::default(),
ambience: Default::default(),
sound_paused: false,
cart_sounds: HashSet::new(),
riding_cart_sounds: None,
dropped: Vec::new(),
next_entity: 0,
particles,
+1
View File
@@ -666,6 +666,7 @@ impl Game<'_> {
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
return false;
}
self.vehicle_attack_sounds();
let b = &mut self.boats[i];
b.hurt_dir = -b.hurt_dir;
b.hurt_time = 10;
@@ -13,6 +13,7 @@ use horizon_client::{
mesher::Vertex,
mobs::{Part, anim::Poses},
particles::{ParticleOptions, ParticleType},
sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds},
};
use horizon_core::{
geometry::{Aabb, Vec3},
@@ -786,6 +787,42 @@ impl Game<'_> {
}
}
}
/// `ClientPacketListener.postAddEntitySoundInstance` for the carts that
/// joined the level since the last tick, and `LocalPlayer.startRiding`'s
/// two inside sounds when the player got in one; then what the sound
/// instances read this tick (the ridden cart and every cart).
pub(super) fn start_cart_sounds(&mut self) -> (Option<u32>, Vec<CartSound>) {
let carts: Vec<CartSound> = self
.carts
.iter()
.map(|c| CartSound {
id: c.id,
position: [c.position.x, c.position.y, c.position.z],
// Vec3.horizontalDistance.
speed: (c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z).sqrt(),
})
.collect();
self.cart_sounds
.retain(|id| carts.iter().any(|c| c.id == *id));
for cart in &carts {
if self.cart_sounds.insert(cart.id) {
let instance = SoundInstance::minecart(cart, SoundEngine::unseeded());
self.audio.play_instance(instance, false);
}
}
let vehicle = self.riding.filter(|id| carts.iter().any(|c| c.id == *id));
if vehicle != self.riding_cart_sounds
&& let Some(cart) = carts.iter().find(|c| Some(c.id) == vehicle)
{
for underwater in [true, false] {
let instance =
SoundInstance::riding_minecart(cart, underwater, SoundEngine::unseeded());
self.audio.play_instance(instance, false);
}
}
self.riding_cart_sounds = vehicle;
(vehicle, carts)
}
/// The rider's tick: the cart moves with the rider's input as its push.
pub(super) fn tick_cart_riding(&mut self, keys: Keys) -> bool {
let Some(i) = self.carts.iter().position(|c| Some(c.id) == self.riding) else {
@@ -1044,6 +1081,7 @@ impl Game<'_> {
let burning = self
.held()
.is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0);
self.vehicle_attack_sounds();
self.hurt_cart(i, damage, self.creative, burning);
self.swing_arm();
true
+4
View File
@@ -28,9 +28,13 @@ impl Game<'_> {
}
self.sound_paused = self.pause;
}
let (vehicle, carts) = self.start_cart_sounds();
let ctx = TickContext {
player_underwater: self.ambience.was_underwater(),
player_removed: self.player.is_none(),
vehicle,
carts,
frozen: !self.clock.runs_normally(),
};
self.audio.tick(self.pause, &ctx);
}
+110 -2
View File
@@ -17,6 +17,7 @@ use std::collections::HashMap;
pub const MASTER: usize = 0;
pub const MUSIC: usize = 1;
pub const RECORDS: usize = 2;
pub const NEUTRAL: usize = 6;
pub const PLAYERS: usize = 7;
pub const AMBIENT: usize = 8;
pub const UI: usize = 10;
@@ -48,12 +49,30 @@ pub enum Ticking {
UnderLiquidLoop { fade: i32 },
/// `UnderLiquidSubSound`.
UnderLiquidSub,
/// `MinecartSoundInstance` following a minecart.
Minecart { cart: u32 },
/// `RidingMinecartSoundInstance` for the player riding a minecart.
RidingMinecart { cart: u32, underwater: bool },
}
/// What tickable instances read about the player.
#[derive(Clone, Copy, Debug, Default)]
/// What a minecart's sound instances read about it.
#[derive(Clone, Copy, Debug)]
pub struct CartSound {
pub id: u32,
pub position: [f64; 3],
/// `getDeltaMovement().horizontalDistance()`.
pub speed: f64,
}
/// What tickable instances read about the player and the entities they follow.
#[derive(Clone, Debug, Default)]
pub struct TickContext {
pub player_underwater: bool,
pub player_removed: bool,
/// The minecart the player rides.
pub vehicle: Option<u32>,
/// The minecarts in the level (a missing one has been removed).
pub carts: Vec<CartSound>,
/// `!tickRateManager().runsNormally()`.
pub frozen: bool,
}
/// `AbstractSoundInstance` and its subclasses' fields.
#[derive(Clone, Debug)]
@@ -247,6 +266,55 @@ impl SoundInstance {
pub fn under_liquid_sub(id: &str, random: LegacyRandom) -> Self {
Self::ambient_loop(id, random, false, Ticking::UnderLiquidSub)
}
/// `new MinecartSoundInstance(minecart)`: silent until the cart rolls.
pub fn minecart(cart: &CartSound, random: LegacyRandom) -> Self {
let [x, y, z] = cart.position;
let mut s = Self::new(
"minecraft:entity.minecart.riding",
NEUTRAL,
0.0,
1.0,
random,
true,
0,
Attenuation::Linear,
[
f64::from(x as f32),
f64::from(y as f32),
f64::from(z as f32),
],
false,
);
s.can_start_silent = true;
s.ticking = Ticking::Minecart { cart: cart.id };
s
}
/// `new RidingMinecartSoundInstance(player, minecart, underwater, event, 0, 0.75, 1)`.
pub fn riding_minecart(cart: &CartSound, underwater: bool, random: LegacyRandom) -> Self {
let id = if underwater {
"minecraft:entity.minecart.inside.underwater"
} else {
"minecraft:entity.minecart.inside"
};
let mut s = Self::new(
id,
NEUTRAL,
0.0,
1.0,
random,
true,
0,
Attenuation::None,
cart.position,
false,
);
s.can_start_silent = true;
s.ticking = Ticking::RidingMinecart {
cart: cart.id,
underwater,
};
s
}
pub fn tickable(&self) -> bool {
self.ticking != Ticking::No
}
@@ -301,6 +369,46 @@ impl SoundInstance {
self.stop();
}
}
Ticking::Minecart { cart } => {
let id = *cart;
let Some(cart) = ctx.carts.iter().find(|c| c.id == id) else {
self.stop();
return;
};
let [x, y, z] = cart.position;
self.position = [
f64::from(x as f32),
f64::from(y as f32),
f64::from(z as f32),
];
// Its own `pitch` field shadows the instance's, which stays 1.
let speed = cart.speed as f32;
self.volume = if speed >= 0.01 && !ctx.frozen {
speed.clamp(0.0, 0.5) * 0.7
} else {
0.0
};
}
Ticking::RidingMinecart { cart, underwater } => {
let (id, underwater) = (*cart, *underwater);
let found = ctx.carts.iter().find(|c| c.id == id);
let Some(cart) = found.filter(|c| ctx.vehicle == Some(c.id)) else {
self.stop();
return;
};
if underwater != ctx.player_underwater {
self.volume = 0.0;
} else {
// Mth.clampedLerp(speed, 0, 0.75), amplified by 1.
let speed = cart.speed as f32;
self.volume = if speed >= 0.01 {
if speed > 1.0 { 0.75 } else { speed * 0.75 }
} else {
0.0
};
self.position = cart.position;
}
}
}
}
/// `LoopSoundInstance.fadeOut`.
@@ -4,13 +4,19 @@ import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.sounds.*;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.TickRateManager;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.vehicle.minecart.Minecart;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
/**
* Drives the real SoundEngine (see VanillaSoundRig) with a script of plays,
@@ -33,6 +39,18 @@ public final class VanillaSoundEngineOracle {
}
}
/** A minecart the minecart sound instances follow. */
public static final class Cart extends Minecart {
Cart() {
super(null, null);
}
@Override
public boolean isSilent() {
return false;
}
}
static float f(String hex) {
return Float.intBitsToFloat(Integer.parseUnsignedInt(hex, 16));
}
@@ -53,6 +71,10 @@ public final class VanillaSoundEngineOracle {
Constructor<UnderLiquidSubSound> sub = UnderLiquidSubSound.class.getDeclaredConstructor(LocalPlayer.class, SoundEvent.class);
sub.setAccessible(true);
var instances = new TreeMap<String, SoundInstance>();
var carts = new TreeMap<String, Cart>();
var level = VanillaSoundRig.make(ClientLevel.class);
var tickRate = new TickRateManager();
VanillaSoundRig.set(level, ClientLevel.class, "tickRateManager", tickRate);
var manager = rig.manager;
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2])))) {
for (String line : Files.readAllLines(Path.of(args[1]))) {
@@ -72,6 +94,9 @@ public final class VanillaSoundEngineOracle {
case "loop" -> new BiomeAmbientSoundsHandler.LoopSoundInstance(event);
case "uloop" -> new UnderLiquidAmbientSoundInstance(event, actor, LocalPlayer::isUnderWater);
case "usub" -> sub.newInstance(actor, event);
case "cart" -> new MinecartSoundInstance(carts.get(a[3]));
case "rcart", "rcartu" -> new RidingMinecartSoundInstance(actor, carts.get(a[3]), a[2].equals("rcartu"),
a[2].equals("rcartu") ? SoundEvents.MINECART_INSIDE_UNDERWATER : SoundEvents.MINECART_INSIDE, 0.0F, 0.75F, 1.0F);
default -> throw new IllegalArgumentException(line);
};
if (!a[2].equals("simple")) seed(instance, seed);
@@ -99,6 +124,23 @@ public final class VanillaSoundEngineOracle {
actor.underwater = a[1].equals("1");
VanillaSoundRig.set(actor, Entity.class, "removalReason", a[2].equals("1") ? Entity.RemovalReason.DISCARDED : null);
}
case "cart" -> {
// cart name x y z dx dy dz removed
Cart cart = carts.get(a[1]);
if (cart == null) {
cart = VanillaSoundRig.make(Cart.class);
VanillaSoundRig.set(cart, Entity.class, "level", level);
carts.put(a[1], cart);
}
VanillaSoundRig.set(cart, Entity.class, "position", new Vec3(d(a[2]), d(a[3]), d(a[4])));
VanillaSoundRig.set(cart, Entity.class, "deltaMovement", new Vec3(d(a[5]), d(a[6]), d(a[7])));
VanillaSoundRig.set(cart, Entity.class, "removalReason", a[8].equals("1") ? Entity.RemovalReason.DISCARDED : null);
}
case "ride" -> VanillaSoundRig.set(actor, Entity.class, "vehicle", a[1].equals("-") ? null : carts.get(a[1]));
case "freeze" -> {
tickRate.setFrozen(a[1].equals("1"));
tickRate.tick();
}
case "tick" -> manager.tick(a[1].equals("1"));
case "forget" -> instances.remove(a[1]);
default -> throw new IllegalArgumentException(line);
+50 -4
View File
@@ -3,9 +3,10 @@
The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No
Output" device (see VanillaSoundRig) and replays scripts of plays (simple,
biome loop, underwater loop and sub-sound instances), stops (by instance, by
sound and/or source, all), category gains, source volume options and
refreshes, channel ends, delayed and queued sounds, pauses and client ticks.
biome loop, underwater loop, sub-sound, minecart and riding-minecart
instances), stops (by instance, by sound and/or source, all), category gains,
source volume options and refreshes, channel ends, delayed and queued sounds,
pauses, minecart states and client ticks.
After every step it prints each instance's `isActive` and the AL source the
engine configured (state, gain, pitch, position, relative, looping, distance
model, max distance, rolloff, reference distance), the subtitle notifications
@@ -13,6 +14,7 @@ and the channel pool counts. Horizon's `SoundEngine` replays the scripts
against a backend that records the same AL source fields.
"""
import json
import math
import random
try:
@@ -38,6 +40,9 @@ class Script:
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay,
'linear' if linear else 'none', relative, seed)
def cart(self, name, at, delta, removed=0):
self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed)
def tick(self, n=1, paused=0):
for _ in range(n):
self.add('tick', paused)
@@ -117,6 +122,30 @@ def scripted(s):
s.tick(3)
s.add('player', 0, 0)
s.reset()
# Minecarts: the rolling sound and the two riding sounds, by speed,
# underwater, frozen ticks, getting out and the cart's removal.
s.cart('k', (10.3, 64.0, 5.7), (0.0, 0.0, 0.0))
s.play('m', 'k', kind='cart', seed=61)
s.tick(2)
for i, v in enumerate([0.005, 0.0099, 0.01, 0.1, 0.3, 0.5, 0.51, 0.8, 1.0, 1.2, 2.0, 0.0]):
s.cart('k', (10.3 + i * 0.37123, 64.0625, 5.7 - i * 0.1), (v * 0.6, -0.04, v * 0.8))
s.tick(2)
if i == 4:
s.add('freeze', 1)
s.tick(3)
s.add('freeze', 0)
s.add('ride', 'k')
s.play('r', 'k', kind='rcartu', seed=62)
s.play('i', 'k', kind='rcart', seed=63)
if i == 8:
s.add('player', 1, 0)
s.tick(3)
s.add('player', 0, 0)
s.add('ride', '-')
s.tick(3)
s.cart('k', (1.0, 2.0, 3.0), (0.2, 0.0, 0.0), removed=1)
s.tick(3)
s.reset()
# Queued tickables, delayed and manually looped sounds.
s.play('q', loop, kind='loop', seed=31)
s.add('stop', 'q')
@@ -173,6 +202,10 @@ def scripted(s):
def fuzz(s, rng, steps):
names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5']
live = set()
for cart in ('k0', 'k1'):
s.cart(cart, (0.0, 64.0, 0.0), (0.0, 0.0, 0.0))
s.add('ride', '-')
s.add('freeze', 0)
for _ in range(steps):
op = rng.random()
name = rng.choice(names)
@@ -210,6 +243,18 @@ def fuzz(s, rng, steps):
elif op < 0.57:
s.add('forget', name)
live.discard(name)
elif op < 0.62:
speed = rng.choice([0.0, 0.005, 0.01, 0.3, 0.5, 1.0, rng.uniform(0, 1.5)])
angle = rng.uniform(0, 6.3)
at = (rng.uniform(-50, 50), rng.uniform(0, 80), rng.uniform(-50, 50))
s.cart(rng.choice(['k0', 'k1']), at, (speed * math.cos(angle), rng.uniform(-0.1, 0.1), speed * math.sin(angle)), int(rng.random() < 0.08))
elif op < 0.65:
s.add('ride', rng.choice(['k0', 'k1', '-']))
elif op < 0.66:
s.add('freeze', int(rng.random() < 0.5))
elif op < 0.70:
s.play(name, rng.choice(['k0', 'k1']), kind=rng.choice(['cart', 'rcart', 'rcartu']), seed=rng.getrandbits(63))
live.add(name)
else:
s.tick(rng.randrange(1, 6))
@@ -238,7 +283,8 @@ def main():
'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear '
'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, '
'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, '
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. '
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, MinecartSoundInstance and RidingMinecartSoundInstance ticks (speed, '
'riding, underwater, frozen ticks, removal), subtitle notifications and ranges, and the 247/8 channel pools. '
'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.')
print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True)