diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 80e994288..2ce6f43c5 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -9,8 +9,13 @@ use horizon_client::{ blocks::BlockFacts, chunk::{Chunk, HEIGHT, MIN_Y}, collisions, + containers::{BlockEntity, CreakingHeart}, items::Items, light::{LightTables, light_chunk}, + mobs::{ + Damage, MobType, creaking, + creaking_heart::{self, HeartEvent, HeartHost}, + }, mobs::{ Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who, control::Operation, spawning::LocalDifficulty, @@ -45,6 +50,12 @@ struct Scenario { creative: bool, /// The tick from which the player faces another yaw. turn: Option<(i32, f32)>, + /// Creaking hearts placed when the scenario starts. + hearts: Vec>, + /// `ServerLevel.isSpawningMonsters`. + spawning: bool, + /// The player hits a mob for 1 at the start of a tick: (tick, mob index). + hurts: Vec<(i32, usize)>, mobs: Vec, } @@ -69,12 +80,15 @@ fn parse(text: &str) -> Vec { "rain" => s.rain = true, "thunder" => s.thunder = true, "levelseed" => {} + "spawning" => s.spawning = true, _ => panic!("unknown scenario option {kv}"), } } } "origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()], "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), + "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { s.player = Some([ f[1].parse().unwrap(), @@ -251,6 +265,91 @@ fn seen(m: &Mob) -> Seen { } } +/// The probe's mobs as a creaking heart sees them: creakings it creates take +/// the n-th seed from 1000, as the oracle's do. +struct Host<'a> { + mobs: &'a mut Vec, + added: Vec, + types: &'a MobTypes, + created: &'a mut i64, + spawning: bool, +} +impl HeartHost for Host<'_> { + fn mob(&self, id: u32) -> Option<&Mob> { + self.mobs + .iter() + .chain(self.added.iter()) + .find(|m| m.id == id) + } + fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> { + self.mobs + .iter_mut() + .chain(self.added.iter_mut()) + .find(|m| m.id == id) + } + fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option { + self.mob(uuid[3] as u32) + .filter(|m| !m.removed) + .map(|m| m.id) + } + fn uuid_for(&mut self, id: u32) -> [i32; 4] { + [0, 0, 0, id as i32] + } + fn creaking_type(&self) -> Option> { + self.types + .types + .get("minecraft:creaking") + .map(|t| Arc::new(t.clone())) + } + fn create_mob(&mut self, kind: Arc, at: Vec3) -> Mob { + let seed = 1000 + *self.created; + *self.created += 1; + let mut m = Mob::new(200_000 + seed as u32, kind, at, 0.0); + m.random = LegacyRandom::new(seed); + horizon_client::mobs::monster_brain::init(&mut m, seed); + m + } + fn add_mob(&mut self, m: Mob) { + self.added.push(m); + } + fn spawning_monsters(&self) -> bool { + self.spawning + } +} +/// The heart's state, block entity and the level random, as the oracle +/// prints them. +fn print_heart( + out: &mut String, + t: i32, + registry: &BlockRegistry, + world: &World, + at: [i32; 3], + heart: &CreakingHeart, + lr: &LegacyRandom, +) { + let state = registry + .state(world.block(at[0], at[1], at[2])) + .and_then(|s| s.properties.get("creaking_heart_state").cloned()) + .unwrap_or_default(); + let _ = writeln!( + out, + "{t} heart {},{},{}\t{state}\t{} {} {} {} {}\tlrng {:x}", + at[0], + at[1], + at[2], + heart.ticker, + heart.emitter, + heart.output_signal, + heart.ticks_existed, + if heart.creaking.is_some() { + "linked" + } else { + "none" + }, + lr.state() + ); +} + /// Whether an event hurts the scenario's player (survival, normal difficulty, /// no armour, made hurtable again every tick by the oracle). fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { @@ -438,6 +537,17 @@ fn main() -> horizon_client::Result<()> { } } } + let mut hearts: Vec<([i32; 3], CreakingHeart)> = Vec::new(); + for h in &s.hearts { + let at = [ + h[1].parse::().unwrap(), + h[2].parse::().unwrap(), + h[3].parse::().unwrap(), + ]; + world.set(at[0], at[1], at[2], state(registry, &h[4]))?; + hearts.push((at, CreakingHeart::default())); + } + let mut created = 0_i64; let keys: Vec<(i32, i32)> = world.chunks.keys().copied().collect(); let lit: Vec<((i32, i32), Chunk)> = keys .iter() @@ -534,6 +644,14 @@ fn main() -> horizon_client::Result<()> { } for t in 1..=s.ticks { world.game_time += 1; + let mut heart_events_later: Vec = Vec::new(); + // Creaking.tick reads the heart's block entity. + for (at, h) in &hearts { + world.block_entities.insert( + (at[0], at[1], at[2]), + BlockEntity::CreakingHeart(Box::new(h.clone())), + ); + } if let (Some(p), Some((tick, yaw))) = (player.as_mut(), s.turn) && t >= tick { @@ -571,6 +689,51 @@ fn main() -> horizon_client::Result<()> { sea_level: -63, }; let mut events = Vec::new(); + let mut heart_events = Vec::new(); + let mut added = Vec::new(); + for &(tick, i) in &s.hurts { + if tick != t || i >= mobs.len() || mobs[i].removed { + continue; + } + let at = player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]); + mobs[i].damage(1.0, Damage::player(at)); + // Creaking.hurtServer: the heart's reaction, then the sway. + if let Some((home, by_player)) = creaking::take_hurt(&mut mobs[i], &w) { + if by_player && let Some((_, h)) = hearts.iter_mut().find(|(at, _)| *at == home) + { + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + types: &types, + created: &mut created, + spawning: s.spawning, + }; + creaking_heart::creaking_hurt( + h, + home, + &w, + &mut scratch, + &mut host, + &mut heart_events, + ); + added.append(&mut host.added); + } + for e in heart_events.drain(..) { + match e { + HeartEvent::Sound(name, _, volume, pitch) => { + events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch)) + } + HeartEvent::SetBlock(..) => heart_events_later.push(e), + HeartEvent::Mob(ev) => events.push(ev), + _ => {} + } + } + creaking::sway(&mut mobs[i], &mut events); + } + events.append(&mut mobs[i].outbox); + } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); @@ -599,6 +762,38 @@ fn main() -> horizon_client::Result<()> { for m in &mut mobs { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } + // ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted). + heart_events.append(&mut heart_events_later); + for (at, h) in &mut hearts { + let uprooted = registry + .state(w.world.block(at[0], at[1], at[2])) + .and_then(|s| s.properties.get("creaking_heart_state").cloned()) + .is_some_and(|v| v == "uprooted"); + if uprooted { + continue; + } + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + types: &types, + created: &mut created, + spawning: s.spawning, + }; + creaking_heart::server_tick(h, *at, &w, &mut scratch, &mut host, &mut heart_events); + added.append(&mut host.added); + } + drop(w); + mobs.append(&mut added); + for e in &heart_events { + match e { + HeartEvent::SetBlock(at, st) => world.set(at[0], at[1], at[2], *st)?, + HeartEvent::Sound(name, _, volume, pitch) => { + events.push(MobEvent::Sound(name, [0.0; 3], *volume, *pitch)) + } + HeartEvent::Mob(ev) => events.push(ev.clone()), + _ => {} + } + } for (i, m) in mobs.iter().enumerate() { print(&mut out, t, i, m); } @@ -621,6 +816,9 @@ fn main() -> horizon_client::Result<()> { ); } } + for (at, h) in &hearts { + print_heart(&mut out, t, registry, &world, *at, h, &scratch); + } for line in traces { let _ = writeln!(out, "{line}"); } diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 98727ba8b..6147b419d 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -1,37 +1,29 @@ -//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an -//! awake heart in a pale oak trunk spawns a creaking that protects it, -//! hurting the creaking makes the heart emit trails and spread resin over -//! the logs, and breaking the heart tears the creaking down. -use super::Game; +//! The creaking heart block entity in the game: `mobs::creaking_heart` +//! ticks each heart (spawning, letting go of and bleeding for its creaking) +//! and this applies what it reports to the world, the mobs and the speakers. +use super::{Game, creatures::seen}; use horizon_client::{ Result, containers::{BlockEntity, CreakingHeart}, - mobs::creaking, + mobs::{ + Mob, MobType, + creaking_heart::{self, HeartEvent, HeartHost}, + }, particles::{ParticleOptions, ParticleType}, }; -use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource}; +use horizon_core::{ + geometry::Vec3, + position::BlockPos, + random::{LegacyRandom, RandomSource}, +}; use horizon_world::registry::BlockStateId; -use std::collections::{HashSet, VecDeque}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; type Pos = (i32, i32, i32); -/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`. -const ORANGE: u32 = 16_545_810; -const GRAY: u32 = 6_250_335; -/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`. -const TOO_FAR: f64 = 34.0; - -/// `Direction.values()`: down, up, north, south, west, east. -const DIRECTIONS: [[i32; 3]; 6] = [ - [0, -1, 0], - [0, 1, 0], - [0, 0, -1], - [0, 0, 1], - [-1, 0, 0], - [1, 0, 0], -]; -const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; - /// Comparator input of a heart (`getAnalogOutputSignal`). pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option { match world.block_entities.get(&(pos.x, pos.y, pos.z))? { @@ -40,6 +32,59 @@ pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) } } +/// The game's mobs as a heart sees them, taken out of the game for the tick. +struct Host<'a> { + mobs: &'a mut Vec, + added: Vec, + uuids: &'a mut HashMap, + creaking: Option>, + next_entity: &'a mut u32, + spawning: bool, +} +impl HeartHost for Host<'_> { + fn mob(&self, id: u32) -> Option<&Mob> { + self.mobs + .iter() + .chain(self.added.iter()) + .find(|m| m.id == id && !m.removed) + } + fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> { + self.mobs + .iter_mut() + .chain(self.added.iter_mut()) + .find(|m| m.id == id && !m.removed) + } + fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option { + self.uuids + .iter() + .find(|(id, u)| **u == uuid && self.mob(**id).is_some()) + .map(|(id, _)| *id) + } + fn uuid_for(&mut self, id: u32) -> [i32; 4] { + *self + .uuids + .entry(id) + .or_insert_with(horizon_client::save::random_uuid) + } + fn creaking_type(&self) -> Option> { + self.creaking.clone() + } + fn create_mob(&mut self, kind: Arc, at: Vec3) -> Mob { + *self.next_entity += 1; + // A new entity's random is its own (Mob::new seeds it). + let mut m = Mob::new(*self.next_entity, kind, at, 0.0); + let seed = i64::from(m.id); + horizon_client::mobs::monster_brain::init(&mut m, seed); + m + } + fn add_mob(&mut self, m: Mob) { + self.added.push(m); + } + fn spawning_monsters(&self) -> bool { + self.spawning + } +} + impl Game<'_> { fn heart_state_name(&self, state: BlockStateId) -> String { self.res @@ -49,204 +94,75 @@ impl Game<'_> { .and_then(|s| s.properties.get("creaking_heart_state").cloned()) .unwrap_or_default() } - /// `Util.shuffledCopy(Direction.values(), random)`. - fn shuffled_directions(&mut self) -> [usize; 6] { - let mut order = [0, 1, 2, 3, 4, 5]; - for i in (2..=6).rev() { - let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize; - order.swap(i - 1, j); - } - order - } - fn is_pale_oak_log(&self, p: Pos) -> bool { - let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name; - self.res - .items - .block_tags - .get("minecraft:pale_oak_logs") - .is_some_and(|s| s.contains(&**name)) - } - fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> { - let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?; - Some((m.center(), m.bounds())) - } - /// The protector's entity, resolving a UUID read from a save. - fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option { - let (id, uuid) = heart.creaking?; - if let Some(id) = id { - if self.mobs.iter().any(|m| m.id == id && !m.removed) { - return Some(id); - } - // The entity is gone: remember it by UUID until it reappears. - heart.creaking = Some((None, uuid)); - } - if let Some(id) = self.mob_id_for_uuid(uuid) { - heart.creaking = Some((Some(id), uuid)); - return Some(id); - } - if heart.ticks_existed >= 30 { - heart.creaking = None; - } - None - } - /// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart. - fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) { - let Some(id) = self.heart_protector(heart) else { - return; + /// Runs `f` on the heart at `key` with the game's mobs and level random, + /// then applies what the heart reported. + fn with_heart( + &mut self, + key: Pos, + heart: &mut CreakingHeart, + f: impl FnOnce( + &mut CreakingHeart, + &horizon_client::mobs::MobWorld, + &mut LegacyRandom, + &mut Host, + &mut Vec, + ), + ) -> Result<()> { + let mut mobs = std::mem::take(&mut self.mobs); + let mut uuids = std::mem::take(&mut self.persist.uuids); + let mut next_entity = self.next_entity; + let mut random = self.world.random.clone(); + let spawning = self.spawning_monsters(); + let creaking = self.res.mob_types.get("minecraft:creaking").cloned(); + let player_uuid = self.level.player_uuid; + let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect(); + let mut events = Vec::new(); + let added = { + let w = self.mob_world_base(&snapshot); + let mut host = Host { + mobs: &mut mobs, + added: Vec::new(), + uuids: &mut uuids, + creaking, + next_entity: &mut next_entity, + spawning, + }; + f(heart, &w, &mut random, &mut host, &mut events); + host.added }; - if by_player { - // creakingDeathEffects: a twitching death. - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - creaking::set_tearing_down(m); - m.health = 0.0; - m.death_time = m.death_time.max(0); - let at = m.center(); - self.audio - .play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0); - } - } else if let Some(i) = self.mobs.iter().position(|m| m.id == id) { - let mut events = Vec::new(); - creaking::tear_down(&mut self.mobs[i], &mut events); - let _ = self.handle_mob_events(events); - } - heart.creaking = None; - } - fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 { - self.mob_center(id).map_or(0.0, |_| { - let m = self.mobs.iter().find(|m| m.id == id).unwrap(); - let at = ( - f64::from(pos.0) + 0.5, - f64::from(pos.1), - f64::from(pos.2) + 0.5, - ); - ((m.position.x - at.0).powi(2) - + (m.position.y - at.1).powi(2) - + (m.position.z - at.2).powi(2)) - .sqrt() - }) - } - /// `emitParticles`: trails between the creaking and the heart. - fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) { - let Some(id) = self.heart_protector(heart) else { - return; - }; - let Some((_, b)) = self.mob_center(id) else { - return; - }; - let (lo, hi) = (b.min_position(), b.max_position()); - for _ in 0..count { - let r = &mut self.world.random; - let mut source = [ - lo.x + r.next_double() * (hi.x - lo.x), - lo.y + r.next_double() * (hi.y - lo.y), - lo.z + r.next_double() * (hi.z - lo.z), - ]; - let mut destination = [ - f64::from(pos.0) + r.next_double(), - f64::from(pos.1) + r.next_double(), - f64::from(pos.2) + r.next_double(), - ]; - if towards { - std::mem::swap(&mut source, &mut destination); - } - let duration = r.next_int_bound(40).unwrap_or(0) + 10; - let color = if towards { ORANGE } else { GRAY }; - self.particles.add( - &ParticleOptions::trail(destination, color, duration), - source, - [0.0; 3], - ); - } - } - /// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log - /// face found within two steps of pale oak logs. - fn heart_spread_resin(&mut self, pos: Pos) -> Option { - let mut visited: HashSet = HashSet::new(); - let mut queue: VecDeque<(Pos, i32)> = VecDeque::new(); - queue.push_back((pos, 0)); - let mut count = 0; - while let Some((current, depth)) = queue.pop_front() { - if !visited.insert(current) { - continue; - } - // The node processor. - if self.is_pale_oak_log(current) { - for d in self.shuffled_directions() { - let n = ( - current.0 + DIRECTIONS[d][0], - current.1 + DIRECTIONS[d][1], - current.2 + DIRECTIONS[d][2], - ); - let neighbour = self.world.block(n.0, n.1, n.2); - let opposite = d ^ 1; - let clump = self.resin_clump_for(neighbour); - let Some(clump) = clump else { continue }; - if self.prop_is(clump, FACE_NAMES[opposite]) { - continue; - } - let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else { - continue; - }; - let _ = self.level_set([n.0, n.1, n.2], placed); - return Some(n); - } - } - count += 1; - if count >= 64 { - return None; - } - if depth < 2 { - // The neighbour provider: adjacent pale oak logs. - for d in self.shuffled_directions() { - let n = ( - current.0 + DIRECTIONS[d][0], - current.1 + DIRECTIONS[d][1], - current.2 + DIRECTIONS[d][2], - ); - if self.is_pale_oak_log(n) { - queue.push_back((n, depth + 1)); - } + mobs.extend(added); + self.mobs = mobs; + self.persist.uuids = uuids; + self.next_entity = next_entity; + self.world.random = random; + let mut mob_events = Vec::new(); + for e in events { + match e { + HeartEvent::SetBlock(at, state) => self.level_set(at, state)?, + HeartEvent::Sound(name, at, volume, pitch) => { + self.audio + .play(&format!("minecraft:{name}"), Some(at), volume, pitch) } + HeartEvent::Trail { + at, + target, + color, + duration, + } => self.particles.add( + &ParticleOptions::trail(target, color, duration), + at, + [0.0; 3], + ), + HeartEvent::OutputChanged(at) => self.container_changed((at[0], at[1], at[2])), + HeartEvent::Mob(event) => mob_events.push(event), } } - None - } - /// The state a face of resin can be added to: air, a source of water, or - /// a clump already there. - fn resin_clump_for(&self, neighbour: BlockStateId) -> Option { - let registry = self.res.assets.registry; - let clump = registry.default_state("minecraft:resin_clump")?; - let facts = self.res.facts.get(neighbour); - if self.res.facts.is_air(neighbour) { - Some(clump) - } else if &*facts.name == "minecraft:water" - && facts.fluid_level == 8 - && !facts.fluid_falling - { - let mut s = registry.state(clump)?.clone(); - s.properties.insert("waterlogged".into(), "true".into()); - registry.resolve(&s).ok() - } else if &*facts.name == "minecraft:resin_clump" { - Some(neighbour) - } else { - None - } - } - fn prop_is(&self, state: BlockStateId, key: &str) -> bool { - self.res - .assets - .registry - .state(state) - .and_then(|s| s.properties.get(key)) - .is_some_and(|v| v == "true") - } - fn with_face(&self, state: BlockStateId, face: &str) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); - s.properties.insert(face.to_owned(), "true".to_owned()); - self.res.assets.registry.resolve(&s).ok() + self.handle_mob_events(mob_events)?; + let _ = key; + Ok(()) } /// A creaking bound to the heart at `home` was hurt (`creakingHurt`). - pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) { + pub(super) fn creaking_hurt(&mut self, home: [i32; 3], _id: u32, by_player: bool) { if !by_player { return; } @@ -255,29 +171,9 @@ impl Game<'_> { else { return; }; - if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 { - self.heart_emit(&mut heart, key, 20, false); - let state = self.world.block(key.0, key.1, key.2); - if self.heart_state_name(state) == "awake" { - let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0); - for _ in 0..clumps { - if let Some(at) = self.heart_spread_resin(key) { - self.audio.play( - "minecraft:block.resin.place", - Some([ - f64::from(at.0) + 0.5, - f64::from(at.1) + 0.5, - f64::from(at.2) + 0.5, - ]), - 1.0, - 1.0, - ); - } - } - } - heart.emitter = 100; - heart.emitter_target = self.mob_center(id).map(|(c, _)| c); - } + let _ = self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::creaking_hurt(h, home, w, lr, host, out); + }); self.world .block_entities .insert(key, BlockEntity::CreakingHeart(heart)); @@ -331,9 +227,18 @@ impl Game<'_> { else { return; }; - self.heart_remove_protector(&mut heart, true); + let _ = self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, true, out); + }); let state = self.world.block(key.0, key.1, key.2); - if self.prop_is(state, "natural") && !self.creative && !self.spectator() { + let natural = self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("natural").cloned()) + .is_some_and(|v| v == "true"); + if natural && !self.creative && !self.spectator() { let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; self.spawn_orbs( [ @@ -348,96 +253,6 @@ impl Game<'_> { .block_entities .insert(key, BlockEntity::CreakingHeart(heart)); } - /// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`. - fn spawn_protector(&mut self, pos: Pos) -> Option { - let t = self.res.mob_types.get("minecraft:creaking").cloned()?; - for _ in 0..5 { - let r = &mut self.world.random; - let dx = r.next_int_bound(33).unwrap_or(16) - 16; - let dz = r.next_int_bound(33).unwrap_or(16) - 16; - let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz); - if !self.world.loaded(at.0, at.2) { - continue; - } - // moveToPossibleSpawnPosition: scan down for a collider with room above. - let mut above = self.world.block(at.0, at.1, at.2); - let mut found = false; - for _ in 0..=16 { - at.1 -= 1; - let current = self.world.block(at.0, at.1, at.2); - let facts = self.res.facts.get(current); - let leaves = self - .res - .items - .block_tags - .get("minecraft:leaves") - .is_some_and(|s| s.contains(&*facts.name)); - let clear_above = self - .res - .behaviours - .collision_shape(above) - .map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty()); - if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 { - at.1 += 1; - found = true; - break; - } - above = current; - } - if !found { - continue; - } - // noCollision(spawn box) and no liquid. - let w = t.width / 2.0; - let bounds = Aabb::new( - horizon_core::geometry::Vec3::new( - f64::from(at.0) + 0.5 - w, - f64::from(at.1), - f64::from(at.2) + 0.5 - w, - ), - horizon_core::geometry::Vec3::new( - f64::from(at.0) + 0.5 + w, - f64::from(at.1) + t.height, - f64::from(at.2) + 0.5 + w, - ), - ); - let mut scene = horizon_client::collisions::SceneCollisions { - world: &self.world, - binding: self.collision, - }; - let free = scene.unobstructed(bounds).unwrap_or(false); - let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid - != horizon_client::blocks::Fluid::None; - if !free || wet { - continue; - } - let id = self.spawn_mob( - "minecraft:creaking", - [ - f64::from(at.0) + 0.5, - f64::from(at.1), - f64::from(at.2) + 0.5, - ], - false, - )?; - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - creaking::set_transient(m, [pos.0, pos.1, pos.2]); - } - return Some(id); - } - None - } - /// `CreakingHeartBlockEntity.computeAnalogOutputSignal`. - fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 { - if heart.creaking.is_none() { - return 0; - } - let Some(id) = self.heart_protector(heart) else { - return 0; - }; - let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0; - 15 - (distance * 15.0).floor() as i32 - } /// `CreakingHeartBlockEntity.serverTick` for every heart. pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> { let keys: Vec = self @@ -456,11 +271,17 @@ impl Game<'_> { let state = self.world.block(key.0, key.1, key.2); if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { // The block is gone: preRemoveSideEffects. - self.heart_remove_protector(&mut heart, false); + self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, false, out); + })?; continue; } + // getTicker: none once uprooted. if self.heart_state_name(state) != "uprooted" { - self.heart_tick(&mut heart, key, state)?; + let pos = [key.0, key.1, key.2]; + self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::server_tick(h, pos, w, lr, host, out); + })?; } self.world .block_entities @@ -469,139 +290,11 @@ impl Game<'_> { self.scan_for_hearts(); Ok(()) } - fn heart_tick( - &mut self, - heart: &mut CreakingHeart, - key: Pos, - state: BlockStateId, - ) -> Result<()> { - heart.ticks_existed += 1; - let output = self.heart_output(heart, key); - if output != heart.output_signal { - heart.output_signal = output; - self.container_changed(key); - } - if heart.emitter > 0 { - if heart.emitter > 50 { - self.heart_emit(heart, key, 1, true); - self.heart_emit(heart, key, 1, false); - } - if heart.emitter % 10 == 0 && heart.emitter_target.is_some() { - if let Some(id) = self.heart_protector(heart) - && let Some((c, _)) = self.mob_center(id) - { - heart.emitter_target = Some(c); - } - if let Some(target) = heart.emitter_target { - let center = [ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]; - let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0; - let at = [ - (center[0] - target[0]) * progress + target[0], - (center[1] - target[1]) * progress + target[1], - (center[2] - target[2]) * progress + target[2], - ]; - let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5; - self.audio - .play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0); - } - } - heart.emitter -= 1; - } - let ticker = heart.ticker; - heart.ticker -= 1; - if ticker >= 0 { - return Ok(()); - } - heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20; - // updateCreakingState: logs gone and no creaking means uprooted. - let active = self.creaking_active(); - let has_logs = self.with_level(|b, level, ticks| { - b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state) - }); - let wanted = if !has_logs && heart.creaking.is_none() { - "uprooted" - } else if active { - "awake" - } else { - "dormant" - }; - let mut current = self.heart_state_name(state); - if wanted != current - && let Some(next) = self.heart_with_state(state, wanted) - { - self.level_set([key.0, key.1, key.2], next)?; - current = wanted.to_owned(); - if wanted == "uprooted" { - return Ok(()); - } - } - if heart.creaking.is_none() { - if current == "awake" && self.spawning_monsters() { - let near = self.player.as_ref().is_some_and(|p| { - let (dx, dy, dz) = ( - p.position.x - (f64::from(key.0) + 0.5), - p.position.y - (f64::from(key.1) + 0.5), - p.position.z - (f64::from(key.2) + 0.5), - ); - dx * dx + dy * dy + dz * dz < 32.0 * 32.0 - }) && !self.spectator(); - if near && let Some(id) = self.spawn_protector(key) { - let uuid = self.uuid_for(id); - heart.creaking = Some((Some(id), uuid)); - heart.ticks_existed = 0; - let at = self.mob_center(id).map(|(c, _)| c); - self.audio - .play("minecraft:entity.creaking.spawn", at, 1.0, 1.0); - self.audio.play( - "minecraft:block.creaking_heart.spawn", - Some([ - f64::from(key.0) + 0.5, - f64::from(key.1) + 0.5, - f64::from(key.2) + 0.5, - ]), - 1.0, - 1.0, - ); - } - } - } else if let Some(id) = self.heart_protector(heart) { - let persistent = self - .mobs - .iter() - .find(|m| m.id == id) - .is_some_and(|m| m.persistent); - let eye = self.player_view().map(|v| v.eye); - let stuck = self - .mobs - .iter_mut() - .find(|m| m.id == id) - .is_some_and(|m| creaking::player_is_stuck(m, eye)); - if (!active && !persistent) - || self.heart_distance_to_creaking(id, key) > TOO_FAR - || stuck - { - self.heart_remove_protector(heart, false); - } - } - Ok(()) - } - fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); - s.properties - .insert("creaking_heart_state".to_owned(), wanted.to_owned()); - self.res.assets.registry.resolve(&s).ok() - } /// `ServerLevel.isSpawningMonsters`. fn spawning_monsters(&self) -> bool { - self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters") - } - /// `EnvironmentAttributes.CREAKING_ACTIVE`. - pub(super) fn creaking_active(&mut self) -> bool { - self.with_level(|b, level, ticks| b.creaking_active(level, ticks)) + self.ui.difficulty != 0 + && self.ui.rules.bool("spawn_mobs") + && self.ui.rules.bool("spawn_monsters") } /// Hearts that came with generated or loaded chunks get their block /// entity (`newBlockEntity`) the first time their chunk is seen. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 04e65a448..dc8bcb330 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -86,7 +86,7 @@ impl ProjectileWorld for ProjWorld<'_, '_> { .full_collision } } -fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { +pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { let villager = m.species() == Species::Villager; Seen { id: m.id, @@ -451,9 +451,11 @@ impl Game<'_> { let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); + // The level random (`ServerLevel.getRandom`): behaviours' durations and + // the like draw from it, and it goes on from where they left it. + let mut scratch = self.world.random.clone(); { let w = self.mob_world_base(&snapshot); - let mut scratch = self.world.random.clone(); let mut pushes = Vec::new(); mobs.retain_mut(|m| { if !w @@ -475,6 +477,7 @@ impl Game<'_> { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } } + self.world.random = scratch; self.mobs.append(&mut mobs); self.sync_riders(); self.tick_skeleton_traps(); diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 948039fcc..a72530e6a 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -477,14 +477,6 @@ impl Game<'_> { pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] { *self.persist.uuids.entry(id).or_insert_with(random_uuid) } - /// The loaded mob with a saved UUID. - pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option { - self.persist - .uuids - .iter() - .find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed)) - .map(|(id, _)| *id) - } /// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`). fn state_from_nbt(&self, tag: &Tag) -> Option { let registry = self.res.assets.registry; diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs index 50fc74889..1d8da0ae8 100644 --- a/crates/horizon-client/src/mobs/creaking.rs +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -130,6 +130,25 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool { m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 }; false } +/// The rest of `Creaking.hurtServer` for a heart-bound creaking, run by the +/// host right after the damage: whether its heart still protects it, and +/// whether a player is to blame (the heart then calls `creakingHurt`). The +/// caller plays [`sway`] after the heart's reaction. +pub fn take_hurt(m: &mut Mob, w: &MobWorld) -> Option<([i32; 3], bool)> { + if m.extra.counter & HURT == 0 { + return None; + } + let by_player = m.extra.counter & HURT_BY_PLAYER != 0; + m.extra.counter &= !(HURT | HURT_BY_PLAYER); + let home = m.extra.home?; + protected(m, w).then_some((home, by_player)) +} +/// `Mob.playHurtSound` of a heart-bound creaking: the ambient sound clock +/// restarts and it sways. +pub fn sway(m: &mut Mob, events: &mut Vec) { + m.ambient_timer = -m.kind.ambient_interval; + m.voice("entity.creaking.sway", events); +} /// `Creaking.doHurtTarget`: the attack animation (the sound is the /// `playAttackSound` that ends `Mob.doHurtTarget`). pub fn on_attack(m: &mut Mob, _events: &mut Vec) { @@ -176,7 +195,7 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { id: m.id, }); } - m.voice("entity.creaking.sway", events); + sway(m, events); } m.extra.counter &= !(HURT | HURT_BY_PLAYER); } diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs index d11826ea8..038e24515 100644 --- a/crates/horizon-client/src/mobs/creaking_heart.rs +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -5,7 +5,7 @@ //! trails and spreads resin over the logs. The game and the mob AI probe //! both tick hearts through this module; the host applies the block changes //! and plays what it reports. -use super::{Mob, MobEvent, MobType, MobWorld, Species, creaking, spawn_rules}; +use super::{Mob, MobEvent, MobType, MobWorld, creaking}; use crate::{collisions::SceneCollisions, containers::CreakingHeart}; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -434,18 +434,9 @@ fn spawn_protector( m.head_yaw = yaw; m.body_yaw = yaw; finalize_spawn(&mut m, lr); - // checkSpawnRules and checkSpawnObstruction (no liquid in the box). - let (bx, by, bz) = (x.floor() as i32, y.floor() as i32, z.floor() as i32); - let allowed = spawn_rules::check_spawn_rules( - Species::Creaking, - w, - spawn_rules::Reason::Spawner, - lr, - bx, - by, - bz, - ); - if !allowed || liquid_in(w, m.bounds()) { + // Mob.checkSpawnRules (always true for a creaking) and + // checkSpawnObstruction (no liquid in the box). + if liquid_in(w, m.bounds()) { continue; } let id = m.id; 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 610523bfe..75fe7d24a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -61,6 +61,8 @@ import net.minecraft.world.clock.WorldClocks; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntitySpawnReason; import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.monster.creaking.Creaking; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Mob; @@ -162,6 +164,12 @@ public final class VanillaMobAiOracle { float turnYaw; List mobs = new ArrayList<>(); long levelSeed = 0; + /** Blocks placed when the scenario starts, so their block entities start afresh and tick. */ + List hearts = new ArrayList<>(); + /** ServerLevel.isSpawningMonsters during the scenario (a heart spawns creakings). */ + boolean spawning; + /** The player hits a mob for 1 at the start of a tick: {tick, mob index}. */ + List hurts = new ArrayList<>(); } static void parse(Path path) throws Exception { @@ -182,12 +190,15 @@ public final class VanillaMobAiOracle { case "rain" -> s.rain = true; case "thunder" -> s.thunder = true; case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]); + case "spawning" -> s.spawning = true; default -> throw new IllegalArgumentException(line); } } } case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } case "fill", "block" -> s.blocks.add(f); + case "heart" -> s.hearts.add(f); + case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])}); 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++) { @@ -495,6 +506,42 @@ public final class VanillaMobAiOracle { brains.add(brain); seeds.add(spec.seed); } + // Hearts start with the scenario: their tickers have not run during the warm-up. + var blockLookup = level.holderLookup(Registries.BLOCK); + List heartPositions = new ArrayList<>(); + for (String[] h : s.hearts) { + BlockPos at = new BlockPos(Integer.parseInt(h[1]), Integer.parseInt(h[2]), Integer.parseInt(h[3])); + level.setBlock(at, BlockStateParser.parseForBlock(blockLookup, h[4], false).blockState(), 2 | 16); + heartPositions.add(at); + } + // Mobs the level creates during the scenario (a heart's creakings) get a seeded + // random, delayed sensors and seeded gates as the scenario's own mobs do, the + // n-th with seed 1000 + n; they join the list once in the level. + List created = new ArrayList<>(); + Field factoryField = field(EntityType.class, "factory"); + Object creakingFactory = factoryField.get(EntityTypes.CREAKING); + final List mobsView = mobs; + factoryField.set(EntityTypes.CREAKING, (EntityType.EntityFactory) (type, lvl) -> { + Creaking c = new Creaking(type, lvl); + try { + long seed = 1000 + created.size(); + if (tracing(s)) field(Entity.class, "random").set(c, new TracingRandom(0L, TRACE, mobsView.size() + created.size())); + c.getRandom().setSeed(seed); + @SuppressWarnings("unchecked") + Map> cs = (Map>) get(c.getBrain(), "sensors"); + for (Sensor sensor : cs.values()) sensor.randomlyDelayStart(c.getRandom()); + seedGates(c.getBrain(), seed); + } catch (Exception e) { + throw new IllegalStateException(e); + } + created.add(c); + return c; + }); + boolean spawnMobs = this.getGameRules().get(GameRules.SPAWN_MOBS); + boolean spawnMonsters = this.getGameRules().get(GameRules.SPAWN_MONSTERS); + this.getGameRules().set(GameRules.SPAWN_MOBS, s.spawning, this); + this.getGameRules().set(GameRules.SPAWN_MONSTERS, s.spawning, this); + int adopted = 0; level.getRandom().setSeed(s.levelSeed); SOUNDS.clear(); Method tickTime = method(ServerLevel.class, "tickTime"); @@ -530,23 +577,57 @@ public final class VanillaMobAiOracle { seedGates(brains.get(i), seeds.get(i)); } } + for (int[] hurt : s.hurts) { + if (hurt[0] == t && hurt[1] < mobs.size() && !mobs.get(hurt[1]).isRemoved()) + mobs.get(hurt[1]).hurtServer(level, level.damageSources().playerAttack(player), 1.0F); + } for (Mob mob : mobs) { if (mob.isRemoved()) continue; mob.checkDespawn(); if (mob.isRemoved()) continue; level.tickNonPassenger(mob); } + if (!heartPositions.isEmpty()) level.tickBlockEntities(); managerTick.invoke(manager); + // Created mobs that made it into the level, in creation order. + for (; adopted < created.size(); adopted++) { + Mob c = created.get(adopted); + if (!c.isRemoved()) { + mobs.add(c); + brains.add(c.getBrain()); + seeds.add(1000L + adopted); + } + } for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); + for (BlockPos h : heartPositions) printHeart(t, level, h); for (String sound : SOUNDS) out.println(t + " sound " + sound); for (String line : TRACE) out.println(line); TRACE.clear(); } for (Mob mob : mobs) mob.discard(); + for (BlockPos h : heartPositions) level.setBlock(h, net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(), 2 | 16); + factoryField.set(EntityTypes.CREAKING, creakingFactory); + this.getGameRules().set(GameRules.SPAWN_MOBS, spawnMobs, this); + this.getGameRules().set(GameRules.SPAWN_MONSTERS, spawnMonsters, this); managerTick.invoke(manager); out.flush(); } + /** A heart's block state and block entity, and the level random. */ + static void printHeart(int t, ServerLevel level, BlockPos at) throws Exception { + StringBuilder sb = new StringBuilder(); + sb.append(t).append(" heart ").append(pos(at)).append('\t') + .append(level.getBlockState(at).getValue(net.minecraft.world.level.block.CreakingHeartBlock.STATE).getSerializedName()); + if (level.getBlockEntity(at) instanceof net.minecraft.world.level.block.entity.CreakingHeartBlockEntity be) { + sb.append('\t').append(get(be, "ticker")).append(' ').append(get(be, "emitter")).append(' ').append(get(be, "outputSignal")) + .append(' ').append(get(be, "ticksExisted")); + Object info = get(be, "creakingInfo"); + sb.append(' ').append(info == null ? "none" : "linked"); + } + sb.append("\tlrng ").append(Long.toHexString(((java.util.concurrent.atomic.AtomicLong) field(net.minecraft.world.level.levelgen.LegacyRandomSource.class, "seed").get(level.getRandom())).get())); + out.println(sb); + } + /** * Every GateBehavior (RunOne and the gates of TradeWithVillager and VillagerMakeLove) shuffles * its behaviours with its own ShufflingList random, which RandomSource.create() seeds from the diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 235e44e8a..d3a19f9a3 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -88,6 +88,16 @@ def scenarios(): add('creaking_behind', 200, ['player 0.5 -60 8.5', 'mob minecraft:creaking 0.5 -60 0.5 0 73 persistent']) # Woken while watched, then free to hunt and hit once the player turns away. add('creaking_attack', 240, ['player 0.5 -60 -7.5 turn=40,180', 'mob minecraft:creaking 0.5 -60 0.5 180 74 persistent']) + # A creaking heart in a pale oak trunk: by night it spawns its creaking near a player, + # by day it sleeps, without logs it is uprooted, with no player near it waits. + TRUNK = ['block 3 -60 3 minecraft:pale_oak_log[axis=y]', 'block 3 -58 3 minecraft:pale_oak_log[axis=y]'] + add('heart_night', 300, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'time=18000 spawning') + add('heart_day', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'spawning') + add('heart_uprooted', 60, ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5'], 'time=18000 spawning') + # A player hits the heart's creaking: no damage, but the heart bleeds resin and trails. + add('heart_hurt', 260, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5', + 'hurt 60 0', 'hurt 64 0', 'hurt 200 0'], 'time=18000 spawning') + add('heart_far', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 40.5 -60 0.5'], 'time=18000 spawning') return s @@ -105,7 +115,7 @@ def write_scenarios(path, chosen): elif f[0] == 'mob': f[2] = repr(float(f[2]) + ox) f[4] = repr(float(f[4]) + oz) - elif f[0] == 'block': + elif f[0] in ('block', 'heart'): f[1] = str(int(f[1]) + ox) f[3] = str(int(f[3]) + oz) elif f[0] == 'fill': @@ -134,6 +144,9 @@ def parse(path): if parts[1] == 'trace': cur.setdefault('trace', {}).setdefault(t, []).append(parts[2]) continue + if parts[1] == 'heart': + cur.setdefault('hearts', {}).setdefault(t, []).append(line.split(' ', 2)[2]) + continue mob = int(parts[1]) row = {} if len(parts) > 2: @@ -221,7 +234,12 @@ def compare(vanilla, rust, fields=None): report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False - # Sounds: first differing tick. + # Creaking hearts (state, block entity, level random): first differing tick. + for t in sorted(set(v.get('hearts', {})) | set(r.get('hearts', {}))): + if v.get('hearts', {}).get(t) != r.get('hearts', {}).get(t): + report.append(f'{name}: hearts differ at tick {t}: vanilla {v.get("hearts", {}).get(t)} | horizon {r.get("hearts", {}).get(t)}') + clean = False + break for t in sorted(set(v['sounds']) | set(r['sounds'])): if v['sounds'].get(t, []) != r['sounds'].get(t, []): report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}')