From f1cc118df0570604b1db2828da20cd67c39411a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:10:25 +0200 Subject: [PATCH] Feeding sounds: each animal's own eating sound, or none, as in vanilla Animal.mobInteract plays playEatingSound(), which is empty in Animal and overridden only by armadillos, cats, foxes, frogs, goats, pigs, sniffers and sulfur cubes (plus nautili). Horizon fell back to entity.generic.eat for every other animal (cows, sheep, chickens, rabbits, turtles, bees...), with a level random pitch instead of each class's volume and pitch. - mobs::ai::eating_sound: the overrides with their exact volume and pitch (makeSound with the voice pitch, playSound(1, 1), or Level.playSound with Mth.randomBetween(0.8, 1.2)); silent otherwise. - mobs::ai::feed_animal: Animal.mobInteract's food part, shared by the game and the mob AI probe; Strider.mobInteract adds entity.strider.eat. - AgeableMob.ageUp(seconds, true): forcedAge and the forced-age particle timer, whose positions draw from the mob's random on the server. - Tame wolves and cats healed with food: TamableAnimal.feed (wolves silent). - Parrots: Parrot.isFood is false; wild ones take parrot food with entity.parrot.eat and a one-in-ten taming chance. - Baby pigs and chickens use their sound variant's baby_sounds. The mob AI harness gains a `feed TICK MOB ITEM` event (the oracle calls the real Animal.mobInteract) and feeding scenarios for adult and baby cows, pigs, sheep and chickens. Fixes #68 Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 17 +++ crates/horizon-client/src/entity_nbt.rs | 2 + crates/horizon-client/src/game/creatures.rs | 76 +++++++----- crates/horizon-client/src/game/nautili.rs | 4 +- crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/ai.rs | 110 +++++++++++++++++- .../horizonlab/parity/VanillaMobAiOracle.java | 15 +++ tools/test_mob_ai_parity.py | 10 ++ 8 files changed, 205 insertions(+), 34 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 40527b810..f90fbfc3e 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -56,6 +56,9 @@ struct Scenario { spawning: bool, /// The player hits a mob for 1 at the start of a tick: (tick, mob index). hurts: Vec<(i32, usize)>, + /// The player feeds an animal at the start of a tick (Animal.mobInteract): + /// (tick, mob index); the scenario only feeds each animal its food. + feeds: Vec<(i32, usize)>, hand: Option, mobs: Vec, } @@ -92,6 +95,7 @@ fn parse(text: &str) -> Vec { } "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), + "feed" => s.feeds.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { s.player = Some([ f[1].parse().unwrap(), @@ -893,6 +897,9 @@ fn main() -> horizon_client::Result<()> { } }); let mut scratch = LegacyRandom::new(0); + // The level's random for eating sounds: only goats and sniffers draw + // from it, and the scenarios feed neither. + let mut level_random = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m, s.creative); } @@ -996,6 +1003,16 @@ fn main() -> horizon_client::Result<()> { } events.append(&mut mobs[i].outbox); } + for &(tick, i) in &s.feeds { + if tick != t || i >= mobs.len() || mobs[i].removed { + continue; + } + if let Some(Some((name, volume, pitch))) = + horizon_client::mobs::ai::feed_animal(&mut mobs[i], &mut level_random) + { + events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch)); + } + } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 64cbe15ba..51948cc72 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -156,6 +156,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { if m.kind.category == "creature" && aged { map.insert("Age".into(), Tag::Int(m.extra.age)); map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked))); + map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age)); for (key, value) in [ ("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), @@ -589,6 +590,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.custom_name = custom_name(tag); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; + m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } m.name_visible = flag(tag, "CustomNameVisible"); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 27b48a15f..82338433d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -11,6 +11,7 @@ use horizon_client::{ mesher::Vertex, mobs::{ Damage, DamageKind, Mob, MobEvent, MobWorld, PlayerView, Seen, SpawnSetup, Species, Who, + ai::{eating_sound, feed_animal}, farm::Climate, spawning::{self, BiomeFacts}, }, @@ -1844,6 +1845,9 @@ impl Game<'_> { let mut consume = false; let mut give: Option<&str> = None; let mut sound: Option<&str> = None; + // Sounds played as vanilla plays them: (event, volume, pitch) at the feet. + let mut eat: Option<(&'static str, f32, f32)> = None; + let feet = [m.position.x, m.position.y, m.position.z]; let mut handled = true; let mut drops: Vec<(String, u32)> = Vec::new(); let is_food = m.kind.food.contains(&item); @@ -1919,9 +1923,9 @@ impl Game<'_> { .get(&item) .and_then(|i| i.food.as_ref()) .map_or(2.0, |f| f.0 as f32); + // TamableAnimal.feed: playEatingSound, which wolves leave empty. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; - sound = Some("entity.wolf.eat"); } Species::Wolf if m.extra.tame @@ -2023,9 +2027,10 @@ impl Game<'_> { .get(&item) .and_then(|i| i.food.as_ref()) .map_or(1.0, |f| f.0 as f32); + // TamableAnimal.feed. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; - sound = Some("entity.cat.eat"); + eat = eating_sound(m, &mut self.world.random); } Species::Cat if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => @@ -2038,7 +2043,6 @@ impl Game<'_> { } Species::Cat if !m.extra.tame && is_food => { consume = true; - sound = Some("entity.cat.eat"); m.persistent = true; let at = [ m.position.x, @@ -2051,6 +2055,7 @@ impl Game<'_> { m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); m.extra.sitting = true; } + eat = eating_sound(m, &mut self.world.random); let kind = if tamed { "heart" } else { "smoke" }; self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; if tamed { @@ -2076,25 +2081,45 @@ impl Game<'_> { sound = Some("item.flintandsteel.use"); self.damage_held_tool(); } + // Parrot.mobInteract: parrot food may tame a wild one (one time in + // ten); a parrot never takes it as Animal food (isFood is false). + Species::Parrot if !m.extra.tame && is_food => { + consume = true; + if !m.silent { + let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; + eat = Some(("entity.parrot.eat", 1.0, pitch)); + } + let at = [ + m.position.x, + m.position.y + f64::from(m.height()) * 0.5 + 0.5, + m.position.z, + ]; + let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0; + if tamed { + m.extra.tame = true; + m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + } + let kind = if tamed { "heart" } else { "smoke" }; + self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?; + if tamed { + let view = self.mob_entity(&self.mobs[index]); + self.trigger_entity("minecraft:tame_animal", "entity", &view); + } + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal + && species != Species::Parrot && (species != Species::HappyGhast || m.is_baby()) => { - // Animal.mobInteract: breed adults, speed up babies. - if m.extra.age == 0 && m.extra.in_love <= 0 { - m.extra.in_love = 600; - m.extra.love_player = true; - consume = true; - sound = Some(eat_sound(species)); - } else if m.extra.age < 0 { - // AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age)) = 10%. - let secs = (-m.extra.age / 20) as f32 * 0.1; - m.extra.age = (m.extra.age + (secs as i32) * 20).min(0); - consume = true; - sound = Some(eat_sound(species)); - } else { - handled = false; + // Animal.mobInteract: breed adults, speed up babies, then + // playEatingSound (silent unless the species overrides it). + match feed_animal(m, &mut self.world.random) { + Some(sound) => { + consume = true; + eat = sound; + } + None => handled = false, } } _ => handled = false, @@ -2109,6 +2134,10 @@ impl Game<'_> { self.audio .play(&format!("minecraft:{s}"), Some(center), 1.0, pitch); } + if let Some((s, volume, pitch)) = eat { + self.audio + .play(&format!("minecraft:{s}"), Some(feet), volume, pitch); + } if consume && !creative && let Some(stack) = self.inventory[selected].as_mut() @@ -2485,19 +2514,6 @@ impl Game<'_> { } } } -fn eat_sound(s: Species) -> &'static str { - match s { - Species::Pig => "entity.pig.eat", - Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat", - Species::Llama | Species::TraderLlama => "entity.llama.eat", - Species::Goat => "entity.goat.eat", - Species::Sniffer => "entity.sniffer.eat", - Species::Fox => "entity.fox.eat", - Species::Cat => "entity.cat.eat", - Species::Panda => "entity.panda.eat", - _ => "entity.generic.eat", - } -} /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index 2a7687dc3..592416630 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -59,8 +59,8 @@ impl Game<'_> { } let m = &mut self.mobs[index]; if !m.extra.age_locked { - let secs = (-m.extra.age / 20) as f32 * 0.1; - m.extra.age = (m.extra.age + (secs as i32) * 20).min(0); + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, secs, true); } let sound = nautilus::eat_sound(m); self.use_nautilus_food(item); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f8ebca55c..195bf536f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -619,6 +619,11 @@ pub struct Extra { pub age: i32, /// `AgeLocked` (tadpoles fed a slime ball... and ageable mobs). pub age_locked: bool, + /// AgeableMob.forcedAge: the age fed food added, restored as the age + /// when it reaches 0 (`ForcedAge`). + pub forced_age: i32, + /// AgeableMob.forcedAgeTimer: ticks of happy villager particles left. + pub forced_age_timer: i32, pub in_love: i32, pub love_player: bool, /// Texture/model variant index (cat type, horse colour, rabbit type...). diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0338c6b1..f3045a8b1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -555,7 +555,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", Species::Piglin if m.ai.target.is_some() => "entity.piglin.angry", Species::Hoglin if m.ai.target.is_some() => "entity.hoglin.angry", - _ => m.kind.sounds[0], + _ => voice_sounds(m)[0], }; let _ = w; if !sound.is_empty() { @@ -617,7 +617,23 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.kind.flags.climber { m.climbing = m.horizontal_collision; } - // AgeableMob.aiStep + // AgeableMob.aiStep: a forced age-up's particles (positions drawn on the + // server too), then the age. + if m.extra.forced_age_timer > 0 { + if m.extra.forced_age_timer % 4 == 0 { + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + let r = &mut m.random; + let x = m.position.x + w * (2.0 * r.next_double() - 1.0); + let y = m.position.y + h * r.next_double() + 0.5; + let z = m.position.z + w * (2.0 * r.next_double() - 1.0); + events.push(MobEvent::Particles { + kind: "happy_villager", + at: [x, y, z], + count: 1, + }); + } + m.extra.forced_age_timer -= 1; + } if m.alive() { if m.extra.age < 0 { let (bw, bh, _) = m.dims(); @@ -977,9 +993,99 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] { match m.species() { Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m), Species::SulfurCube => super::sulfur_cube::sounds(m), + // The sound variant's baby_sounds (classic sets, like the rest here). + Species::Pig if m.is_baby() => [ + "entity.baby_pig.ambient", + "entity.baby_pig.hurt", + "entity.baby_pig.death", + ], + Species::Chicken if m.is_baby() => [ + "entity.baby_chicken.ambient", + "entity.baby_chicken.hurt", + "entity.baby_chicken.death", + ], _ => m.kind.sounds, } } +/// `Animal.mobInteract` with its food in hand: an adult that can fall in +/// love does, a baby grows up by a tenth, and either plays its eating sound +/// (`Strider.mobInteract` plays its own afterwards). `None` when the animal +/// does not take the food; otherwise the sound to play, if any. +pub fn feed_animal( + m: &mut Mob, + level: &mut impl RandomSource, +) -> Option> { + if m.extra.age == 0 && m.extra.in_love <= 0 { + m.extra.in_love = 600; + m.extra.love_player = true; + } else if m.extra.age < 0 { + // AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age), true): a tenth. + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + age_up(m, secs, true); + } else { + return None; + } + let mut sound = eating_sound(m, level); + if m.species() == Species::Strider && !m.silent { + let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; + sound = Some(("entity.strider.eat", 1.0, pitch)); + } + Some(sound) +} +/// `AgeableMob.ageUp(seconds, forced)`. +pub fn age_up(m: &mut Mob, seconds: i32, forced: bool) { + let age = m.extra.age; + let grown = (age + seconds * 20).min(0); + m.extra.age = grown; + if forced { + m.extra.forced_age += grown - age; + if m.extra.forced_age_timer == 0 { + m.extra.forced_age_timer = 40; + } + } + if m.extra.age == 0 { + m.extra.age = m.extra.forced_age; + } +} +/// `Animal.playEatingSound` (empty) and its overrides, as (sound, volume, +/// pitch); `level` is the level's random. Pigs and cats use the classic sound +/// set, like their other sounds here. +pub fn eating_sound( + m: &mut Mob, + level: &mut impl RandomSource, +) -> Option<(&'static str, f32, f32)> { + let baby = m.is_baby(); + // Mth.randomBetween(level.getRandom(), 0.8, 1.2). + let mut between = || level.next_float() * 0.4 + 0.8; + let (sound, volume, pitch, entity_sound) = match m.species() { + // makeSound: getSoundVolume, getVoicePitch. + Species::Armadillo | Species::Pig | Species::SulfurCube => { + let sound = match m.species() { + Species::Armadillo => "entity.armadillo.eat", + Species::Pig if baby => "entity.baby_pig.eat", + Species::Pig => "entity.pig.eat", + _ => "entity.small_sulfur_cube.eat", + }; + let pitch = m.voice_pitch(); + (sound, sound_volume(m), pitch, true) + } + // playSound(sound, 1, 1). + Species::Cat if baby => ("entity.baby_cat.eat", 1.0, 1.0, true), + Species::Cat => ("entity.cat.eat", 1.0, 1.0, true), + Species::Fox => ("entity.fox.eat", 1.0, 1.0, true), + // level().playSound(null, this, sound, NEUTRAL, volume, pitch). + Species::Frog => ("entity.frog.eat", 2.0, 1.0, false), + Species::Goat if m.extra.screaming => ("entity.goat.screaming.eat", 1.0, between(), false), + Species::Goat => ("entity.goat.eat", 1.0, between(), false), + Species::Sniffer => ("entity.sniffer.eat", 1.0, between(), false), + _ => return None, + }; + // Entity.playSound is skipped for a silent entity. + if entity_sound && m.silent { + return None; + } + Some((sound, volume, pitch)) +} pub fn sound_volume(m: &Mob) -> f32 { match m.species() { Species::Ghast => 5.0, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 1b57e7690..6b034411b 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -184,6 +184,9 @@ public final class VanillaMobAiOracle { boolean spawning; /** The player hits a mob for 1 at the start of a tick: {tick, mob index}. */ List hurts = new ArrayList<>(); + /** The player feeds an animal at the start of a tick (Animal.mobInteract with the item in + * its main hand): {tick, mob index, item id}. */ + List feeds = new ArrayList<>(); } static void parse(Path path) throws Exception { @@ -220,6 +223,7 @@ public final class VanillaMobAiOracle { } case "heart" -> s.hearts.add(f); case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])}); + case "feed" -> s.feeds.add(new Object[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), f[3]}); case "player" -> { s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; for (int i = 4; i < f.length; i++) { @@ -713,6 +717,17 @@ public final class VanillaMobAiOracle { if (hurt[0] == t && hurt[1] < ENTS.size() && ENTS.get(hurt[1]) instanceof LivingEntity hurtMob && !hurtMob.isRemoved()) hurtMob.hurtServer(level, level.damageSources().playerAttack(player), 1.0F); } + for (Object[] feed : s.feeds) { + int index = (Integer) feed[1]; + if ((Integer) feed[0] != t || index >= ENTS.size() + || !(ENTS.get(index) instanceof net.minecraft.world.entity.animal.Animal animal) || animal.isRemoved()) continue; + var hand = net.minecraft.world.InteractionHand.MAIN_HAND; + var held = player.getItemInHand(hand); + player.setItemInHand(hand, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse((String) feed[2])), 64)); + animal.mobInteract(player, hand); + player.setItemInHand(hand, held); + } for (Entity e : List.copyOf(ENTS)) { if (e.isRemoved()) continue; e.checkDespawn(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 524d69d3f..d2f69c07e 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -208,6 +208,16 @@ def scenarios(): add('golem_part_full', 500, [chest(-3, 1, 'cobblestone*60,cobblestone*64,-,cobblestone*63'), 'mob minecraft:copper_golem 0.5 -60 0.5 0 117 persistent cooldown=0 hand=cobblestone*16']) add('golem_idle', 400, ['player 4.5 -60 2.5', 'mob minecraft:copper_golem 0.5 -60 0.5 0 118 persistent']) + # The player feeds animals their food (Animal.mobInteract): an adult falls in love once, a baby + # grows each time, and each plays its own eating sound or none (Animal.playEatingSound). + for species, food, seed in [('cow', 'wheat', 120), ('pig', 'carrot', 121), ('sheep', 'wheat', 122), + ('chicken', 'wheat_seeds', 123)]: + for baby in ('', ' baby'): + add(f'feed_{species}{baby.replace(" ", "_")}', 80, [ + 'player 3.5 -60 0.5', + f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent{baby}', + f'feed 20 0 minecraft:{food}', f'feed 40 0 minecraft:{food}', + ]) return s