From fb954f7d7f80b107b4b3dfa76dd02c738bb40dc4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:29:51 +0200 Subject: [PATCH 1/7] Load saved light and test it against vanilla Chunks saved with isLightOn now read their SkyLight and BlockLight arrays back like vanilla instead of being relit: a missing sky layer repeats the bottom layer of the section above it, and a missing block layer is dark. Such chunks skip the light job, mesh as soon as their neighbours are lit, and only relight when a freshly generated neighbour arrives. tools/test_light_parity.py builds a scene of slabs, stairs, snow, trapdoors, lanterns, leaves and lava in a vanilla world, edits it, and requires every saved light value and every incremental relight to match Horizon's engine. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/chunk.rs | 3 + crates/horizon-client/src/save.rs | 104 ++++++++++++++++++++++++- crates/horizon-client/src/streaming.rs | 15 +++- tools/test_light_parity.py | 100 ++++++++++++++++++++++++ 4 files changed, 220 insertions(+), 2 deletions(-) create mode 100755 tools/test_light_parity.py diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index e1332b159..d5e65655c 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -94,6 +94,8 @@ pub struct Chunk { /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. pub heights: Arc<[i16; 256]>, pub lit: bool, + /// Light read from a save with `isLightOn`: no light job is needed. + pub light_loaded: bool, /// Newly generated (not loaded from a save): eligible for generation-time spawns. pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. @@ -120,6 +122,7 @@ impl Chunk { biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, + light_loaded: false, fresh: false, block_entities: Vec::new(), structure_refs: Vec::new(), diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index bcca25e8a..83e93e8e1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -901,6 +901,60 @@ pub fn decode_with( Some(chunk) } +/// Read the stored `SkyLight`/`BlockLight` layers of a chunk saved with +/// `isLightOn` (`SerializableChunkData.read` + `ThreadedLevelLightEngine`), +/// so it needs no relighting. A missing sky layer repeats the bottom layer of +/// the section above it (15 above the highest stored one); a missing block +/// layer is dark. +pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) { + if tag.get("isLightOn") != Some(&Tag::Byte(1)) { + return; + } + let Some(Tag::List(sections)) = tag.get("sections") else { + return; + }; + let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS]; + for section in sections { + let Some(y) = number(section.get("Y")) else { + continue; + }; + let si = y as i32 - (MIN_Y >> 4); + if !(0..SECTIONS as i32).contains(&si) { + continue; + } + let layer = |name: &str| match section.get(name) { + Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]), + _ => None, + }; + layers[si as usize] = (layer("SkyLight"), layer("BlockLight")); + } + let sky_default = if sky_light { 15u8 } else { 0 }; + // Sky nibbles of the section above's bottom layer, going down. + let mut above: [u8; 256] = [sky_default; 256]; + for si in (0..SECTIONS).rev() { + let (sky, block) = layers[si]; + let mut data = Box::new([0u8; 4096]); + let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; + for (i, packed) in data.iter_mut().enumerate() { + let s = match sky { + Some(a) if sky_light => nibble(a, i), + _ => above[i & 255], + }; + let b = block.map_or(0, |a| nibble(a, i)); + *packed = s << 4 | b; + } + for (i, a) in above.iter_mut().enumerate() { + *a = data[i] >> 4; + } + let mut section = (*chunk.sections[si]).clone(); + section.light = Light::Full(data); + section.compact(); + chunk.sections[si] = Arc::new(section); + } + chunk.lit = true; + chunk.light_loaded = true; +} + type RegionCache = Mutex>>>>; /// One dimension folder (`dimensions/minecraft/`). Region files are /// read lazily by worker threads. @@ -951,7 +1005,9 @@ impl SaveDir { pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option { let root = self.read_record("region", x, z)?; let tables = self.tables.get().map(|t| &**t); - decode_with(&root, registry, biomes, tables) + let mut chunk = decode_with(&root, registry, biomes, tables)?; + load_light(&root.tag, &mut chunk, self.sky_light); + Some(chunk) } /// Entities saved for a chunk (`entities/`; older chunks may still keep /// them in the chunk's own `entities` list). @@ -2016,6 +2072,52 @@ mod tests { assert_eq!(nibbles(&light, true)[0], 0x5F); } #[test] + fn stored_light_loads_with_vanilla_defaults() { + let mut sky = vec![0u8; 2048]; + sky[0] = 0x5A; // x=0 -> 10, x=1 -> 5 + let section = |y: i8, entries: Vec<(&str, Tag)>| { + let mut all = vec![("Y", Tag::Byte(y))]; + all.extend(entries); + Tag::compound(all) + }; + let tag = Tag::compound([ + ("isLightOn", Tag::Byte(1)), + ( + "sections", + Tag::List(vec![ + section( + -4, + vec![ + ("SkyLight", Tag::ByteArray(sky)), + ("BlockLight", Tag::ByteArray(vec![0x21; 2048])), + ], + ), + // No sky layer: repeats the bottom layer of the section above. + section(-3, vec![]), + ]), + ), + ]); + let mut chunk = Chunk::empty(0, 0); + load_light(&tag, &mut chunk, true); + assert!(chunk.lit && chunk.light_loaded); + let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i); + assert_eq!(at(&chunk, 0, 0), 0xA1, "stored sky 10, block 1"); + assert_eq!(at(&chunk, 0, 1), 0x52, "stored sky 5, block 2"); + // Section -3 has no layers; above it (-2..) sky defaults to 15. + assert_eq!(at(&chunk, 1, 0), 0xF0); + assert_eq!(at(&chunk, SECTIONS - 1, 5), 0xF0); + let mut dark = Chunk::empty(0, 0); + load_light(&tag, &mut dark, false); + assert_eq!(at(&dark, 1, 0), 0x00, "no skylight dimension"); + let mut unlit = Chunk::empty(0, 0); + load_light( + &Tag::compound([("isLightOn", Tag::Byte(0))]), + &mut unlit, + true, + ); + assert!(!unlit.lit && !unlit.light_loaded); + } + #[test] fn level_round_trips_through_the_vanilla_files() { let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 6fd8a64bd..c43e82e69 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -329,10 +329,23 @@ impl Streaming { self.decorated.insert(key); if self.in_range(key.0, key.1, 2) { self.generated_total += 1; + // A chunk saved with its light needs no light job; its + // unlit neighbours still light themselves from it. + let loaded = chunk.light_loaded; world.chunks.insert(key, Arc::new(chunk)); + if loaded { + self.lit.insert(key); + for sy in 0..SECTIONS as i32 { + world.dirty_sections.insert((key.0, sy, key.1)); + } + } for dz in -1..=1 { for dx in -1..=1 { - world.dirty_light.insert((key.0 + dx, key.1 + dz)); + let n = (key.0 + dx, key.1 + dz); + if !loaded || world.chunks.get(&n).is_some_and(|c| !c.light_loaded) + { + world.dirty_light.insert(n); + } } } } diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py new file mode 100755 index 000000000..3e42acd5c --- /dev/null +++ b/tools/test_light_parity.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Compare Horizon's light engine with the vanilla 26.3 server. + +Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, +leaves, water and glowstone in a fresh vanilla world, lets the vanilla light +engine settle, stops the server so the SkyLight/BlockLight arrays are saved, +then relights every saved chunk with `examples/light_parity` and requires every +value to agree. The example also replays block edits through the incremental +`light::relight` and checks them against a full relight. + + test_light_parity.py [--seed N] [--keep] +""" +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LOCAL = ROOT / '.local' +RESOURCES = LOCAL / 'horizon-client' / '26.3' +SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar' + +# Absolute coordinates well above the terrain, inside force-loaded chunks. +SCENE = [ + 'forceload add 0 0 63 63', + 'sleep 6', + # Closed room with a bottom-slab roof and a glowstone lamp. + 'fill 2 170 2 20 175 20 stone hollow', + 'fill 2 176 2 20 176 20 stone_slab[type=bottom]', + 'setblock 10 171 10 glowstone', + # Stairs, top and bottom; snow layers; trapdoors; lanterns; water. + 'fill 4 171 4 4 171 18 oak_stairs[facing=east,half=top]', + 'fill 6 171 4 6 171 18 stone_brick_stairs[facing=north,half=bottom,shape=inner_left]', + 'fill 12 171 4 18 171 6 snow[layers=3]', + 'fill 12 172 8 18 172 8 oak_trapdoor[half=bottom,open=false]', + 'fill 12 173 12 18 173 12 oak_trapdoor[half=top,open=true,facing=north]', + 'setblock 14 171 14 lantern', + 'setblock 15 175 15 soul_lantern[hanging=true]', + 'fill 8 171 16 9 172 17 water', + # Open-air structures: sky light through slabs, stairs and leaves. + 'fill 24 170 24 46 170 46 stone', + 'fill 26 171 26 44 171 26 stone_slab[type=top]', + 'fill 26 171 28 44 171 28 stone_slab[type=bottom]', + 'fill 26 172 30 44 172 30 oak_leaves[persistent=true]', + 'fill 26 171 32 30 171 40 glass', + 'fill 32 171 32 36 171 40 oak_stairs[facing=south,half=bottom]', + 'fill 38 171 32 38 175 40 stone_brick_wall', + 'fill 40 171 32 44 171 40 dirt_path', + 'fill 40 172 34 44 172 34 daylight_detector', + 'fill 24 180 50 46 180 50 stone_slab[type=double]', + 'fill 24 178 52 46 178 52 oak_stairs[facing=west,half=top]', + 'setblock 30 171 44 torch', + 'setblock 34 171 44 campfire', + 'setblock 38 171 44 sea_lantern', + 'setblock 42 171 44 lava', + 'sleep 10', + # Edits after the first lighting pass, so vanilla updates incrementally. + 'setblock 10 171 10 air', + 'setblock 10 176 10 air', + 'setblock 30 171 26 air', + 'fill 26 172 30 30 172 30 air', + # Vanilla saves a chunk only when its blocks changed, so light that + # reached an untouched chunk later is stale on disk: mark every compared + # chunk (0..2, 0..3) as edited so it is written at shutdown. + *[f'setblock {x * 16 + 8} 169 {z * 16 + 8} stone' for x in range(3) for z in range(4)], + 'sleep 8', +] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', default='4242') + parser.add_argument('--keep', action='store_true') + args = parser.parse_args() + run = LOCAL / 'rust-light-parity' + shutil.rmtree(run, ignore_errors=True) + run.mkdir(parents=True) + command = [sys.executable, str(ROOT / 'tools' / 'vanilla_world_check.py'), '--jar', str(SERVER), + '--dir', str(run), '--world', 'world', '--seed', args.seed, '--wait-after', '8'] + for step in SCENE: + command += ['--command', step] + if subprocess.run(command).returncode: + sys.exit('vanilla server reported problems') + dimension = run / 'world' / 'dimensions' / 'minecraft' / 'overworld' + if not (dimension / 'region').is_dir(): + dimension = run / 'world' + for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): + status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', + '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + cwd=ROOT).returncode + if status: + sys.exit('light mismatch against vanilla') + print('light parity ok') + if not args.keep: + shutil.rmtree(run, ignore_errors=True) + + +if __name__ == '__main__': + main() From 3de8b358ec584893253af531ffcc96e867cdd0ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:56:20 +0200 Subject: [PATCH 2/7] Dispense items like vanilla dispensers and droppers Dispensers now follow DispenserBlock's behaviour table: arrows, eggs, snowballs, experience bottles, thrown potions, firework rockets (flying straight until they hit something) and fire charges are shot out with the vanilla power and spread; buckets place or pick up water, lava, powder snow and mobs through the new Behaviours bucket calls; flint and steel, bone meal, TNT, shears (sheep, mooshrooms, bogged, beehives), brushes on armadillos, honeycomb waxing, respawn anchors, glass bottles (water, honey), water potions on mud, boats, minecarts, armor stands, shulker boxes, carved pumpkins (which now build snow and iron golems for players too), wither skulls, spawn eggs and worn equipment on players, armor stands and mobs that may pick up loot. Every dispense plays the vanilla click, fail or launch sound and the smoke puff, and droppers keep the plain drop or container insert. Experience bottles can also be thrown by the player. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/entity_nbt.rs | 3 +- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/dispenser.rs | 1462 +++++++++++++++++++ crates/horizon-client/src/game/fireworks.rs | 32 +- crates/horizon-client/src/game/golems.rs | 82 ++ crates/horizon-client/src/game/machines.rs | 385 +---- crates/horizon-client/src/game/minecarts.rs | 10 +- crates/horizon-client/src/game/potions.rs | 89 +- crates/horizon-client/src/items.rs | 25 + crates/horizon-client/src/mobs.rs | 2 + crates/horizon-client/src/mobs/spawning.rs | 22 +- crates/horizon-world/src/level/buckets.rs | 146 ++ crates/horizon-world/src/level/fluids.rs | 2 +- crates/horizon-world/src/level/mod.rs | 2 + crates/horizon-world/src/level/tests.rs | 63 + 15 files changed, 1912 insertions(+), 416 deletions(-) create mode 100644 crates/horizon-client/src/game/dispenser.rs create mode 100644 crates/horizon-client/src/game/golems.rs create mode 100644 crates/horizon-world/src/level/buckets.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a655c2dcd..02ab14543 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -124,7 +124,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), - ("CanPickUpLoot", Tag::Byte(0)), + ("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))), ("LeftHanded", Tag::Byte(0)), ( "Brain", @@ -446,6 +446,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; m.persistent = flag(tag, "PersistenceRequired"); + m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..cd921c878 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -15,6 +15,7 @@ mod commands; mod control; mod creatures; mod crossbow; +mod dispenser; mod dragon; mod enchant_effects; mod end; @@ -25,6 +26,7 @@ mod fishing; mod fov; mod frames; mod game_mode; +mod golems; mod growth; mod jukebox; mod lightning; @@ -1830,6 +1832,7 @@ impl Game<'_> { self.stats.add("used", &stack.item, 1); self.trigger_block("minecraft:placed_block", target, &stack); self.check_wither_spawn(target)?; + self.check_golem_spawn(target)?; self.consume_held(); Ok(()) } diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs new file mode 100644 index 000000000..75f39881d --- /dev/null +++ b/crates/horizon-client/src/game/dispenser.rs @@ -0,0 +1,1462 @@ +//! Dispenser behaviours: `DispenserBlock.getDispenseMethod(..).dispense` with +//! every `DispenseItemBehavior` registration of vanilla that Horizon has the +//! entities for. A behaviour returns what is left in the slot and the level +//! event it plays (`DefaultDispenseItemBehavior.dispense` then plays that +//! event and the smoke animation, event 2000). +use super::Game; +use horizon_client::{ + Result, + collisions::SceneCollisions, + containers::BlockEntity, + items::ItemStack, + mobs::{MobEvent, SpawnSetup, Species}, + particles::{ParticleOptions, ParticleType}, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{ + fluid::FluidKind, + level::{BucketContent, PlaceContext, PlaceOutcome}, + registry::BlockStateId, +}; + +type Pos = (i32, i32, i32); + +/// The sound event of a plain click, a failed dispense and a launched projectile. +const CLICK: i32 = 1000; +const FAIL: i32 = 1001; +const LAUNCH: i32 = 1002; + +fn step(d: Direction) -> [i32; 3] { + match d { + Direction::Down => [0, -1, 0], + Direction::Up => [0, 1, 0], + Direction::North => [0, 0, -1], + Direction::South => [0, 0, 1], + Direction::West => [-1, 0, 0], + Direction::East => [1, 0, 0], + } +} +fn offset(p: Pos, d: Direction) -> Pos { + let s = step(d); + (p.0 + s[0], p.1 + s[1], p.2 + s[2]) +} +/// `Direction.get3DDataValue`. +fn data_value(d: Direction) -> i32 { + match d { + Direction::Down => 0, + Direction::Up => 1, + Direction::North => 2, + Direction::South => 3, + Direction::West => 4, + Direction::East => 5, + } +} +/// `Direction.toYRot` (vertical directions give 270 through `data2d = -1`). +fn y_rot(d: Direction) -> f32 { + match d { + Direction::South => 0.0, + Direction::West => 90.0, + Direction::North => 180.0, + Direction::East => 270.0, + _ => 270.0, + } +} +fn block_box(p: Pos) -> Aabb { + Aabb::new( + Vec3::new(f64::from(p.0), f64::from(p.1), f64::from(p.2)), + Vec3::new(f64::from(p.0 + 1), f64::from(p.1 + 1), f64::from(p.2 + 1)), + ) +} +fn overlaps(a: Aabb, b: Aabb) -> bool { + let (a0, a1, b0, b1) = ( + a.min_position(), + a.max_position(), + b.min_position(), + b.max_position(), + ); + a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y && a0.z < b1.z && b0.z < a1.z +} +/// `ItemStack.shrink(1)`; the slot is empty at zero. +fn shrink(mut stack: ItemStack) -> Option { + stack.count -= 1; + (stack.count > 0).then_some(stack) +} +/// A dispenser's answer: the slot's new content and the level event played. +type Dispensed = (Option, i32); + +/// Entities `getEntitiesOfClass(.., AABB(pos))` can find. +enum Target { + Player, + Mob(usize), + Stand(usize), +} + +impl Game<'_> { + fn prop(&self, state: BlockStateId, key: &str) -> Option { + self.res + .assets + .registry + .state(state)? + .properties + .get(key) + .cloned() + } + /// The same block with other properties (`withProperty`). + fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + for (k, v) in props { + s.properties.insert((*k).to_owned(), (*v).to_owned()); + } + self.res.assets.registry.resolve(&s).ok() + } + fn block_at(&self, p: Pos) -> BlockStateId { + self.world.block(p.0, p.1, p.2) + } + fn dispenser_block_name(&self, p: Pos) -> std::sync::Arc { + self.res.facts.get(self.block_at(p)).name.clone() + } + fn in_block_tag(&self, tag: &str, block: &str) -> bool { + self.res + .items + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + fn water_at(&self, p: Pos) -> bool { + matches!( + self.res.behaviours.fluid_kind(self.block_at(p)), + FluidKind::Water | FluidKind::FlowingWater + ) + } + fn center(p: Pos) -> [f64; 3] { + [ + f64::from(p.0) + 0.5, + f64::from(p.1) + 0.5, + f64::from(p.2) + 0.5, + ] + } + fn pos_of(p: Pos) -> BlockPos { + BlockPos::new(p.0, p.1, p.2) + } + + // ---- level events (LevelEventHandler) ---- + + /// The dispenser level events: 1000 click, 1001 fail, 1002 launch, 1004 + /// firework shoot, 1018 blaze shoot and 2000 smoke shot out of the front. + pub(super) fn dispenser_event(&mut self, id: i32, pos: Pos, data: i32) { + let c = Self::center(pos); + match id { + 1000 => self + .audio + .play("minecraft:block.dispenser.dispense", Some(c), 1.0, 1.0), + 1001 => self + .audio + .play("minecraft:block.dispenser.fail", Some(c), 1.0, 1.2), + 1002 => self + .audio + .play("minecraft:block.dispenser.launch", Some(c), 1.0, 1.2), + 1004 => self + .audio + .play("minecraft:entity.firework_rocket.shoot", Some(c), 1.0, 1.2), + 1018 => { + let r = &mut self.world.random; + let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; + self.audio + .play("minecraft:entity.blaze.shoot", Some(c), 2.0, pitch); + } + 2000 => { + let s = match data { + 0 => [0, -1, 0], + 1 => [0, 1, 0], + 2 => [0, 0, -1], + 3 => [0, 0, 1], + 4 => [-1, 0, 0], + _ => [1, 0, 0], + }; + for _ in 0..10 { + let r = self.particles.random(); + let pow = r.next_double() * 0.2 + 0.01; + let (sx, sy, sz) = (f64::from(s[0]), f64::from(s[1]), f64::from(s[2])); + let p = [ + f64::from(pos.0) + + sx * 0.6 + + 0.5 + + sx * 0.01 + + (r.next_double() - 0.5) * sz * 0.5, + f64::from(pos.1) + + sy * 0.6 + + 0.5 + + sy * 0.01 + + (r.next_double() - 0.5) * sy * 0.5, + f64::from(pos.2) + + sz * 0.6 + + 0.5 + + sz * 0.01 + + (r.next_double() - 0.5) * sx * 0.5, + ]; + let v = [ + sx * pow + r.next_gaussian() * 0.01, + sy * pow + r.next_gaussian() * 0.01, + sz * pow + r.next_gaussian() * 0.01, + ]; + self.particles + .add(&ParticleOptions::simple(ParticleType::Smoke), p, v); + } + } + _ => {} + } + } + + // ---- DefaultDispenseItemBehavior ---- + + /// `DispenserBlock.getDispensePosition(source, scale, offset)`. + fn dispense_position(pos: Pos, facing: Direction, scale: f64, offset: [f64; 3]) -> Vec3 { + let s = step(facing); + let c = Self::center(pos); + Vec3::new( + c[0] + scale * f64::from(s[0]) + offset[0], + c[1] + scale * f64::from(s[1]) + offset[1], + c[2] + scale * f64::from(s[2]) + offset[2], + ) + } + /// `DefaultDispenseItemBehavior.spawnItem` at `getDispensePosition`. + pub(super) fn spawn_dispensed( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + accuracy: i32, + ) { + let s = step(facing); + let p = Self::dispense_position(pos, facing, 0.7, [0.0; 3]); + let mut at = [p.x, p.y, p.z]; + at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; + let r = &mut self.world.random; + // new ItemEntity(level, x, y, z, stack): its default motion draws first. + let _ = (r.next_double(), r.next_double()); + let pow = r.next_double() * 0.1 + 0.2; + let spread = 0.017_227_5 * f64::from(accuracy); + let v = [ + r.triangle(f64::from(s[0]) * pow, spread), + r.triangle(0.2, spread), + r.triangle(f64::from(s[2]) * pow, spread), + ]; + self.spawn_item(stack, at, v, 0); + } + /// `DefaultDispenseItemBehavior.execute`: drop one item. + fn default_execute( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + ) -> Option { + let one = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + self.spawn_dispensed(pos, facing, one, 6); + (stack.count > 0).then_some(stack) + } + /// `new DefaultDispenseItemBehavior().dispense(..)` including its events. + pub(super) fn dispense_default( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Option { + let left = self.default_execute(pos, facing, stack); + self.dispenser_event(CLICK, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + left + } + /// `DefaultDispenseItemBehavior.consumeWithRemainder`: the remainder goes + /// into the dispenser (`insertItem`) or is dropped. + fn consume_with_remainder( + &mut self, + pos: Pos, + facing: Direction, + mut stack: ItemStack, + remainder: ItemStack, + ) -> Option { + stack.count -= 1; + if stack.count == 0 { + return Some(remainder); + } + let mut rest = remainder; + if let Some(entity) = self.world.block_entities.get_mut(&pos) { + let max = self + .res + .items + .get(&rest.item) + .map_or(64, |i| i.max_stack) + .max(1); + for cell in entity.slots_mut() { + match cell { + None => { + let n = rest.count.min(max); + *cell = Some(ItemStack { + count: n, + ..rest.clone() + }); + rest.count -= n; + } + Some(e) if e.same_item_same_components(&rest) => { + let n = rest.count.min(max.saturating_sub(e.count)); + e.count += n; + rest.count -= n; + } + Some(_) => {} + } + if rest.count == 0 { + break; + } + } + } + if rest.count > 0 { + self.spawn_dispensed(pos, facing, rest, 6); + self.dispenser_event(CLICK, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + } + Some(stack) + } + /// `ItemStack.hurtAndBreak(amount)` without an entity. + fn hurt_and_break(&mut self, mut stack: ItemStack, amount: u32) -> Option { + let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + if max == 0 { + return Some(stack); + } + stack.damage += self.durability_loss(&stack, amount); + if stack.damage >= max { + return shrink(ItemStack { damage: 0, ..stack }); + } + Some(stack) + } + + // ---- the registry ---- + + /// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`: what the + /// slot holds afterwards. + pub(super) fn dispense_item( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result> { + let item = stack.item.to_string(); + let (left, event) = match item.as_str() { + "minecraft:arrow" + | "minecraft:tipped_arrow" + | "minecraft:spectral_arrow" + | "minecraft:egg" + | "minecraft:blue_egg" + | "minecraft:brown_egg" + | "minecraft:snowball" + | "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:firework_rocket" + | "minecraft:fire_charge" => self.dispense_projectile(pos, facing, stack), + "minecraft:armor_stand" => self.dispense_armor_stand(pos, facing, stack), + "minecraft:chest" => self.dispense_chest(pos, facing, stack), + "minecraft:lava_bucket" + | "minecraft:water_bucket" + | "minecraft:powder_snow_bucket" + | "minecraft:salmon_bucket" + | "minecraft:cod_bucket" + | "minecraft:pufferfish_bucket" + | "minecraft:tropical_fish_bucket" + | "minecraft:axolotl_bucket" + | "minecraft:tadpole_bucket" => self.dispense_filled_bucket(pos, facing, stack)?, + "minecraft:bucket" => self.dispense_empty_bucket(pos, facing, stack)?, + "minecraft:flint_and_steel" => self.dispense_flint_and_steel(pos, facing, stack)?, + "minecraft:bone_meal" => self.dispense_bone_meal(pos, facing, stack)?, + "minecraft:tnt" => self.dispense_tnt(pos, facing, stack), + "minecraft:wither_skeleton_skull" => self.dispense_wither_skull(pos, facing, stack)?, + "minecraft:carved_pumpkin" => self.dispense_carved_pumpkin(pos, facing, stack)?, + "minecraft:glass_bottle" => self.dispense_glass_bottle(pos, facing, stack)?, + "minecraft:glowstone" => self.dispense_glowstone(pos, facing, stack)?, + "minecraft:shears" => self.dispense_shears(pos, facing, stack)?, + "minecraft:brush" => self.dispense_brush(pos, facing, stack), + "minecraft:honeycomb" => self.dispense_honeycomb(pos, facing, stack)?, + "minecraft:potion" => self.dispense_potion(pos, facing, stack)?, + _ if item.ends_with("shulker_box") => self.dispense_shulker_box(pos, facing, stack)?, + _ if super::boats::boat_wood(&item).is_some() => self.dispense_boat(pos, facing, stack), + _ if super::minecarts::CartKind::from_id(&item).is_some() => { + self.dispense_minecart(pos, facing, stack) + } + _ => self.dispense_default_method(pos, facing, stack), + }; + self.dispenser_event(event, pos, 0); + self.dispenser_event(2000, pos, data_value(facing)); + Ok(left) + } + /// `DispenserBlock.getDefaultDispenseMethod`: equipment, spawn eggs, or a drop. + fn dispense_default_method( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Dispensed { + let equippable = self + .res + .items + .get(&stack.item) + .is_some_and(|i| i.equip_slot.is_some()); + if equippable { + let mut stack = stack; + if self.dispense_equipment(pos, facing, &mut stack) { + return (Some(stack).filter(|s| s.count > 0), CLICK); + } + return (self.default_execute(pos, facing, stack), CLICK); + } + if stack.item.ends_with("_spawn_egg") { + return self.dispense_spawn_egg(pos, facing, stack); + } + (self.default_execute(pos, facing, stack), CLICK) + } + + // ---- entities ---- + + /// Entities whose box overlaps the block at `p`. + fn targets_at(&self, p: Pos) -> Vec { + let block = block_box(p); + let mut out: Vec = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| m.alive() && overlaps(m.bounds(), block)) + .map(|(i, _)| Target::Mob(i)) + .collect(); + out.extend( + self.armor_stands + .iter() + .enumerate() + .filter(|(_, s)| overlaps(s.bounds(), block)) + .map(|(i, _)| Target::Stand(i)), + ); + if let Some(v) = self.player_view() + && v.alive + && !self.spectator() + && overlaps(v.bounds, block) + { + out.push(Target::Player); + } + out + } + /// The Y offset `EntityType.getYOffset` finds for a box set down into a block. + fn drop_offset(&self, width: f64, height: f64, p: Pos) -> f64 { + let h = width / 2.0; + let (x, z) = (f64::from(p.0) + 0.5, f64::from(p.2) + 0.5); + let y = f64::from(p.1) + 1.0; + let bounds = Aabb::new( + Vec3::new(x - h, y, z - h), + Vec3::new(x + h, y + height, z + h), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + match scene.resolve(bounds, Vec3::new(0.0, -1.0, 0.0), 0.0, false) { + Ok(moved) => 1.0 + moved.y, + Err(_) => 0.0, + } + } + /// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob. + fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option { + let name = if kind.contains(':') { + kind.to_owned() + } else { + format!("minecraft:{kind}") + }; + let t = self.res.mob_types.get(&name)?.clone(); + let y_off = if try_move_down { + self.drop_offset(t.width, t.height, p) + } else { + 0.0 + }; + let at = [ + f64::from(p.0) + 0.5, + f64::from(p.1) + y_off, + f64::from(p.2) + 0.5, + ]; + self.spawn_mob(&name, at, true) + } + /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first entity in + /// front that can wear the item gets one of it. + fn dispense_equipment(&mut self, pos: Pos, _facing: Direction, stack: &mut ItemStack) -> bool { + let Some(info) = self.res.items.get(&stack.item) else { + return false; + }; + let (Some(slot), true) = (info.equip_slot.clone(), info.equip_dispensable) else { + return false; + }; + let allowed = info.equip_allowed.clone(); + let sound = info.equip_sound.clone(); + let front = offset(pos, _facing); + let one = ItemStack { + count: 1, + ..stack.clone() + }; + let armor_index = match slot.as_str() { + "head" => Some(0), + "chest" => Some(1), + "legs" => Some(2), + "feet" => Some(3), + _ => None, + }; + let id_allowed = |id: &str| allowed.as_ref().is_none_or(|a| a.contains(id)); + let item: std::sync::Arc = stack.item.clone(); + for target in self.targets_at(front) { + let at = match target { + Target::Player => { + // The player wears armour only. + let Some(i) = armor_index else { continue }; + if !id_allowed("minecraft:player") || self.armor[i].is_some() { + continue; + } + self.armor[i] = Some(one.clone()); + self.apply_equipment(); + self.player_view().map(|v| v.position) + } + Target::Stand(i) => { + let Some(ai) = armor_index else { continue }; + if !id_allowed("minecraft:armor_stand") { + continue; + } + // ArmorStand equipment: mainhand, offhand, feet, legs, chest, head. + let index = 5 - ai; + let stand = &mut self.armor_stands[i]; + if stand.equipment[index].is_some() { + continue; + } + stand.equipment[index] = Some(one.clone()); + Some(stand.position) + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + if !id_allowed(&m.kind.id) { + continue; + } + let species = m.species(); + let tamed = m.extra.tame; + let equine = matches!( + species, + Species::Horse + | Species::Donkey + | Species::Mule + | Species::SkeletonHorse + | Species::ZombieHorse + | Species::Camel + ); + let slot_free = match (slot.as_str(), armor_index) { + (_, Some(0)) => m.extra.head.is_none(), + (_, Some(1)) => m.extra.chest.is_none(), + (_, Some(2)) => m.extra.legs.is_none(), + (_, Some(3)) => m.extra.feet.is_none(), + ("saddle", _) => !m.extra.saddled, + ("body", _) => species == Species::Horse && m.extra.head.is_none(), + _ => false, + }; + // Mob.canDispenserEquipIntoSlot and the overrides. + let saddle_ok = slot == "saddle" + && (matches!(species, Species::Pig | Species::Strider) || equine && tamed); + let body_ok = slot == "body" && equine && tamed; + if !slot_free || !(m.extra.pick_up_loot || saddle_ok || body_ok) { + continue; + } + if species == Species::Strider && slot == "saddle" && m.is_baby() { + continue; + } + match (slot.as_str(), armor_index) { + (_, Some(0)) => m.extra.head = Some(item.clone()), + (_, Some(1)) => m.extra.chest = Some(item.clone()), + (_, Some(2)) => m.extra.legs = Some(item.clone()), + (_, Some(3)) => m.extra.feet = Some(item.clone()), + ("saddle", _) => m.extra.saddled = true, + _ => m.extra.head = Some(item.clone()), + } + // setGuaranteedDrop / setPersistenceRequired. + m.persistent = true; + Some(m.position) + } + }; + if let (Some(sound), Some(at)) = (sound, at) { + self.audio.play(&sound, Some([at.x, at.y, at.z]), 1.0, 1.0); + } + stack.count -= 1; + return true; + } + false + } + fn dispense_spawn_egg(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); + let front = offset(pos, facing); + if self + .spawn_mob_at(&kind, front, facing != Direction::Up) + .is_none() + { + return (Some(stack), CLICK); + } + (shrink(stack), CLICK) + } + + // ---- ProjectileDispenseBehavior ---- + + fn dispense_projectile(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let item = stack.item.to_string(); + let s = step(facing); + let dir = [f64::from(s[0]), f64::from(s[1]), f64::from(s[2])]; + // ProjectileItem.DispenseConfig per item: position, uncertainty, power, event. + let (at, uncertainty, power, event) = match item.as_str() { + "minecraft:firework_rocket" => ( + Self::dispense_position(pos, facing, 0.500_009_999_999_747_4, [0.0; 3]), + 1.0, + 0.5, + 1004, + ), + "minecraft:fire_charge" => ( + Self::dispense_position(pos, facing, 1.0, [0.0; 3]), + 6.666_666_5, + 1.0, + 1018, + ), + "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" => ( + Self::dispense_position(pos, facing, 0.7, [0.0, 0.1, 0.0]), + 3.0, + 1.375, + LAUNCH, + ), + _ => ( + Self::dispense_position(pos, facing, 0.7, [0.0, 0.1, 0.0]), + 6.0, + 1.1, + LAUNCH, + ), + }; + let one = ItemStack { + count: 1, + ..stack.clone() + }; + match item.as_str() { + "minecraft:experience_bottle" + | "minecraft:splash_potion" + | "minecraft:lingering_potion" => { + let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.launch_thrown(one, at, shot.velocity); + } + "minecraft:firework_rocket" => { + let mut shot = Projectile::new(ProjectileKind::Snowball, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.launch_dispensed_rocket(at, shot.velocity, &one); + } + _ => { + let kind = match item.as_str() { + "minecraft:arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + "minecraft:spectral_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: Some(("minecraft:glowing", 200)), + }, + "minecraft:tipped_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: stack + .potion() + .and_then(horizon_client::brewing::potion) + .and_then(|def| { + def.effects + .iter() + .find(|(id, _, _)| { + !horizon_client::brewing::effect(id) + .is_some_and(|e| e.instant) + }) + .map(|(id, duration, _)| (*id, (duration / 8).max(1))) + }), + }, + "minecraft:fire_charge" => { + // The fireball's own aim is drawn first, then shot along the facing. + let r = &mut self.world.random; + let _ = ( + r.triangle(dir[0], 0.114_85), + r.triangle(dir[1], 0.114_85), + r.triangle(dir[2], 0.114_85), + ); + ProjectileKind::SmallFireball + } + "minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => { + ProjectileKind::Egg + } + _ => ProjectileKind::Snowball, + }; + let mut shot = Projectile::new(kind, at, None); + shot.shoot(&mut self.world.random, dir, power, uncertainty); + self.creatures.projectiles.push(shot); + } + } + (shrink(stack), event) + } + + // ---- entities placed by items ---- + + fn dispense_armor_stand(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let front = offset(pos, facing); + let foot = Vec3::new( + f64::from(front.0) + 0.5, + f64::from(front.1), + f64::from(front.2) + 0.5, + ); + self.next_entity += 1; + let stand = + horizon_client::entities::ArmorStand::new(self.next_entity, foot, y_rot(facing)); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.armor_stands.push(stand); + (shrink(stack), CLICK) + } + /// A tame donkey, mule or llama in front without a chest gets it. + fn dispense_chest(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let front = offset(pos, facing); + for target in self.targets_at(front) { + let Target::Mob(i) = target else { continue }; + let m = &mut self.mobs[i]; + if matches!( + m.species(), + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama + ) && m.extra.tame + && !m.extra.chested + { + m.extra.chested = true; + return (shrink(stack), CLICK); + } + } + (self.default_execute(pos, facing, stack), CLICK) + } + /// `BoatDispenseItemBehavior`. + fn dispense_boat(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let Some(wood) = super::boats::boat_wood(&stack.item).map(str::to_owned) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + let front = offset(pos, facing); + let s = step(facing); + let c = Self::center(pos); + // Boat width 1.375. + let outside = 0.5625 + 1.375 / 2.0; + let (x, y, z) = ( + c[0] + f64::from(s[0]) * outside, + c[1] + f64::from(s[1]) * f64::from(1.125f32), + c[2] + f64::from(s[2]) * outside, + ); + let below = (front.0, front.1 - 1, front.2); + let y_offset = if self.water_at(front) { + 1.0 + } else if self.res.facts.is_air(self.block_at(front)) && self.water_at(below) { + 0.0 + } else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + if !self.boat_models.models.contains_key(&wood) { + return (self.dispense_default(pos, facing, stack), CLICK); + } + self.next_entity += 1; + let boat = super::boats::Boat::new( + self.next_entity, + wood.as_str().into(), + Vec3::new(x, y + y_offset, z), + y_rot(facing), + ); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.boats.push(boat); + (shrink(stack), CLICK) + } + /// `MinecartDispenseItemBehavior`. + fn dispense_minecart(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let Some(kind) = super::minecarts::CartKind::from_id(&stack.item) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + let s = step(facing); + let c = Self::center(pos); + let (x, base_y, z) = ( + c[0] + f64::from(s[0]) * 1.125, + c[1].floor() + f64::from(s[1]), + c[2] + f64::from(s[2]) * 1.125, + ); + let front = offset(pos, facing); + let y_offset = if let Some(rail) = self.rail(front.0, front.1, front.2) { + if rail.shape.is_slope() { 0.6 } else { 0.1 } + } else { + if !self.res.facts.is_air(self.block_at(front)) { + return (self.dispense_default(pos, facing, stack), CLICK); + } + let below = (front.0, front.1 - 1, front.2); + let Some(rail) = self.rail(below.0, below.1, below.2) else { + return (self.dispense_default(pos, facing, stack), CLICK); + }; + if facing != Direction::Down && rail.shape.is_slope() { + -0.4 + } else { + -0.9 + } + }; + self.next_entity += 1; + let cart = super::minecarts::Minecart::new( + self.next_entity, + kind, + Vec3::new(x, base_y + y_offset, z), + ); + self.world.modified.insert((front.0 >> 4, front.2 >> 4)); + self.carts.push(cart); + (shrink(stack), CLICK) + } + + // ---- buckets ---- + + /// The filled bucket behaviour: `DispensibleContainerItem.emptyContents`. + fn dispense_filled_bucket( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let item = stack.item.to_string(); + let target = offset(pos, facing); + let (content, sound, mob) = match item.as_str() { + "minecraft:lava_bucket" => ( + BucketContent::Fluid(FluidKind::Lava), + "minecraft:item.bucket.empty_lava", + None, + ), + "minecraft:water_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty", + None, + ), + "minecraft:powder_snow_bucket" => ( + BucketContent::Powder, + "minecraft:item.bucket.empty_powder_snow", + None, + ), + "minecraft:axolotl_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_axolotl", + Some("axolotl"), + ), + "minecraft:tadpole_bucket" => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_tadpole", + Some("tadpole"), + ), + other => ( + BucketContent::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty_fish", + Some(match other { + "minecraft:salmon_bucket" => "salmon", + "minecraft:cod_bucket" => "cod", + "minecraft:pufferfish_bucket" => "pufferfish", + _ => "tropical_fish", + }), + ), + }; + let target_pos = Self::pos_of(target); + let emptied = self + .with_level(|b, level, ticks| b.bucket_empty(level, ticks, target_pos, content, sound)); + self.process_level_events()?; + if !emptied { + return Ok((self.dispense_default(pos, facing, stack), CLICK)); + } + if self.dim == super::Dim::Nether + && matches!(content, BucketContent::Fluid(FluidKind::Water)) + { + // The water evaporates in a cloud of smoke. + let c = Self::center(target); + for _ in 0..8 { + let r = self.particles.random(); + let p = [ + f64::from(target.0) + (r.next_double() * 2.0 - 1.0), + f64::from(target.1) + (r.next_double() * 2.0 - 1.0), + f64::from(target.2) + (r.next_double() * 2.0 - 1.0), + ]; + let _ = c; + self.particles.add( + &ParticleOptions::simple(ParticleType::LargeSmoke), + p, + [0.0; 3], + ); + } + } else if let Some(kind) = mob { + // MobBucketItem.checkExtraContent. + self.spawn_mob_at(kind, target, true); + } + let bucket = ItemStack::new("minecraft:bucket", 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, bucket), + CLICK, + )) + } + /// The empty bucket: `BucketPickup.pickupBlock`. + fn dispense_empty_bucket( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = Self::pos_of(offset(pos, facing)); + let picked = self.with_level(|b, level, ticks| b.bucket_pickup(level, ticks, target)); + self.process_level_events()?; + match picked { + Some(filled) => { + let filled = ItemStack::new(filled, 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, filled), + CLICK, + )) + } + None => Ok((self.default_execute(pos, facing, stack), CLICK)), + } + } + + // ---- fire, bone meal and TNT ---- + + fn dispense_flint_and_steel( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let target_pos = Self::pos_of(target); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let mut success = true; + if self.res.facts.is_air(state) { + // BaseFireBlock.canBePlacedAt: a fire that survives, or a portal. + let below = self.dispenser_block_name((target.0, target.1 - 1, target.2)); + let fire_name = if matches!(&*below, "minecraft:soul_sand" | "minecraft:soul_soil") { + "minecraft:soul_fire" + } else { + "minecraft:fire" + }; + let fire = self.res.assets.registry.default_state(fire_name); + if let Some(fire) = fire + && self.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) + { + self.level_set([target.0, target.1, target.2], fire)?; + } else if !self.try_light_portal([target.0, target.1, target.2])? { + // Nothing to light; vanilla still counts it as a success. + } + } else if self.prop(state, "lit").as_deref() == Some("false") + && (name.contains("campfire") || name.contains("candle")) + && self.prop(state, "waterlogged").as_deref() != Some("true") + { + if let Some(lit) = self.with_props(state, &[("lit", "true")]) { + self.level_set([target.0, target.1, target.2], lit)?; + } + } else if &*name == "minecraft:tnt" { + if self.ui.rules.bool("tnt_explodes") { + self.spawn_primed_tnt(target_pos, false); + self.with_level(|b, level, ticks| b.remove_block(level, ticks, target_pos, false)); + self.process_level_events()?; + } else { + success = false; + } + } + let event = if success { CLICK } else { FAIL }; + if success { + return Ok((self.hurt_and_break(stack, 1), event)); + } + Ok((Some(stack), event)) + } + fn dispense_bone_meal( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let target_pos = Self::pos_of(target); + let grown = self.with_level(|b, level, ticks| { + b.grow_crop(level, ticks, target_pos) + || b.grow_water_plant(level, ticks, target_pos, None) + }); + if grown { + self.level_events + .push(horizon_world::level::LevelEvent::LevelEvent { + id: 1505, + pos: target_pos, + data: 15, + }); + } + self.process_level_events()?; + if grown { + Ok((shrink(stack), CLICK)) + } else { + Ok((Some(stack), FAIL)) + } + } + fn dispense_tnt(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + if !self.ui.rules.bool("tnt_explodes") { + return (Some(stack), FAIL); + } + let target = Self::pos_of(offset(pos, facing)); + self.spawn_primed_tnt(target, false); + (shrink(stack), CLICK) + } + + // ---- blocks placed by dispensers ---- + + fn dispense_wither_skull( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let free = self.res.facts.is_air(self.block_at(target)) + && target.1 >= horizon_client::chunk::MIN_Y + 2 + && self.ui.difficulty != 0 + && self.can_build_wither(target); + if free { + let rotation = match facing { + Direction::Up | Direction::Down => 0, + other => { + // RotationSegment.convertToSegment: opposite 2D data value * 4. + (match other.opposite() { + Direction::South => 0, + Direction::West => 1, + Direction::North => 2, + _ => 3, + }) * 4 + } + }; + let skull = self + .res + .assets + .registry + .default_state("minecraft:wither_skeleton_skull") + .and_then(|s| self.with_props(s, &[("rotation", &rotation.to_string())])); + if let Some(skull) = skull { + self.level_set([target.0, target.1, target.2], skull)?; + if let Some(entity) = BlockEntity::for_block("minecraft:wither_skeleton_skull") { + self.world.block_entities.insert(target, entity); + } + self.check_wither_spawn([target.0, target.1, target.2])?; + return Ok((shrink(stack), CLICK)); + } + } + let mut stack = stack; + let equipped = self.dispense_equipment(pos, facing, &mut stack); + Ok(( + Some(stack).filter(|s| s.count > 0), + if equipped { CLICK } else { FAIL }, + )) + } + /// `WitherSkullBlock.getOrCreateWitherBase().find(level, pos)`: the soul + /// sand T below the row `head` is in. + fn can_build_wither(&self, head: Pos) -> bool { + let soul = |p: Pos| { + matches!( + &*self.dispenser_block_name(p), + "minecraft:soul_sand" | "minecraft:soul_soil" + ) + }; + let air = |p: Pos| self.res.facts.is_air(self.block_at(p)); + for (ax, az) in [(1, 0), (0, 1)] { + for col in 0..3 { + let left = (head.0 - ax * col, head.1, head.2 - az * col); + let at = |c: i32, row: i32| (left.0 + ax * c, left.1 - row, left.2 + az * c); + if (0..3).all(|c| soul(at(c, 1))) + && soul(at(1, 2)) + && air(at(0, 2)) + && air(at(2, 2)) + { + return true; + } + } + } + false + } + fn dispense_carved_pumpkin( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + if self.res.facts.is_air(self.block_at(target)) + && self.can_spawn_golem([target.0, target.1, target.2]) + { + if let Some(pumpkin) = self + .res + .assets + .registry + .default_state("minecraft:carved_pumpkin") + { + self.level_set([target.0, target.1, target.2], pumpkin)?; + self.check_golem_spawn([target.0, target.1, target.2])?; + } + return Ok((shrink(stack), CLICK)); + } + let mut stack = stack; + let equipped = self.dispense_equipment(pos, facing, &mut stack); + Ok(( + Some(stack).filter(|s| s.count > 0), + if equipped { CLICK } else { FAIL }, + )) + } + /// `ShulkerBoxDispenseBehavior`: place it like a `DirectionalPlaceContext`. + fn dispense_shulker_box( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let front = offset(pos, facing); + let below_empty = self + .res + .facts + .is_air(self.block_at((front.0, front.1 - 1, front.2))); + let clicked_face = if below_empty { facing } else { Direction::Up }; + let front_state = self.block_at(front); + if !(self.res.facts.is_air(front_state) || self.res.facts.get(front_state).replaceable) { + return Ok((Some(stack), FAIL)); + } + let ctx = PlaceContext { + clicked_pos: Self::pos_of(front), + face: clicked_face, + hit: Vec3::new( + f64::from(front.0) + 0.5, + f64::from(front.1), + f64::from(front.2) + 0.5, + ), + inside: false, + yaw: y_rot(facing), + pitch: 0.0, + sneaking: false, + item: stack.item.to_string(), + can_use_game_master_blocks: false, + }; + let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); + let PlaceOutcome::Placed { pos: placed, state } = outcome else { + self.process_level_events()?; + return Ok((Some(stack), FAIL)); + }; + let target = (placed.x, placed.y, placed.z); + if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + self.world.block_entities.insert(target, entity); + self.fill_placed_box([target.0, target.1, target.2], &stack); + } + let sounds = self.res.facts.get(state).sounds.clone(); + self.audio.play( + &sounds.place, + Some(Self::center(target)), + (sounds.volume + 1.0) / 2.0, + sounds.pitch * 0.8, + ); + self.process_level_events()?; + Ok((shrink(stack), CLICK)) + } + + // ---- bottles, glowstone, shears, brush, honeycomb ---- + + fn dispense_glass_bottle( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let honey = self + .prop(state, "honey_level") + .and_then(|v| v.parse::().ok()); + if self.in_block_tag("minecraft:beehives", &name) + && let Some(level) = honey + && level >= 5 + { + // releaseBeesAndResetHoneyLevel (the bees themselves are not modelled). + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set([target.0, target.1, target.2], reset)?; + } + let bottle = ItemStack::new("minecraft:honey_bottle", 1); + return Ok(( + self.consume_with_remainder(pos, facing, stack, bottle), + CLICK, + )); + } + if self.water_at(target) { + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + return Ok(( + self.consume_with_remainder(pos, facing, stack, water), + CLICK, + )); + } + Ok((self.default_execute(pos, facing, stack), FAIL)) + } + fn dispense_glowstone( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + if &*self.dispenser_block_name(target) == "minecraft:respawn_anchor" { + let charge = self + .prop(state, "charges") + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + if charge != 4 { + if let Some(next) = + self.with_props(state, &[("charges", &(charge + 1).to_string())]) + { + self.level_set([target.0, target.1, target.2], next)?; + } + self.audio.play( + "minecraft:block.respawn_anchor.charge", + Some(Self::center(target)), + 1.0, + 1.0, + ); + return Ok((shrink(stack), CLICK)); + } + return Ok((Some(stack), FAIL)); + } + Ok((self.default_execute(pos, facing, stack), CLICK)) + } + fn dispense_shears( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let sheared = self.shear_beehive(target)? || self.shear_entity(target)?; + if sheared { + return Ok((self.hurt_and_break(stack, 1), CLICK)); + } + Ok((Some(stack), FAIL)) + } + fn shear_beehive(&mut self, target: Pos) -> Result { + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + let level = self + .prop(state, "honey_level") + .and_then(|v| v.parse::().ok()); + if !self.in_block_tag("minecraft:beehives", &name) || level.is_none_or(|l| l < 5) { + return Ok(false); + } + self.audio.play( + "minecraft:block.beehive.shear", + Some(Self::center(target)), + 1.0, + 1.0, + ); + // BeehiveBlock.dropHoneycomb, then the honey level resets. + self.pop_resource( + [target.0, target.1, target.2], + ItemStack::new("minecraft:honeycomb", 3), + ); + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set([target.0, target.1, target.2], reset)?; + } + Ok(true) + } + /// `Shearable.shear` on the first ready entity in the block. + fn shear_entity(&mut self, target: Pos) -> Result { + for t in self.targets_at(target) { + let Target::Mob(i) = t else { continue }; + let m = &self.mobs[i]; + let at = [m.position.x, m.position.y, m.position.z]; + match m.species() { + Species::Sheep if !m.extra.sheared && !m.is_baby() => { + let color = + horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; + self.mobs[i].extra.sheared = true; + self.audio + .play("minecraft:entity.sheep.shear", Some(at), 1.0, 1.0); + let stacks = self.res.items.loot_table( + &format!("minecraft:shearing/sheep/{color}"), + false, + None, + &mut self.world.random, + ); + self.drop_sheared(at, stacks); + return Ok(true); + } + Species::Bogged if !m.extra.sheared => { + self.mobs[i].extra.sheared = true; + self.audio + .play("minecraft:entity.bogged.shear", Some(at), 1.0, 1.0); + let stacks = self.res.items.loot_table( + "minecraft:shearing/bogged", + false, + None, + &mut self.world.random, + ); + self.drop_sheared(at, stacks); + return Ok(true); + } + Species::Mooshroom if !m.is_baby() => { + let mushroom = if m.extra.variant == 1 { + "minecraft:brown_mushroom" + } else { + "minecraft:red_mushroom" + }; + let setup = SpawnSetup { + yaw: m.yaw, + persistent: true, + ..Default::default() + }; + self.mobs[i].removed = true; + self.audio + .play("minecraft:entity.mooshroom.shear", Some(at), 1.0, 1.0); + self.handle_mob_events(vec![MobEvent::SpawnKind { + kind: "minecraft:cow".into(), + at, + setup, + }])?; + for _ in 0..5 { + let v = [0.0, 0.2, 0.0]; + self.spawn_item( + ItemStack::new(mushroom, 1), + [at[0], at[1] + 1.0, at[2]], + v, + 10, + ); + } + return Ok(true); + } + _ => {} + } + } + Ok(false) + } + /// The drops of a sheared mob, one entity per item, a block above its feet. + fn drop_sheared(&mut self, at: [f64; 3], stacks: Vec) { + for stack in stacks { + for _ in 0..stack.count { + let r = &mut self.world.random; + let v = [ + f64::from((r.next_float() - r.next_float()) * 0.1), + f64::from(r.next_float() * 0.05), + f64::from((r.next_float() - r.next_float()) * 0.1), + ]; + let one = ItemStack { + count: 1, + ..stack.clone() + }; + self.spawn_item(one, [at[0], at[1] + 1.0, at[2]], v, 10); + } + } + } + /// A brush used on an adult armadillo in front. + fn dispense_brush(&mut self, pos: Pos, facing: Direction, stack: ItemStack) -> Dispensed { + let target = offset(pos, facing); + let armadillo = self.targets_at(target).into_iter().find_map(|t| match t { + Target::Mob(i) if self.mobs[i].species() == Species::Armadillo => Some(i), + _ => None, + }); + let Some(i) = armadillo.filter(|&i| !self.mobs[i].is_baby()) else { + return (Some(stack), FAIL); + }; + let m = &self.mobs[i]; + let at = [m.position.x, m.position.y, m.position.z]; + let drops = self.res.items.loot_table( + "minecraft:brush/armadillo", + false, + None, + &mut self.world.random, + ); + for d in drops { + self.spawn_item(d, [at[0], at[1] + 0.5, at[2]], [0.0, 0.2, 0.0], 10); + } + self.audio + .play("minecraft:entity.armadillo.brush", Some(at), 1.0, 1.0); + (self.hurt_and_break(stack, 16), CLICK) + } + fn dispense_honeycomb( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let state = self.block_at(target); + let name = self.dispenser_block_name(target); + // HoneycombItem.WAXABLES: each copper block has a waxed twin. + let waxed = name.strip_prefix("minecraft:").and_then(|n| { + if n.starts_with("waxed_") { + return None; + } + let twin = format!("minecraft:waxed_{n}"); + let mut s = self.res.assets.registry.state(state)?.clone(); + self.res.assets.registry.default_state(&twin)?; + s.name = twin; + self.res.assets.registry.resolve(&s).ok() + }); + let Some(waxed) = + waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) + else { + return Ok((self.default_execute(pos, facing, stack), CLICK)); + }; + self.level_set([target.0, target.1, target.2], waxed)?; + self.audio.play( + "minecraft:item.honeycomb.wax_on", + Some(Self::center(target)), + 1.0, + 1.0, + ); + Ok((shrink(stack), CLICK)) + } + fn dispense_potion( + &mut self, + pos: Pos, + facing: Direction, + stack: ItemStack, + ) -> Result { + let target = offset(pos, facing); + let water = stack.potion() == Some("minecraft:water"); + let name = self.dispenser_block_name(target); + if !water || !self.in_block_tag("minecraft:convertible_to_mud", &name) { + // The inner default behaviour dispenses, then the potion's own + // events play on top. + return Ok((self.dispense_default(pos, facing, stack), CLICK)); + } + for _ in 0..5 { + let r = self.particles.random(); + let p = [ + f64::from(pos.0) + r.next_double(), + f64::from(pos.1 + 1), + f64::from(pos.2) + r.next_double(), + ]; + self.particles + .add(&ParticleOptions::simple(ParticleType::Splash), p, [0.0; 3]); + } + self.audio.play( + "minecraft:item.bottle.empty", + Some(Self::center(pos)), + 1.0, + 1.0, + ); + if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { + self.level_set([target.0, target.1, target.2], mud)?; + } + let bottle = ItemStack::new("minecraft:glass_bottle", 1); + Ok(( + self.consume_with_remainder(pos, facing, stack, bottle), + CLICK, + )) + } +} diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index c021842e8..2bd400d96 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -24,6 +24,9 @@ pub(super) struct Rocket { explosions: Vec, /// Boosting the player (attachedToEntity). attached: bool, + /// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on + /// the first block it hits. + angled: bool, icon: Option, } fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { @@ -52,6 +55,7 @@ impl Game<'_> { lifetime, explosions, attached, + angled: false, icon: Some("item/firework_rocket".into()), } } @@ -73,6 +77,13 @@ impl Game<'_> { self.swing_arm(); true } + /// `FireworkRocketItem.asProjectile` shot out of a dispenser. + pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) { + let mut rocket = self.new_rocket(at, stack, false); + rocket.velocity = velocity; + rocket.angled = true; + self.rockets.push(rocket); + } /// `FireworkRocketItem.use` while gliding: a rocket attached to the player. pub(super) fn boost_firework(&mut self, stack: &ItemStack) -> bool { if &*stack.item != "minecraft:firework_rocket" @@ -118,12 +129,23 @@ impl Game<'_> { Vec3::new(r.position.x - h, r.position.y, r.position.z - h), Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h), ); - let wanted = Vec3::new( - r.velocity.x * 1.15, - r.velocity.y + 0.04, - r.velocity.z * 1.15, - ); + let wanted = if r.angled { + r.velocity + } else { + Vec3::new( + r.velocity.x * 1.15, + r.velocity.y + 0.04, + r.velocity.z * 1.15, + ) + }; if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) { + let blocked = (moved.x - wanted.x).abs() > 1e-7 + || (moved.y - wanted.y).abs() > 1e-7 + || (moved.z - wanted.z).abs() > 1e-7; + if r.angled && blocked { + // hitTargetOrDeflectSelf: explode on the block. + r.life = r.lifetime; + } let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; r.position = Vec3::new( diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs new file mode 100644 index 000000000..7287c51bd --- /dev/null +++ b/crates/horizon-client/src/game/golems.rs @@ -0,0 +1,82 @@ +//! Building golems from blocks (`CarvedPumpkinBlock.trySpawnGolem`): a carved +//! pumpkin or jack o'lantern on two snow blocks makes a snow golem, and on a +//! T of four iron blocks (arms along X or Z, nothing beside the legs) an iron +//! golem. Players placing the pumpkin and dispensers share it. +use super::Game; +use horizon_client::Result; + +impl Game<'_> { + fn golem_block(&self, p: [i32; 3]) -> &str { + let state = self.world.block(p[0], p[1], p[2]); + &self.res.facts.get(state).name + } + fn is_golem_head(&self, p: [i32; 3]) -> bool { + matches!( + self.golem_block(p), + "minecraft:carved_pumpkin" | "minecraft:jack_o_lantern" + ) + } + /// The blocks of the golem whose head is at `head` and its spawn base + /// (`BlockPattern.find`), snow golems first. + fn find_golem(&self, head: [i32; 3]) -> Option<(&'static str, Vec<[i32; 3]>, [i32; 3])> { + let below = |n: i32| [head[0], head[1] - n, head[2]]; + if self.golem_block(below(1)) == "minecraft:snow_block" + && self.golem_block(below(2)) == "minecraft:snow_block" + { + return Some(( + "minecraft:snow_golem", + vec![head, below(1), below(2)], + below(2), + )); + } + for (ax, az) in [(1, 0), (0, 1)] { + let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s]; + let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block"); + let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2])); + if arms + && self.golem_block(side(0, 2)) == "minecraft:iron_block" + && [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2))) + { + let mut blocks = vec![head]; + blocks.extend((-1..=1).map(|s| side(s, 1))); + blocks.push(side(0, 2)); + return Some(("minecraft:iron_golem", blocks, side(0, 2))); + } + } + None + } + /// `CarvedPumpkinBlock.canSpawnGolem`. + pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool { + self.find_golem(head).is_some() + } + /// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed. + pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> { + if !self.is_golem_head(head) { + return Ok(()); + } + let Some((kind, blocks, base)) = self.find_golem(head) else { + return Ok(()); + }; + for p in blocks { + let state = self.world.block(p[0], p[1], p[2]); + self.destroy_particles(p, state); + self.level_set(p, self.world.air)?; + } + let at = [ + f64::from(base[0]) + 0.5, + f64::from(base[1]) + 0.05, + f64::from(base[2]) + 0.5, + ]; + if let Some(id) = self.spawn_mob(kind, at, false) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.yaw = 0.0; + m.body_yaw = 0.0; + m.head_yaw = 0.0; + m.previous_yaw = 0.0; + m.previous_body_yaw = 0.0; + m.previous_head_yaw = 0.0; + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 835056c09..1ad1d1cec 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -6,15 +6,10 @@ use super::Game; use horizon_client::{ Result, containers::BlockEntity, - entities::Arrow, items::{ItemStack, Items}, world::World, }; -use horizon_core::{ - geometry::{Direction, Vec3}, - position::BlockPos, - random::{LegacyRandom, RandomSource}, -}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; use horizon_world::{level::Behaviours, registry::BlockStateId}; type Pos = (i32, i32, i32); @@ -72,11 +67,6 @@ impl View { } } -thread_local! { - /// Entity-owned randomness (projectile spread), separate from the level random. - static ENTITY_RANDOM: std::cell::RefCell = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45)); -} - fn dir_from_name(name: &str) -> Option { Some(match name { "down" => Direction::Down, @@ -585,14 +575,8 @@ impl Game<'_> { odds += 1; } } - let center = [ - f64::from(pos.x) + 0.5, - f64::from(pos.y) + 0.5, - f64::from(pos.z) + 0.5, - ]; let Some(slot) = slot else { - self.audio - .play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2); + self.dispenser_event(1001, key, 0); return Ok(()); }; let Some(facing) = self @@ -608,7 +592,7 @@ impl Game<'_> { let target = offset(key, facing); let remaining = if dropper { match self.containers().view(target, false) { - None => self.default_dispense(key, facing, stack), + None => self.dispense_default(key, facing, stack), Some(into) => { let one = ItemStack { count: 1, @@ -630,7 +614,7 @@ impl Game<'_> { } } } else { - self.dispense_behaviour(key, facing, stack)? + self.dispense_item(key, facing, stack)? }; if let Some(entry) = self.slot_mut_at(&view, slot) { *entry = remaining; @@ -638,367 +622,6 @@ impl Game<'_> { self.container_changed(key); Ok(()) } - /// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke. - fn default_dispense( - &mut self, - pos: Pos, - facing: Direction, - mut stack: ItemStack, - ) -> Option { - let one = ItemStack { - count: 1, - ..stack.clone() - }; - stack.count -= 1; - self.spawn_dispensed(pos, facing, one, 6); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - (stack.count > 0).then_some(stack) - } - fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) { - let center = [ - f64::from(pos.0) + 0.5, - f64::from(pos.1) + 0.5, - f64::from(pos.2) + 0.5, - ]; - self.audio.play(sound, Some(center), 1.0, pitch); - } - /// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`. - fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) { - let s = step(facing); - let mut at = [ - f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), - f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]), - f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), - ]; - at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 }; - let r = &mut self.world.random; - // new ItemEntity(level, x, y, z, stack): its default motion draws first. - let _ = (r.next_double(), r.next_double()); - let pow = r.next_double() * 0.1 + 0.2; - let spread = 0.017_227_5 * f64::from(accuracy); - let v = [ - r.triangle(f64::from(s[0]) * pow, spread), - r.triangle(0.2, spread), - r.triangle(f64::from(s[2]) * pow, spread), - ]; - self.spawn_item(stack, at, v, 0); - } - /// `DefaultDispenseItemBehavior.consumeWithRemainder`. - fn consume_with_remainder( - &mut self, - pos: Pos, - facing: Direction, - mut stack: ItemStack, - remainder: ItemStack, - ) -> Option { - stack.count -= 1; - if stack.count == 0 { - return Some(remainder); - } - // DispenserBlockEntity.insertItem, then drop what does not fit. - let mut rest = remainder; - if let Some(view) = self.containers().view(pos, false) { - let max = self.containers().max_stack(&rest); - for i in 0..view.len() { - let Some(entry) = self.slot_mut_at(&view, i) else { - continue; - }; - match entry { - None => { - let n = rest.count.min(max); - *entry = Some(ItemStack { - count: n, - ..rest.clone() - }); - rest.count -= n; - } - Some(e) if e.item == rest.item && e.damage == rest.damage => { - let n = rest.count.min(max.saturating_sub(e.count)); - e.count += n; - rest.count -= n; - } - Some(_) => {} - } - if rest.count == 0 { - break; - } - } - } - if rest.count > 0 { - self.spawn_dispensed(pos, facing, rest, 6); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - } - Some(stack) - } - /// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`. - fn dispense_behaviour( - &mut self, - pos: Pos, - facing: Direction, - stack: ItemStack, - ) -> Result> { - let target = offset(pos, facing); - let target_pos = BlockPos::new(target.0, target.1, target.2); - let item = stack.item.to_string(); - let result = match item.as_str() { - "minecraft:bone_meal" => { - let grown = self.with_level(|b, level, ticks| { - b.grow_crop(level, ticks, target_pos) - || b.grow_water_plant(level, ticks, target_pos, None) - }); - self.process_level_events()?; - if grown { - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.audio.play( - "minecraft:item.bone_meal.use", - Some([ - f64::from(target.0) + 0.5, - f64::from(target.1) + 0.5, - f64::from(target.2) + 0.5, - ]), - 1.0, - 1.0, - ); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } else { - self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2); - Some(stack) - } - } - "minecraft:tnt" => { - self.spawn_primed_tnt(target_pos, false); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } - "minecraft:flint_and_steel" => { - let target_state = self.world.block(target.0, target.1, target.2); - let target_name = self.res.facts.get(target_state).name.clone(); - let fire = self.res.assets.registry.default_state("minecraft:fire"); - let success = if self.res.facts.is_air(target_state) - && let Some(fire) = fire - && self - .with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire)) - { - self.level_set([target.0, target.1, target.2], fire)?; - true - } else if &*target_name == "minecraft:tnt" { - self.spawn_primed_tnt(target_pos, false); - self.with_level(|b, level, ticks| { - b.remove_block(level, ticks, target_pos, false) - }); - self.process_level_events()?; - true - } else if self.containers().prop(target_state, "lit") == Some("false") - && (target_name.contains("campfire") || target_name.contains("candle")) - && self.containers().prop(target_state, "waterlogged") != Some("true") - { - let lit = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("lit".into(), "true".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(lit) = lit { - self.level_set([target.0, target.1, target.2], lit)?; - } - true - } else { - false - }; - self.dispenser_sound( - pos, - if success { - "minecraft:block.dispenser.dispense" - } else { - "minecraft:block.dispenser.fail" - }, - if success { 1.0 } else { 1.2 }, - ); - let mut stack = stack; - if success { - stack.damage += 1; - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); - if max > 0 && stack.damage >= max { - return Ok(None); - } - } - Some(stack) - } - "minecraft:water_bucket" | "minecraft:lava_bucket" => { - let fluid = if item == "minecraft:water_bucket" { - "minecraft:water" - } else { - "minecraft:lava" - }; - let target_state = self.world.block(target.0, target.1, target.2); - let f = self.res.facts.get(target_state).clone(); - let waterloggable = item == "minecraft:water_bucket" - && self.containers().prop(target_state, "waterlogged") == Some("false"); - if waterloggable { - let wet = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("waterlogged".into(), "true".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(wet) = wet { - self.level_set([target.0, target.1, target.2], wet)?; - } - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: "minecraft:bucket".into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } else if (self.res.facts.is_air(target_state) || f.replaceable) - && !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid) - && let Some(source) = self.res.assets.registry.default_state(fluid) - { - self.level_set([target.0, target.1, target.2], source)?; - let sound = if fluid == "minecraft:water" { - "minecraft:item.bucket.empty" - } else { - "minecraft:item.bucket.empty_lava" - }; - self.audio.play( - sound, - Some([ - f64::from(target.0) + 0.5, - f64::from(target.1) + 0.5, - f64::from(target.2) + 0.5, - ]), - 1.0, - 1.0, - ); - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: "minecraft:bucket".into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } else { - self.default_dispense(pos, facing, stack) - } - } - "minecraft:bucket" => { - let target_state = self.world.block(target.0, target.1, target.2); - let f = self.res.facts.get(target_state).clone(); - let picked = if f.waterlogged - && self.containers().prop(target_state, "waterlogged") == Some("true") - { - let dry = self - .res - .assets - .registry - .state(target_state) - .cloned() - .and_then(|mut s| { - s.properties.insert("waterlogged".into(), "false".into()); - self.res.assets.registry.resolve(&s).ok() - }); - if let Some(dry) = dry { - self.level_set([target.0, target.1, target.2], dry)?; - } - Some("minecraft:water_bucket") - } else if f.fluid_level == 8 - && !f.fluid_falling - && matches!(&*f.name, "minecraft:water" | "minecraft:lava") - { - self.level_set([target.0, target.1, target.2], self.world.air)?; - Some(if &*f.name == "minecraft:water" { - "minecraft:water_bucket" - } else { - "minecraft:lava_bucket" - }) - } else if &*f.name == "minecraft:powder_snow" { - self.level_set([target.0, target.1, target.2], self.world.air)?; - Some("minecraft:powder_snow_bucket") - } else { - None - }; - match picked { - Some(filled) => { - self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0); - self.consume_with_remainder( - pos, - facing, - stack, - ItemStack { - item: filled.into(), - count: 1, - damage: 0, - extra: None, - }, - ) - } - None => self.default_dispense(pos, facing, stack), - } - } - "minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => { - // ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up. - let s = step(facing); - let at = Vec3::new( - f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]), - f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1, - f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]), - ); - let spread = 0.017_227_5 * 6.0; - let v = ENTITY_RANDOM.with(|r| { - let r = &mut *r.borrow_mut(); - [ - (f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1, - (f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1, - (f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1, - ] - }); - self.arrows.push(Arrow { - from_player: true, - critical: false, - position: at, - previous: at, - velocity: Vec3::new(v[0], v[1], v[2]), - stuck: false, - age: 0, - base_damage: 2.0, - }); - self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2); - Some(ItemStack { - count: stack.count - 1, - ..stack - }) - .filter(|s| s.count > 0) - } - _ => self.default_dispense(pos, facing, stack), - }; - Ok(result) - } } // ---- hopper, dispenser and dropper screens ---- diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 259758994..26b085560 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -90,7 +90,7 @@ const SEAT: f64 = 0.1875 - 0.6; pub(super) const CART_KEY_Y: i32 = -100_000; #[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Shape { +pub(super) enum Shape { NorthSouth, EastWest, AscendingEast, @@ -117,7 +117,7 @@ impl Shape { _ => Self::NorthSouth, } } - fn is_slope(self) -> bool { + pub(super) fn is_slope(self) -> bool { matches!( self, Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth @@ -141,9 +141,9 @@ impl Shape { } } } -struct Rail { +pub(super) struct Rail { name: Arc, - shape: Shape, + pub(super) shape: Shape, powered: bool, } impl Minecart { @@ -203,7 +203,7 @@ impl CartModels { } } impl Game<'_> { - fn rail(&self, x: i32, y: i32, z: i32) -> Option { + pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option { let state = self.world.block(x, y, z); let name = self.res.facts.get(state).name.clone(); if !matches!( diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index ffa2c86da..53f9afe02 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -19,6 +19,18 @@ pub(super) struct ThrownPotion { velocity: Vec3, age: u32, } +impl Game<'_> { + /// A splash potion, lingering potion or experience bottle in flight (the + /// player's throws and dispensers both end up here). + pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { + self.potions.thrown.push(ThrownPotion { + stack, + position, + velocity, + age: 0, + }); + } +} /// Effects, thrown potions and the attribute modifiers last applied. #[derive(Default)] pub(super) struct PotionState { @@ -46,15 +58,19 @@ impl Game<'_> { } Ok(true) } - "minecraft:splash_potion" | "minecraft:lingering_potion" => { + "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:experience_bottle" => { let Some(eye) = self.eye_position() else { return Ok(true); }; let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); - let sound = if &*stack.item == "minecraft:splash_potion" { - "minecraft:entity.splash_potion.throw" - } else { - "minecraft:entity.lingering_potion.throw" + let (sound, power) = match &*stack.item { + "minecraft:splash_potion" => ("minecraft:entity.splash_potion.throw", 0.5), + "minecraft:experience_bottle" => { + ("minecraft:entity.experience_bottle.throw", 0.7) + } + _ => ("minecraft:entity.lingering_potion.throw", 0.5), }; self.audio.play(sound, Some(eye), 0.5, pitch); // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). @@ -74,9 +90,9 @@ impl Game<'_> { let r = &mut self.world.random; let mut jitter = || r.triangle(0.0, 0.0172275); let v = Vec3::new( - (f64::from(dir[0]) / l + jitter()) * 0.5, - (f64::from(dir[1]) / l + jitter()) * 0.5, - (f64::from(dir[2]) / l + jitter()) * 0.5, + (f64::from(dir[0]) / l + jitter()) * power, + (f64::from(dir[1]) / l + jitter()) * power, + (f64::from(dir[2]) / l + jitter()) * power, ); let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity); let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); @@ -85,15 +101,14 @@ impl Game<'_> { v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z, ); - self.potions.thrown.push(ThrownPotion { - stack: ItemStack { + self.launch_thrown( + ItemStack { count: 1, ..stack.clone() }, - position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), - velocity: v, - age: 0, - }); + Vec3::new(eye[0], eye[1] - 0.1, eye[2]), + v, + ); self.swing_arm(); self.consume_held(); Ok(true) @@ -326,19 +341,25 @@ impl Game<'_> { } t.position = next; // ThrowableItemProjectile: drag 0.99 then gravity 0.05. + // ThrownExperienceBottle.getDefaultGravity is 0.07. + let gravity = if &*t.stack.item == "minecraft:experience_bottle" { + 0.07 + } else { + 0.05 + }; t.velocity = Vec3::new( t.velocity.x * 0.99, - t.velocity.y * 0.99 - 0.05, + t.velocity.y * 0.99 - gravity, t.velocity.z * 0.99, ); t.age < 1200 && t.position.y > -128.0 }); // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. for t in &thrown { - let sprite = if &*t.stack.item == "minecraft:lingering_potion" { - "item/lingering_potion" - } else { - "item/splash_potion" + let sprite = match &*t.stack.item { + "minecraft:lingering_potion" => "item/lingering_potion", + "minecraft:experience_bottle" => "item/experience_bottle", + _ => "item/splash_potion", }; let mut fixed = horizon_core::random::LegacyRandom::new(0); let mut p = horizon_client::particles::Particle::terrain( @@ -362,6 +383,36 @@ impl Game<'_> { } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { + if &*stack.item == "minecraft:experience_bottle" { + // ThrownExperienceBottle.onHit: the water-coloured splash (level + // event 2002) and 3 to 11 experience. + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + "minecraft:entity.splash_potion.break", + Some([at.x, at.y, at.z]), + 1.0, + pitch, + ); + for _ in 0..8 { + let v = [ + f64::from(self.world.random.next_float() - 0.5) * 0.3, + 0.2, + f64::from(self.world.random.next_float() - 0.5) * 0.3, + ]; + let p = horizon_client::particles::Particle::terrain( + &mut self.world.random, + [at.x, at.y, at.z], + v, + "item/splash_potion".into(), + 0x38_5DC6, + ); + self.particles.push(p); + } + let r = &mut self.world.random; + let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0); + self.spawn_orbs([at.x, at.y, at.z], value as u32); + return; + } let lingering = &*stack.item == "minecraft:lingering_potion"; let event = if lingering { "minecraft:entity.lingering_potion.break" diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index eff648db2..c7eb83aae 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -53,6 +53,10 @@ pub struct ItemInfo { pub glider: bool, /// `equippable.swappable` and `equip_sound`. pub swappable: bool, + /// `equippable.dispensable` (dispensers may put it on an entity). + pub equip_dispensable: bool, + /// `equippable.allowed_entities` resolved to entity type ids; None allows all. + pub equip_allowed: Option>, pub equip_sound: Option, /// `jukebox_playable`: the jukebox song it plays. pub jukebox_song: Option, @@ -251,6 +255,13 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>, spec: &str) -> HashSet { + match spec.strip_prefix('#') { + Some(tag) => tags.get(tag).cloned().unwrap_or_default(), + None => HashSet::from([spec.to_owned()]), + } +} impl Items { pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let raw: BTreeMap = @@ -264,6 +275,7 @@ impl Items { .or_insert(BlockStateId(i as u32)); } } + let entity_tags = load_tags(root, "entity_type")?; let mut items = HashMap::new(); let mut order = Vec::new(); for (name, c) in &raw { @@ -323,6 +335,19 @@ impl Items { swappable: c["minecraft:equippable"]["swappable"] .as_bool() .unwrap_or(true), + equip_dispensable: c["minecraft:equippable"]["dispensable"] + .as_bool() + .unwrap_or(true), + equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] { + Value::String(spec) => Some(entity_spec(&entity_tags, spec)), + Value::Array(list) => Some( + list.iter() + .filter_map(Value::as_str) + .flat_map(|spec| entity_spec(&entity_tags, spec)) + .collect(), + ), + _ => None, + }, equip_sound: c["minecraft:equippable"]["equip_sound"] .as_str() .map(str::to_owned), diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a15b1e1c6..24dafbf94 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -433,6 +433,8 @@ pub struct Extra { /// Dye colour id (sheep wool, collars). pub color: u8, pub sheared: bool, + /// `Mob.canPickUpLoot` (also lets dispensers equip it). + pub pick_up_loot: bool, pub saddled: bool, pub chested: bool, pub tame: bool, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 1138649b2..266d5baa1 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -299,7 +299,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { S::Wolf => m.extra.variant = biome.wolf, S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => { - // Zombie.finalizeSpawn: 5% babies (normal difficulty). + // Zombie.finalizeSpawn: pick up loot 55% of the time (scaled by + // difficulty), 5% babies (normal difficulty). + m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); if m.random.next_float() < 0.05 { m.extra.age = i32::MIN / 2; } @@ -348,8 +350,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { } // AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on // registration). - S::Skeleton | S::Stray | S::Bogged | S::Parched => populate_armor(m, difficulty), - S::Pillager => m.extra.main_hand = Some("minecraft:crossbow".into()), + S::Skeleton | S::Stray | S::Bogged | S::Parched => { + populate_armor(m, difficulty); + m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special(); + } + S::Pillager => { + m.extra.main_hand = Some("minecraft:crossbow".into()); + m.extra.pick_up_loot = true; + } S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => { super::equine::finalize(m) } @@ -358,6 +366,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { // Piglin.createSpawnWeapon: half crossbows, half golden swords, and // each piece of golden armour one time in ten. S::Piglin if !m.is_baby() => { + m.extra.pick_up_loot = true; for i in 0..4 { if m.random.next_float() < 0.1 { let (slot, piece) = match i { @@ -379,11 +388,16 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { .into(), ); } - S::PiglinBrute => m.extra.main_hand = Some("minecraft:golden_axe".into()), + S::PiglinBrute => { + m.extra.main_hand = Some("minecraft:golden_axe".into()); + m.extra.pick_up_loot = true; + } S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()), S::Villager => { m.extra.variant = villager_type(biome); + m.extra.pick_up_loot = true; } + S::Fox | S::Panda | S::Dolphin => m.extra.pick_up_loot = true, S::TropicalFish => super::aquatic::finalize(m), S::Slime | S::MagmaCube => super::cube::finalize(m), _ => {} diff --git a/crates/horizon-world/src/level/buckets.rs b/crates/horizon-world/src/level/buckets.rs new file mode 100644 index 000000000..8fe4907a9 --- /dev/null +++ b/crates/horizon-world/src/level/buckets.rs @@ -0,0 +1,146 @@ +//! Dispenser use of buckets: `BucketPickup.pickupBlock` for an empty bucket and +//! `DispensibleContainerItem.emptyContents` for filled ones (`BucketItem`, +//! `MobBucketItem`, `SolidBucketItem`), both without a player. +use super::{ + Behaviours, Dimension, LevelAccess, Sim, Ticks, + classes::{Class, Interface}, +}; +use crate::{ + fluid::{FluidKind, FluidState}, + registry::BlockStateId, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use std::sync::Arc; + +/// What a filled bucket empties into the world. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BucketContent { + /// Water or lava (mob buckets hold water). + Fluid(FluidKind), + /// `SolidBucketItem`: the block placed into an empty space (powder snow). + Powder, +} + +impl Sim<'_, L> { + /// `BucketPickup.pickupBlock(null, level, pos, state)`: the filled bucket + /// that results, None when the block gives nothing. + pub(crate) fn bucket_pickup(&mut self, pos: BlockPos) -> Option<&'static str> { + let b = self.b; + let state = self.state(pos); + let item = if b.instance_of(state, Class::Liquid) { + match b.fluid(state).kind() { + FluidKind::Water | FluidKind::FlowingWater => "minecraft:water_bucket", + FluidKind::Lava | FluidKind::FlowingLava => "minecraft:lava_bucket", + FluidKind::Empty => return None, + } + } else if b.implements(state, Interface::SimpleWaterlogged) + && b.table.has(state, b.props.waterlogged) + { + "minecraft:water_bucket" + } else if b.is_block(state, b.named.powder_snow) { + "minecraft:powder_snow_bucket" + } else { + return None; + }; + self.pickup_block(pos, state).then_some(item) + } + /// `BucketItem.emptyContents(null, level, pos, null)`. `sound` is the + /// bucket's empty sound (mob buckets have their own). + pub(crate) fn bucket_empty( + &mut self, + pos: BlockPos, + content: BucketContent, + sound: &str, + ) -> bool { + let b = self.b; + let fluid = match content { + BucketContent::Powder => { + if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) { + let snow = b.table.default_state(b.named.powder_snow); + self.set_block_and_update(pos, snow); + self.game_event(pos, "minecraft:fluid_place"); + self.empty_sound(pos, sound); + return true; + } + return false; + } + BucketContent::Fluid(fluid) => fluid, + }; + let state = self.state(pos); + // canBeReplaced(fluid): replaceable or not solid (portals refuse). + let may_replace = !b.instance_of(state, Class::EndPortal) + && !b.instance_of(state, Class::EndGateway) + && (b.is_replaceable(state) || !b.is_solid(state)); + let liquid_container = self.is_liquid_container(state); + let container = liquid_container && self.can_place_liquid(state, fluid); + let place_liquid = may_replace || container; + if !(b.is_air(state) || place_liquid) { + return false; + } + let water = matches!(fluid, FluidKind::Water | FluidKind::FlowingWater); + if water && self.level.dimension() == Dimension::Nether { + // WATER_EVAPORATES: the water hisses away. + let pitch = 2.6 + (self.random().next_float() - self.random().next_float()) * 0.8; + self.emit(super::LevelEvent::Sound { + pos, + sound: "minecraft:block.fire.extinguish".into(), + volume: 0.5, + pitch, + }); + return true; + } + if liquid_container && water { + self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false)); + self.empty_sound(pos, sound); + return true; + } + if may_replace && !b.instance_of(state, Class::Liquid) { + self.destroy_block(pos, true, super::flags::UPDATE_LIMIT); + } + let source = FluidState::new( + if water { + FluidKind::Water + } else { + FluidKind::Lava + }, + 8, + false, + ); + let legacy: BlockStateId = b.legacy_block(source); + if !self.set_block(pos, legacy, super::flags::UPDATE_ALL_IMMEDIATE) + && !self.fluid_at(pos).is_source() + { + return false; + } + self.empty_sound(pos, sound); + true + } + fn empty_sound(&mut self, pos: BlockPos, sound: &str) { + let sound: Arc = sound.into(); + self.sound(pos, &sound, 1.0, 1.0); + self.game_event(pos, "minecraft:fluid_place"); + } +} + +impl Behaviours { + /// `BucketPickup.pickupBlock` by a dispenser: the filled bucket item. + pub fn bucket_pickup( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> Option<&'static str> { + self.sim(level, ticks).bucket_pickup(pos) + } + /// `DispensibleContainerItem.emptyContents(null, level, pos, null)`. + pub fn bucket_empty( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + content: BucketContent, + sound: &str, + ) -> bool { + self.sim(level, ticks).bucket_empty(pos, content, sound) + } +} diff --git a/crates/horizon-world/src/level/fluids.rs b/crates/horizon-world/src/level/fluids.rs index d1017fb34..b778f6511 100644 --- a/crates/horizon-world/src/level/fluids.rs +++ b/crates/horizon-world/src/level/fluids.rs @@ -178,7 +178,7 @@ impl Sim<'_, L> { // ---- liquid containers ---- /// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause). - fn is_liquid_container(&self, state: BlockStateId) -> bool { + pub(super) fn is_liquid_container(&self, state: BlockStateId) -> bool { self.b.implements(state, Interface::LiquidBlockContainer) || self.b.implements(state, Interface::SimpleWaterlogged) } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a066cafc..1a05bbb11 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -101,6 +101,7 @@ pub mod states; pub mod ticks; mod bonemeal; +mod buckets; mod falling; mod feature_world; mod fluids; @@ -126,6 +127,7 @@ mod growth_tests; #[cfg(test)] mod tests; +pub use buckets::BucketContent; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; pub use falling::Landing; pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index c1ffce5a1..28c9ac73d 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -917,3 +917,66 @@ fn dripstone_fills_cauldrons() { } assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]"); } + +#[test] +fn dispenser_buckets_pick_up_and_empty() { + let mut w = world!(); + let at = BlockPos::new(0, 10, 0); + let water = w.id("water", &[("level", "0")]); + w.put(at, water); + let picked = w.b().bucket_pickup(&mut w.level, &mut w.ticks, at); + assert_eq!(picked, Some("minecraft:water_bucket")); + assert_eq!(w.get(at), w.b().air()); + // Flowing water gives nothing. + let flowing = w.id("water", &[("level", "3")]); + w.put(at, flowing); + assert_eq!(w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), None); + // A waterlogged slab is drained and stays a slab. + let slab = w.id("oak_slab", &[("waterlogged", "true")]); + w.put(at, slab); + assert_eq!( + w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), + Some("minecraft:water_bucket") + ); + assert_eq!(w.prop(at, "waterlogged"), "false"); + // Powder snow comes up as its bucket. + let snow = w.id("powder_snow", &[]); + w.put(at, snow); + assert_eq!( + w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), + Some("minecraft:powder_snow_bucket") + ); + // Emptying water into air makes a source; stone refuses. + let sound = "minecraft:item.bucket.empty"; + let content = BucketContent::Fluid(crate::fluid::FluidKind::Water); + assert!( + w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + assert_eq!(w.name(at), "water[level=0]"); + let stone = w.id("stone", &[]); + w.put(at, stone); + assert!( + !w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + // Water fills a waterloggable slab instead of replacing it. + let dry = w.id("oak_slab", &[]); + w.put(at, dry); + assert!( + w.b() + .bucket_empty(&mut w.level, &mut w.ticks, at, content, sound) + ); + assert_eq!(w.prop(at, "waterlogged"), "true"); + // Powder snow only goes into empty space. + let air = w.b().air(); + w.put(at, air); + assert!(w.b().bucket_empty( + &mut w.level, + &mut w.ticks, + at, + BucketContent::Powder, + "minecraft:item.bucket.empty_powder_snow" + )); + assert_eq!(w.name(at), "powder_snow[]"); +} From 2ad11eb68d619539b56e9a36ebbc744d0088e2f7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:15:05 +0200 Subject: [PATCH 3/7] Add the creaking and the creaking heart A creaking heart in a pale oak trunk now follows its logs: placed or updated between two logs on its axis it wakes at night (12600 to 23400 in the overworld) or goes dormant by day, and stays uprooted without them. An awake heart with a player within 32 blocks spawns a linked creaking within 16 blocks, keeps its UUID in the saved block entity, reports the distance to it as a comparator signal, and lets it go when the day comes, it strays more than 34 blocks or a player stands inside it. The creaking freezes while any player looks at it, wakes when one looks from within 12 blocks, then hunts the nearest visible player and hits every 40 ticks. Bound to a heart it takes no damage; hits only make it sway and, when a player did it, make the heart send trail particles and sometimes spread resin clumps over nearby logs. Breaking the heart makes its creaking twitch to death, and removing the block any other way tears it down in a burst of crumbling pale oak. It has the vanilla model, animations (walk, attack, invulnerable, death), glowing eyes, sounds and NBT home_pos, and the trail particle exists now. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/containers.rs | 32 +- crates/horizon-client/src/entity_nbt.rs | 14 + crates/horizon-client/src/game.rs | 22 +- crates/horizon-client/src/game/creaking.rs | 663 ++++++++++++++++++++ crates/horizon-client/src/game/creatures.rs | 8 + crates/horizon-client/src/game/persist.rs | 10 +- crates/horizon-client/src/mobs.rs | 12 + crates/horizon-client/src/mobs/ai.rs | 22 +- crates/horizon-client/src/mobs/anim.rs | 2 + crates/horizon-client/src/mobs/creaking.rs | 365 +++++++++++ crates/horizon-client/src/mobs/goals.rs | 9 +- crates/horizon-client/src/mobs/living.rs | 7 +- crates/horizon-client/src/mobs/render.rs | 15 +- crates/horizon-client/src/mobs/species.rs | 15 + crates/horizon-client/src/particles.rs | 52 ++ crates/horizon-client/src/save.rs | 48 +- crates/horizon-world/src/level/creaking.rs | 83 +++ crates/horizon-world/src/level/data.rs | 2 + crates/horizon-world/src/level/mod.rs | 1 + crates/horizon-world/src/level/place.rs | 7 +- crates/horizon-world/src/level/tests.rs | 50 ++ crates/horizon-world/src/level/tick.rs | 1 + 22 files changed, 1426 insertions(+), 14 deletions(-) create mode 100644 crates/horizon-client/src/game/creaking.rs create mode 100644 crates/horizon-client/src/mobs/creaking.rs create mode 100644 crates/horizon-world/src/level/creaking.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..486b55235 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,20 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// `CreakingHeartBlockEntity`: its protector and the hurt emitter. + CreakingHeart(Box), +} +/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`). +#[derive(Clone, Debug, Default)] +pub struct CreakingHeart { + /// The protector: its entity id once resolved, and its UUID (the saved form). + pub creaking: Option<(Option, [i32; 4])>, + pub ticks_existed: i64, + pub ticker: i32, + /// Ticks left of the hurt effect (`emitter`) and where it heads. + pub emitter: i32, + pub emitter_target: Option<[f64; 3]>, + pub output_signal: i32, } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -101,6 +115,9 @@ impl BlockEntity { speed: 1.0, })); } + if name == "minecraft:creaking_heart" { + return Some(Self::CreakingHeart(Box::default())); + } if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } @@ -155,6 +172,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::CreakingHeart(_) => "minecraft:creaking_heart", } } pub fn contents(&self) -> Vec { @@ -164,7 +182,7 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) => Vec::new(), + Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), } } @@ -173,7 +191,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::CreakingHeart(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +203,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::CreakingHeart(_) => &mut [], } } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 02ab14543..bd45054ac 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -246,6 +246,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("equipment".into(), Tag::Compound(equipment)); } + "minecraft:creaking" => { + // home_pos: the heart it is bound to. + if let Some(home) = m.extra.home { + map.insert("home_pos".into(), Tag::IntArray(home.to_vec())); + } else { + map.remove(&"home_pos".into()); + } + } "minecraft:villager" => { use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; let data = Tag::compound([ @@ -563,6 +571,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.egg_time = -1 - 400; } } + if m.species() == crate::mobs::Species::Creaking + && let Some(Tag::IntArray(home)) = tag.get("home_pos") + && home.len() == 3 + { + crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]); + } if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cd921c878..6b705f8f1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -13,6 +13,7 @@ mod chat; mod combat; mod commands; mod control; +mod creaking; mod creatures; mod crossbow; mod dispenser; @@ -307,6 +308,17 @@ impl LevelAccess for GameLevel<'_> { if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) { return comparator; } + if let Some(signal) = creaking::heart_signal(self.world, pos) { + return if self.registry.state(_state).is_some_and(|s| { + s.properties + .get("creaking_heart_state") + .is_some_and(|v| v == "uprooted") + }) { + 0 + } else { + signal + }; + } if let Some(signal) = books::lectern_signal(self.world, pos) { return signal; } @@ -613,6 +625,7 @@ struct Game<'a> { hook: Option, tridents: Vec, rockets: Vec, + creaking: creaking::CreakingState, trident_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, @@ -1609,6 +1622,7 @@ impl Game<'_> { None } .unwrap_or(self.world.air); + self.creaking_heart_broken(pos); if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) { // Containers.dropContents (shulker boxes keep theirs). let name = facts.name.clone(); @@ -3043,7 +3057,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3268,7 +3283,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -4312,6 +4328,7 @@ impl Game<'_> { self.tick_hoppers()?; self.tick_jukeboxes(); self.tick_beacons(); + self.tick_creaking_hearts()?; // ChestLidController: 0.1 per tick towards open/closed. if let Some(key) = self.container { self.chest_open.entry(key).or_insert((0.0, 0.0)); @@ -7671,6 +7688,7 @@ pub fn run() -> Result<()> { hook: None, tridents: Vec::new(), rockets: Vec::new(), + creaking: Default::default(), trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), tnts: Vec::new(), hoppers: HashMap::new(), diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs new file mode 100644 index 000000000..98727ba8b --- /dev/null +++ b/crates/horizon-client/src/game/creaking.rs @@ -0,0 +1,663 @@ +//! 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; +use horizon_client::{ + Result, + containers::{BlockEntity, CreakingHeart}, + mobs::creaking, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource}; +use horizon_world::registry::BlockStateId; +use std::collections::{HashSet, VecDeque}; + +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))? { + BlockEntity::CreakingHeart(h) => Some(h.output_signal), + _ => None, + } +} + +impl Game<'_> { + fn heart_state_name(&self, state: BlockStateId) -> String { + self.res + .assets + .registry + .state(state) + .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; + }; + 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)); + } + } + } + } + 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() + } + /// 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) { + if !by_player { + return; + } + let key = (home[0], home[1], home[2]); + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + 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); + } + self.world + .block_entities + .insert(key, BlockEntity::CreakingHeart(heart)); + } + /// `Creaking.tearDown`: the crumble particles. + pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { + let registry = self.res.assets.registry; + let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| { + let Some(mut state) = registry + .default_state(name) + .and_then(|s| registry.state(s).cloned()) + else { + return; + }; + for (k, v) in props { + state.properties.insert((*k).to_owned(), (*v).to_owned()); + } + let Ok(id) = registry.resolve(&state) else { + return; + }; + let Some((sprite, tint)) = this.particle_sprite(id) else { + return; + }; + for _ in 0..count { + let r = &mut this.world.random; + let p = [ + center[0] + r.next_gaussian() * spread[0], + center[1] + r.next_gaussian() * spread[1], + center[2] + r.next_gaussian() * spread[2], + ]; + this.particles.add( + &ParticleOptions::block(ParticleType::BlockCrumble, sprite.clone(), tint), + p, + [0.0; 3], + ); + } + }; + crumble(self, "minecraft:pale_oak_wood", &[], 100); + crumble( + self, + "minecraft:creaking_heart", + &[("creaking_heart_state", "awake")], + 10, + ); + } + /// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to + /// death and a natural heart drops experience. + pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + else { + return; + }; + self.heart_remove_protector(&mut heart, true); + let state = self.world.block(key.0, key.1, key.2); + if self.prop_is(state, "natural") && !self.creative && !self.spectator() { + let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; + self.spawn_orbs( + [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ], + xp, + ); + } + self.world + .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 + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_))) + .map(|(k, _)| *k) + .collect(); + for key in keys { + let Some(BlockEntity::CreakingHeart(mut heart)) = + self.world.block_entities.remove(&key) + else { + continue; + }; + 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); + continue; + } + if self.heart_state_name(state) != "uprooted" { + self.heart_tick(&mut heart, key, state)?; + } + self.world + .block_entities + .insert(key, BlockEntity::CreakingHeart(heart)); + } + 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)) + } + /// Hearts that came with generated or loaded chunks get their block + /// entity (`newBlockEntity`) the first time their chunk is seen. + fn scan_for_hearts(&mut self) { + let Some(heart) = self + .res + .assets + .registry + .default_state("minecraft:creaking_heart") + else { + return; + }; + let keys: Vec<(i32, i32)> = self + .world + .chunks + .iter() + .filter(|(k, c)| c.lit && !self.creaking.scanned.contains(k)) + .map(|(k, _)| *k) + .collect(); + for key in keys { + self.creaking.scanned.insert(key); + let Some(chunk) = self.world.chunks.get(&key).cloned() else { + continue; + }; + let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name; + let _ = heart; + for (si, section) in chunk.sections.iter().enumerate() { + if section.is_uniform(0) { + continue; + } + for i in 0..4096 { + let id = section.get(i); + if name(id) != "minecraft:creaking_heart" { + continue; + } + let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32); + let pos = ( + key.0 * 16 + lx, + horizon_client::chunk::MIN_Y + si as i32 * 16 + ly, + key.1 * 16 + lz, + ); + self.world + .block_entities + .entry(pos) + .or_insert_with(|| BlockEntity::CreakingHeart(Box::default())); + } + } + } + let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); + self.creaking.scanned.retain(|k| loaded.contains(k)); + } +} + +/// What the creaking code remembers between ticks. +#[derive(Default)] +pub(super) struct CreakingState { + /// Chunks already scanned for heart blocks. + scanned: HashSet<(i32, i32)>, +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f2cbf245e..7f13adffc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -970,6 +970,14 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::CreakingHurt { + home, + by_player, + id, + } => self.creaking_hurt(home, id, by_player), + MobEvent::CreakingTearDown { center, spread } => { + self.creaking_tear_down(center, spread) + } MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 548ae34ee..46e934092 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -269,9 +269,17 @@ impl Game<'_> { } self.persist.raw.insert(id, tag); } - fn uuid_for(&mut self, id: u32) -> [i32; 4] { + 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.rs b/crates/horizon-client/src/mobs.rs index 24dafbf94..f53eb3901 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -11,6 +11,7 @@ pub mod anim; pub mod aquatic; pub mod camel; pub mod control; +pub mod creaking; pub mod cube; pub mod data; pub mod enderman; @@ -664,6 +665,17 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it). + CreakingHurt { + home: [i32; 3], + by_player: bool, + id: u32, + }, + /// `Creaking.tearDown`: crumbling particles around the creaking. + CreakingTearDown { + center: [f64; 3], + spread: [f64; 3], + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d7a9e0084..a0ae29a97 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -87,6 +87,7 @@ pub enum Family { Wither, Allay, Villager, + Creaking, } pub fn family(s: Species) -> Family { use Species as S; @@ -121,6 +122,7 @@ pub fn family(s: Species) -> Family { S::Ravager => Family::Ravager, S::Wither => Family::Wither, S::Allay => Family::Allay, + S::Creaking => Family::Creaking, S::Villager => Family::Villager, S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin, S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => { @@ -169,6 +171,7 @@ pub fn register(m: &mut Mob) { Family::Wither => super::wither::register(m), Family::Allay => super::allay::register(m), Family::Villager => super::villager::register(m), + Family::Creaking => super::creaking::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -251,7 +254,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { return false; } base_tick(m, w, events); - if m.death_time >= 20 { + if m.death_time >= super::creaking::death_limit(m) { + // Creaking.tickDeath: a heart's creaking crumbles away. + if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) { + super::creaking::tear_down(m, events); + } return false; } ai_step(m, w, events); @@ -391,6 +398,8 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air", Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return, Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item", + // Creaking.getAmbientSound: silent while awake. + Species::Creaking if m.extra.flag => return, // Shulker.playAmbientSound: silent while closed. Species::Shulker if m.extra.counter == 0 => return, Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", @@ -405,6 +414,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if super::creaking::is_creaking(m) { + super::creaking::update(m, w, events); + } if m.ai.no_jump_delay > 0 { m.ai.no_jump_delay -= 1; } @@ -486,6 +498,10 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { /// Mob.serverAiStep fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.ai.no_action_time += 1; + // A creaking looked at stands still. + if super::creaking::is_creaking(m) && !super::creaking::can_move(m) { + return; + } // A saddled mount follows its rider instead of its goals. if super::equine::controlled(m) { super::equine::ridden_step(m); @@ -664,6 +680,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { match m.species() { // Allay.hurtServer: its liked player cannot hurt it. Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false, + Species::Creaking => super::creaking::accepts_damage(m, source), Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false), Species::Shulker => super::shulker::accepts(m, source), Species::Enderman => super::enderman::on_damage(m, source), @@ -707,6 +724,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if m.species() == Species::Ravager { super::ravager::on_attack(m, cx.events); } + if super::creaking::is_creaking(m) { + super::creaking::on_attack(m, cx.events); + } let mut amount = m.attrs.attack_damage; let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index f56e504a4..ae44a2630 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -9,6 +9,7 @@ use std::f32::consts::PI; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Anim { Allay, + Creaking, Camel, Wither, Vex, @@ -346,6 +347,7 @@ pub fn setup( match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), + Anim::Creaking => super::creaking::anim(m, s, p, w_anims), Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { super::aquatic::anim(m, s, p) } diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs new file mode 100644 index 000000000..0a2e8603a --- /dev/null +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -0,0 +1,365 @@ +//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at +//! them, wake up when one looks from within 12 blocks, then hunt the nearest +//! visible player and hit every 40 ticks. One bound to a creaking heart takes +//! no damage (it only sways and hurts the heart's resin spreader), dies when +//! the heart no longer protects it and falls apart with the heart. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone}, + keyframes::Animation, + path::PathType, +}; +use crate::containers::BlockEntity; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::HashMap; + +/// `Extra.ints` slots. +const INVULNERABLE: usize = 0; +const ATTACKING: usize = 1; +const STUCK: usize = 2; +const TEARING_DOWN: usize = 3; +const EYES: usize = 4; +const NEXT_FLICKER: usize = 5; +/// `Extra.counter` bits: hurt while protected, and by a player. +const HURT: i32 = 1; +const HURT_BY_PLAYER: i32 = 2; + +/// `Creaking.ACTIVATION_RANGE_SQ`. +const ACTIVATION_RANGE_SQ: f64 = 144.0; +/// `Creaking.INVULNERABILITY_ANIMATION_DURATION` and the attack animation. +const INVULNERABILITY_TICKS: i32 = 8; +const ATTACK_TICKS: i32 = 15; +/// `Creaking.TWITCH_DEATH_DURATION`. +const TWITCH_TICKS: i32 = 45; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(2, MeleeAttack::new(1.0, false).interval(40)); + g.add(5, Stroll::avoiding_water(0.3)); + g.add(6, LookAtPlayer::new(8.0)); + m.ai.targets.add(1, HuntPlayer); +} +/// Bound to a heart (`getHomePos() != null`). +pub fn heart_bound(m: &Mob) -> bool { + is_creaking(m) && m.extra.home.is_some() +} +pub fn tearing_down(m: &Mob) -> bool { + is_creaking(m) && m.extra.ints[TEARING_DOWN] != 0 +} +/// `Creaking.canMove`: false while a player looks at it. +pub fn can_move(m: &Mob) -> bool { + !m.extra.flag2 +} +/// `Creaking.isActive`. +pub fn is_active(m: &Mob) -> bool { + m.extra.flag +} +/// `Creaking.setTransient`: bind to the heart at `pos` and avoid damage. +pub fn set_transient(m: &mut Mob, pos: [i32; 3]) { + m.extra.home = Some(pos); + m.set_malus(PathType::Damaging, 8.0); + m.set_malus(PathType::PowderSnow, 8.0); + m.set_malus(PathType::Lava, 8.0); + m.set_malus(PathType::Fire, 0.0); + m.set_malus(PathType::FireInNeighbor, 0.0); +} +/// `Creaking.setTearingDown`: the heart was broken by someone. +pub fn set_tearing_down(m: &mut Mob) { + m.extra.ints[TEARING_DOWN] = 1; +} +/// `Creaking.hasGlowingEyes` / `isActive`: the eyes layer shows. +pub fn eyes_glowing(m: &Mob) -> bool { + if tearing_down(m) { + m.extra.ints[EYES] != 0 + } else { + is_active(m) + } +} +/// Ticks of death animation before the mob is removed (`tickDeath`). +pub fn death_limit(m: &Mob) -> i32 { + if heart_bound(m) && tearing_down(m) { + TWITCH_TICKS + 1 + } else { + 20 + } +} +/// `Creaking.tearDown`: crumbles away. +pub fn tear_down(m: &mut Mob, events: &mut Vec) { + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + events.push(MobEvent::CreakingTearDown { + center: [ + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ], + spread: [ + (hi.x - lo.x) * 0.3, + (hi.y - lo.y) * 0.3, + (hi.z - lo.z) * 0.3, + ], + }); + m.voice("entity.creaking.death", events); + m.removed = true; +} +/// `Creaking.hurtServer` for a heart-bound creaking: no damage, only the +/// invulnerability animation and the heart's reaction. Returns whether the +/// normal damage path should run. +pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool { + if !heart_bound(m) || source.kind == DamageKind::Generic { + return true; + } + if source.is_fire() || !m.alive() || m.extra.ints[INVULNERABLE] > 0 { + return false; + } + let by_player = source.attacker == Some(Who::Player); + // The direct entity must be living or a projectile (or a player must be to blame). + let direct = matches!( + source.kind, + DamageKind::PlayerAttack + | DamageKind::MobAttack + | DamageKind::Arrow + | DamageKind::Thrown + | DamageKind::Fireball + | DamageKind::Thorns + ); + if !direct && !by_player { + return false; + } + m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS; + m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 }; + false +} +/// `Creaking.doHurtTarget` extras: the attack animation and sound. +pub fn on_attack(m: &mut Mob, events: &mut Vec) { + m.extra.ints[ATTACKING] = ATTACK_TICKS; + m.voice("entity.creaking.attack", events); +} +/// The heart this creaking is bound to protects it (`isProtector`); a link +/// read from a save is trusted until the heart resolves it. +fn protected(m: &Mob, w: &MobWorld) -> bool { + let Some(home) = m.extra.home else { + return true; + }; + match w.world.block_entities.get(&(home[0], home[1], home[2])) { + Some(BlockEntity::CreakingHeart(h)) => match h.creaking { + Some((Some(id), _)) => id == m.id, + Some((None, _)) => true, + None => false, + }, + _ => false, + } +} +/// `Creaking.tick` and the start of `aiStep`: protection, timers, freezing. +pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + // Creaking.tick: without its heart's protection it dies. + if heart_bound(m) && m.alive() && !protected(m, w) { + m.health = 0.0; + } + for slot in [INVULNERABLE, ATTACKING] { + if m.extra.ints[slot] > 0 { + m.extra.ints[slot] -= 1; + } + } + let age = m.age as f32; + m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); + m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); + m.anim.states[2].animate_when(tearing_down(m), age); + if m.extra.counter & HURT != 0 { + // hurtServer: sway, and the heart reacts to a player's hit. + if protected(m, w) { + let by_player = m.extra.counter & HURT_BY_PLAYER != 0; + if let Some(home) = m.extra.home { + events.push(MobEvent::CreakingHurt { + home, + by_player, + id: m.id, + }); + } + m.voice("entity.creaking.sway", events); + } + m.extra.counter &= !(HURT | HURT_BY_PLAYER); + } + // checkEyeBlink: the eyes of a creaking falling apart flicker. + if m.death_time > m.extra.ints[NEXT_FLICKER] { + let glowing = m.extra.ints[EYES] != 0; + let (lo, hi) = if glowing { + (2, 8) + } else { + (m.death_time / 4, m.death_time / 2) + }; + let span = (hi - lo + 1).max(1); + m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); + m.extra.ints[EYES] = i32::from(!glowing); + } + if !m.alive() { + return; + } + let now = check_can_move(m, w, events); + if now != can_move(m) { + if now { + m.voice("entity.creaking.unfreeze", events); + } else { + stop_in_place(m); + m.voice("entity.creaking.freeze", events); + } + m.extra.flag2 = !now; + } +} +/// `Mob.stopInPlace`. +pub fn stop_in_place(m: &mut Mob) { + m.nav_stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.zza = 0.0; + m.ai.speed = 0.0; +} +fn activate(m: &mut Mob, events: &mut Vec) { + m.ai.target = Some(Who::Player); + m.voice("entity.creaking.activate", events); + m.extra.flag = true; +} +fn deactivate(m: &mut Mob, events: &mut Vec) { + m.ai.target = None; + m.voice("entity.creaking.deactivate", events); + m.extra.flag = false; +} +/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`. +fn looked_at_by(m: &Mob, w: &MobWorld) -> bool { + let Some(p) = &w.player else { return false }; + let look = p.look; + let eye = m.eye_y(); + [eye, m.position.y + 0.5, (eye + m.position.y) / 2.0] + .into_iter() + .any(|y| { + let d = [ + m.position.x - p.position.x, + y - p.eye[1], + m.position.z - p.position.z, + ]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if len < 1.0e-6 { + return true; + } + let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len; + dot > 0.5 + && w.line_of_sight( + Vec3::new(p.eye[0], p.eye[1], p.eye[2]), + Vec3::new(m.position.x, y, m.position.z), + ) + }) +} +/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it. +fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { + let active = is_active(m); + // NEAREST_PLAYERS: players within the follow range. + let near = w.player.as_ref().filter(|p| { + let d = Vec3::new(p.position.x, p.position.y, p.position.z); + m.distance_sqr(d) < 32.0 * 32.0 + }); + let Some(p) = near else { + if active { + deactivate(m, events); + } + return true; + }; + // canAttack: alive and not creative or spectator. + let attackable = p.alive && !p.creative; + if attackable { + // GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake. + let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin"); + if (!active || !disguised) && looked_at_by(m, w) { + if active { + return false; + } + if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ { + activate(m, events); + return false; + } + } + } else if active { + deactivate(m, events); + } + true +} +/// `Creaking.playerIsStuckInYou`: the player's eyes inside it for more than 4 ticks. +pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool { + let Some(eye) = eye else { + m.extra.ints[STUCK] = 0; + return false; + }; + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let inside = eye[0] >= lo.x + && eye[0] <= hi.x + && eye[1] >= lo.y + && eye[1] <= hi.y + && eye[2] >= lo.z + && eye[2] <= hi.z; + if inside { + m.extra.ints[STUCK] += 1; + m.extra.ints[STUCK] > 4 + } else { + m.extra.ints[STUCK] = 0; + false + } +} +/// The nearest attackable player the creaking can see. +fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = &cx.w.player else { + return false; + }; + let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2); + p.alive && !p.creative && near && m.sees(cx.w, Who::Player) +} +/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the +/// nearest visible player. +#[derive(Clone, Debug)] +struct HuntPlayer; +impl Goal for HuntPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !is_active(m) || !sees_attackable_player(m, cx) { + return false; + } + m.ai.target = Some(Who::Player); + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx) + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + if m.ai.target == Some(Who::Player) { + m.ai.target = None; + } + } +} +/// `CreakingModel.setupAnim`. +pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap) { + p.xrot("head", s.x_rot.to_radians()); + p.yrot("head", s.y_rot.to_radians()); + let get = |n: &str| animations.get(&format!("CreakingAnimation.CREAKING_{n}")); + if can_move(m) + && let Some(walk) = get("WALK") + { + walk.apply_walk(s.pos, s.speed, 1.0, 1.0, p); + } + for (state, name) in [ + (&m.anim.states[0], "ATTACK"), + (&m.anim.states[1], "INVULNERABLE"), + (&m.anim.states[2], "DEATH"), + ] { + if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) { + a.apply(ms, 1.0, p); + } + } +} +/// The creaking species exists in the species table. +pub fn is_creaking(m: &Mob) -> bool { + m.species() == Species::Creaking +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 814d6a3f1..b47cc30d6 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -731,6 +731,8 @@ pub struct MeleeAttack { pub until_attack: i32, last_check: i64, raise_arm: i32, + /// Ticks between attacks (20 unless set). + pub interval: i32, } impl MeleeAttack { pub fn new(speed: f64, follow_unseen: bool) -> Self { @@ -743,12 +745,17 @@ impl MeleeAttack { until_attack: 0, last_check: i64::MIN / 2, raise_arm: 0, + interval: 20, } } pub fn zombie(mut self) -> Self { self.zombie = true; self } + pub fn interval(mut self, ticks: i32) -> Self { + self.interval = ticks; + self + } } impl Goal for MeleeAttack { goal_clone!(); @@ -834,7 +841,7 @@ impl Goal for MeleeAttack { } self.until_attack = (self.until_attack - 1).max(0); if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { - self.until_attack = adjusted(true, 20); + self.until_attack = adjusted(true, self.interval); m.swing(); super::ai::do_hurt_target(m, who, cx); } diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 327b0662b..00ebfb71a 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -437,7 +437,12 @@ impl Mob { let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32; self.previous_limb_speed = self.limb_speed; if self.alive() { - let target = (distance * 4.0).min(1.0); + // Creaking.updateWalkAnimation walks the model faster. + let target = if self.species() == super::Species::Creaking { + (distance * 25.0).min(3.0) + } else { + (distance * 4.0).min(1.0) + }; self.limb_speed += (target - self.limb_speed) * 0.4; self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 }; } else { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 13a24e1a9..d640b6973 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -403,6 +403,13 @@ pub fn layers(m: &Mob) -> Vec { ); } } + S::Creaking if super::creaking::eyes_glowing(m) => push( + &mut v, + "creaking#eyes", + "entity/creaking/creaking_eyes", + white, + true, + ), S::Spider | S::CaveSpider => push( &mut v, &m.kind.model_key(), @@ -622,7 +629,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation; - if m.death_time > 0 { + if m.death_time > 0 && !super::creaking::tearing_down(m) { let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) .sqrt() .min(1.0); @@ -740,7 +747,8 @@ pub fn render_with( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let overlay = + u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); let s = anim::state(m, alpha); let (model_key, texture) = body(m); let model = m @@ -793,7 +801,8 @@ pub fn render_single( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let overlay = + u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); let s = anim::state(m, alpha); let model = m.kind.model.clone(); let mut poses = Poses::new(&model); diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 820006f32..1d38d4789 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -83,6 +83,7 @@ pub enum Species { Wither, Camel, Allay, + Creaking, } /// Baby bounding boxes (each class's BABY_DIMENSIONS). #[derive(Clone, Copy, Debug)] @@ -914,6 +915,20 @@ pub const ALL: &[Def] = &[ None, Baby::None ), + def!( + Creaking, + "creaking", + "creaking#main", + "entity/creaking/creaking", + A::Creaking, + [ + "entity.creaking.ambient", + "entity.generic.hurt", + "entity.creaking.death" + ], + Some("entity.creaking.step"), + Baby::None + ), def!( Camel, "camel", diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 8fa53a860..5e075d29e 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -41,6 +41,7 @@ macro_rules! particle_types { particle_types! { Block = "block", BlockCrumble = "block_crumble", + Trail = "trail", DustPillar = "dust_pillar", FallingDust = "falling_dust", Smoke = "smoke", @@ -140,6 +141,8 @@ pub struct ParticleOptions { pub color: [f32; 4], /// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`. pub scale: f32, + /// `TrailParticleOption`: the point it flies to and how many ticks it takes. + pub trail: Option<([f64; 3], i32)>, } impl ParticleOptions { pub fn simple(ty: ParticleType) -> Self { @@ -148,6 +151,20 @@ impl ParticleOptions { block: None, color: [1.0; 4], scale: 1.0, + trail: None, + } + } + /// `TrailParticleOption(target, color, duration)`. + pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self { + Self { + color: [ + ((rgb >> 16) & 255) as f32 / 255.0, + ((rgb >> 8) & 255) as f32 / 255.0, + (rgb & 255) as f32 / 255.0, + 1.0, + ], + trail: Some((target, duration)), + ..Self::simple(ParticleType::Trail) } } pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self { @@ -261,6 +278,10 @@ enum Behaviour { DragonBreath { hit_ground: bool, }, + /// `TrailParticle`: eases towards its target over its lifetime. + Trail { + target: [f64; 3], + }, } #[derive(Clone, Copy, Debug, PartialEq)] enum DripStage { @@ -1662,6 +1683,24 @@ impl ParticleEngine { q.set_power(o.scale); q } + T::Trail => { + let (target, duration) = o.trail?; + let mut q = Particle::at(r, ty, p); + let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25; + let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r)); + q.set_color( + (o.color[0] * jr).min(1.0), + (o.color[1] * jg).min(1.0), + (o.color[2] * jb).min(1.0), + ); + q.size = 0.26; + q.lifetime = duration; + q.has_physics = false; + q.free_move = true; + q.light = Light::FullBright; + q.behaviour = Behaviour::Trail { target }; + q + } }; if particle.set.is_some() { particle.sprite = self.first(ty); @@ -2146,6 +2185,19 @@ impl ParticleEngine { start[2] + p.velocity[2] * f64::from(pos), ]; } + Behaviour::Trail { target } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1)); + for i in 0..3 { + p.position[i] += (target[i] - p.position[i]) * alpha; + } + } Behaviour::HugeExplosion => { p.previous = p.position; let age = p.age; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 83e93e8e1..1b532c59b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -400,6 +400,11 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("Page", Tag::Int(l.page))); } } + BlockEntity::CreakingHeart(h) => { + if let Some((_, uuid)) = h.creaking { + entries.push(("creaking", uuid_tag(uuid))); + } + } } Tag::compound(entries) } @@ -421,6 +426,13 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }), )); } + if id == "minecraft:creaking_heart" { + let heart = crate::containers::CreakingHeart { + creaking: uuid_from_tag(tag.get("creaking")).map(|uuid| (None, uuid)), + ..Default::default() + }; + return Some((pos, BlockEntity::CreakingHeart(Box::new(heart)))); + } if id == "minecraft:lectern" { let lectern = crate::containers::Lectern { book: tag.get("Book").and_then(item_from_nbt), @@ -474,7 +486,10 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), - BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} + BlockEntity::Jukebox(_) + | BlockEntity::Beacon(_) + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_) => {} } Some((pos, entity)) } @@ -2063,6 +2078,37 @@ mod tests { assert_eq!((r[1] >> 12) & 0xF, 4, "version 4"); } #[test] + fn creaking_heart_keeps_its_protector_uuid() { + use crate::containers::{BlockEntity, CreakingHeart}; + let heart = CreakingHeart { + creaking: Some((Some(7), [1, 2, 3, 4])), + ..Default::default() + }; + let tag = encode_block_entity( + (3, 70, -5), + &BlockEntity::CreakingHeart(Box::new(heart)), + "minecraft:creaking_heart", + ); + assert_eq!( + tag.get("creaking"), + Some(&Tag::IntArray(vec![1, 2, 3, 4])), + "vanilla stores the protector's UUID under `creaking`" + ); + let (pos, entity) = decode_block_entity(&tag).expect("heart decodes"); + assert_eq!(pos, (3, 70, -5)); + let BlockEntity::CreakingHeart(h) = entity else { + panic!("a creaking heart"); + }; + // The entity id is resolved again once the creaking is loaded. + assert_eq!(h.creaking, Some((None, [1, 2, 3, 4]))); + let lonely = encode_block_entity( + (0, 0, 0), + &BlockEntity::CreakingHeart(Box::default()), + "minecraft:creaking_heart", + ); + assert!(lonely.get("creaking").is_none()); + } + #[test] fn light_nibbles_use_vanilla_order() { let mut a = Box::new([0u8; 4096]); a[0] = 0xF3; // sky 15, block 3 at x=0 diff --git a/crates/horizon-world/src/level/creaking.rs b/crates/horizon-world/src/level/creaking.rs new file mode 100644 index 000000000..07633c978 --- /dev/null +++ b/crates/horizon-world/src/level/creaking.rs @@ -0,0 +1,83 @@ +//! The creaking heart block (`CreakingHeartBlock`): its state follows the +//! pale oak logs on both ends of its axis and the `creaking_active` +//! environment attribute. The block entity (protector, particles, resin) +//! lives with the entities in the client. +use super::{Behaviours, Dimension, LevelAccess, Sim, Ticks, update::rel}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; + +/// `Direction.Axis.getDirections()`. +fn axis_directions(axis: &str) -> [Direction; 2] { + match axis { + "x" => [Direction::West, Direction::East], + "z" => [Direction::North, Direction::South], + _ => [Direction::Down, Direction::Up], + } +} + +impl Sim<'_, L> { + /// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld day timeline + /// turns it on from 12600 to 23400. + pub(crate) fn creaking_active(&self) -> bool { + self.level.dimension() == Dimension::Overworld + && (12600..23401).contains(&self.level.day_time().rem_euclid(24000)) + } + /// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs along the axis. + pub(crate) fn heart_has_required_logs(&self, state: BlockStateId, pos: BlockPos) -> bool { + let b = self.b; + let axis = b.table.text(state, b.props.axis); + axis_directions(axis).into_iter().all(|d| { + let neighbour = self.state(rel(pos, d)); + b.in_set(neighbour, &b.tags.pale_oak_logs) + && b.table.text(neighbour, b.props.axis) == axis + }) + } + /// `CreakingHeartBlock.updateState`: an uprooted heart with its logs wakes + /// (at night) or goes dormant. + pub(crate) fn heart_update_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + let b = self.b; + let uprooted = b.table.text(state, b.props.creaking_heart_state) == "uprooted"; + if uprooted && self.heart_has_required_logs(state, pos) { + let next = if self.creaking_active() { + "awake" + } else { + "dormant" + }; + b.table.set_text(state, b.props.creaking_heart_state, next) + } else { + state + } + } + /// `CreakingHeartBlock.tick` (scheduled by `updateShape`). + pub(crate) fn heart_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let next = self.heart_update_state(state, pos); + if next != state { + self.set_block_and_update(pos, next); + } + } + /// `CreakingHeartBlock.getStateForPlacement` after the axis is set. + pub(crate) fn heart_placement(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + self.heart_update_state(state, pos) + } +} + +impl Behaviours { + /// `EnvironmentAttributes.CREAKING_ACTIVE` at the level's time. + pub fn creaking_active( + &self, + level: &mut L, + ticks: &mut Ticks, + ) -> bool { + self.sim(level, ticks).creaking_active() + } + /// `CreakingHeartBlock.hasRequiredLogs`. + pub fn creaking_heart_has_logs( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + ) -> bool { + self.sim(level, ticks).heart_has_required_logs(state, pos) + } +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 73efe9158..e66b086e6 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -451,6 +451,7 @@ tags! { enables_bubble_column_push_up = "enables_bubble_column_push_up", enables_bubble_column_drag_down = "enables_bubble_column_drag_down", shulker_boxes = "shulker_boxes", + pale_oak_logs = "pale_oak_logs", convertible_to_mud = "convertible_to_mud", grows_crops = "grows_crops", candles = "candles", @@ -553,6 +554,7 @@ props! { honey_level = "honey_level", bloom = "bloom", natural = "natural", + creaking_heart_state = "creaking_heart_state", cracked = "cracked", has_book = "has_book", signal_fire = "signal_fire", diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a05bbb11..1a0cdaa20 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -102,6 +102,7 @@ pub mod ticks; mod bonemeal; mod buckets; +mod creaking; mod falling; mod feature_world; mod fluids; diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index 01e9527c2..401288c3e 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -786,7 +786,12 @@ impl Sim<'_, L> { ); Some(table.set_text(default, p.orientation, &orientation)) } - Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => { + Class::CreakingHeart => { + let state = + table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face))); + Some(self.heart_placement(state, ctx.pos)) + } + Class::RotatedPillar | Class::InfestedRotatedPillar => { Some(table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face)))) } Class::DecoratedPot => { diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 28c9ac73d..6e53a9fa3 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -43,6 +43,7 @@ pub(crate) struct TestLevel { air: BlockStateId, random: LegacyRandom, pub time: i64, + pub day_time: i64, pub events: Vec, pub block_light: HashMap, } @@ -53,6 +54,7 @@ impl TestLevel { air: b.air(), random: LegacyRandom::new(42), time: 0, + day_time: 0, events: Vec::new(), block_light: HashMap::new(), } @@ -74,6 +76,9 @@ impl LevelAccess for TestLevel { fn game_time(&self) -> i64 { self.time } + fn day_time(&self) -> i64 { + self.day_time + } fn block_light(&self, pos: BlockPos) -> i32 { self.block_light.get(&pos).copied().unwrap_or(0) } @@ -980,3 +985,48 @@ fn dispenser_buckets_pick_up_and_empty() { )); assert_eq!(w.name(at), "powder_snow[]"); } + +#[test] +fn creaking_heart_follows_its_logs_and_the_night() { + let mut w = world!(); + let heart_at = BlockPos::new(0, 10, 0); + let log = |w: &World, axis: &str| w.id("pale_oak_log", &[("axis", axis)]); + let heart = w.id( + "creaking_heart", + &[("axis", "y"), ("creaking_heart_state", "uprooted")], + ); + let (below, above) = (BlockPos::new(0, 9, 0), BlockPos::new(0, 11, 0)); + w.put(heart_at, heart); + w.put(below, log(&w, "y")); + // A log along another axis does not count. + w.put(above, log(&w, "x")); + assert!( + !w.b() + .creaking_heart_has_logs(&mut w.level, &mut w.ticks, heart_at, heart) + ); + // Day: a log update wakes the uprooted heart to dormant. + let up = log(&w, "y"); + w.set(above, up); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "dormant"); + // Night: the same trunk wakes a fresh heart up. + w.level.day_time = 14000; + w.put(heart_at, heart); + w.put(above, w.b().air()); + w.set(above, up); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "awake"); + // Placed without logs it stays uprooted. + w.put(above, w.b().air()); + w.put(heart_at, heart); + let air = w.b().air(); + w.set(above, air); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted"); +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 0723af984..e8eda53cf 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -146,6 +146,7 @@ impl Sim<'_, L> { } Class::Observer => self.observer_tick(pos, state), Class::Eyeblossom => self.eyeblossom_tick(state, pos, false), + Class::CreakingHeart => self.heart_tick(state, pos), Class::DriedGhast => self.dried_ghast_tick(state, pos), Class::RedstoneLamp => self.lamp_tick(pos, state), Class::RedstoneTorch => self.torch_tick(pos, state), From af791c55b777cb838ab4959d46b0fb6396b315e2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:34:06 +0200 Subject: [PATCH 4/7] Add pillager patrols and the ominous banner Every ten minutes or so, in daylight and a fifth of the time, a patrol of pillagers spawns 24 to 48 blocks from a player who is not near a village, once the world is five days old and outside mushroom fields. The leader wears the ominous banner and heads for a distant target in ten block hops with its companions following; patrols hold their ground, shout to nearby raiders and attack together once something comes close. Natural spawns lead a patrol one time in seventeen. A fallen banner always drops, and a captain pillager drops an ominous bottle that gives Bad Omen when drunk. Patrol state, the banner's patterns and the bottle's amplifier are saved as vanilla NBT. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/entity_nbt.rs | 19 +- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/creatures.rs | 40 +- crates/horizon-client/src/game/potions.rs | 9 +- crates/horizon-client/src/game/raids.rs | 205 +++++++++ crates/horizon-client/src/item_data.rs | 71 +++ crates/horizon-client/src/mobs.rs | 16 + crates/horizon-client/src/mobs/ai.rs | 5 + crates/horizon-client/src/mobs/raider.rs | 459 ++++++++++++++++++++ 9 files changed, 823 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-client/src/game/raids.rs create mode 100644 crates/horizon-client/src/mobs/raider.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index bd45054ac..4dcc75671 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -371,6 +371,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } _ => {} } + crate::mobs::raider::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. if !crate::mobs::equine::is_equine(m.species()) { let mut equipment = match map.get(&"equipment".into()) { @@ -391,7 +392,22 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { equipment.get(&slot.into()).and_then(|e| e.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == **id ); - if !keep { + if slot == "head" + && &**id == crate::mobs::raider::BANNER + && crate::mobs::raider::is_raider(m.species()) + { + // The captain's ominous banner keeps its patterns. + let has_patterns = equipment + .get(&slot.into()) + .and_then(|e| e.get("components")) + .is_some(); + if !has_patterns { + equipment.insert( + slot.into(), + crate::save::item_to_nbt(&crate::mobs::raider::ominous_banner()), + ); + } + } else if !keep { equipment.insert( slot.into(), Tag::compound([ @@ -616,6 +632,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.health = health; m.extra.flag2 = flag(tag, "wasOnGround"); } + crate::mobs::raider::read_nbt(&mut m, tag); // A mob saved mid-death finishes dying; one saved dead is dropped. if m.health <= 0.0 && m.death_time == 0 { return None; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6b705f8f1..5865d0adb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -45,6 +45,7 @@ mod perspective; mod piglins; mod postprocess; mod potions; +mod raids; mod remote; mod render_control; mod render_tick; @@ -531,6 +532,7 @@ struct Game<'a> { mobs: Vec, arrows: Vec, creatures: creatures::Creatures, + raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, chest_open: HashMap<(i32, i32, i32), (f32, f32)>, @@ -7617,6 +7619,7 @@ pub fn run() -> Result<()> { mobs: Vec::new(), arrows: Vec::new(), creatures: Default::default(), + raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7f13adffc..b7f6c0699 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -115,6 +115,7 @@ fn seen(m: &Mob) -> Seen { bed: (m.species() == Species::Villager) .then_some(m.extra.bed) .flatten(), + active_raid: horizon_client::mobs::raider::has_active_raid(m), } } impl Game<'_> { @@ -191,6 +192,17 @@ impl Game<'_> { } /// Create a mob of `kind` at a position, finalized like a natural spawn. pub(super) fn spawn_mob(&mut self, kind: &str, at: [f64; 3], persistent: bool) -> Option { + self.spawn_mob_for(kind, at, persistent, false) + } + /// `spawn_mob` for a patrol or raid (`EntitySpawnReason.PATROL` / `EVENT`), + /// which never rolls a patrol leader. + pub(super) fn spawn_mob_for( + &mut self, + kind: &str, + at: [f64; 3], + persistent: bool, + scripted: bool, + ) -> Option { let kind = if kind.contains(':') { kind.to_owned() } else { @@ -208,6 +220,14 @@ impl Game<'_> { ); let difficulty = self.local_difficulty(at); spawning::finalize(&mut mob, &facts, &difficulty); + if !scripted { + let reason = if persistent { + horizon_client::mobs::raider::Reason::Other + } else { + horizon_client::mobs::raider::Reason::Natural + }; + horizon_client::mobs::raider::finalize(&mut mob, reason); + } let id = mob.id; self.mobs.push(mob); Some(id) @@ -265,7 +285,7 @@ impl Game<'_> { serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() }) } /// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES). - fn motion_top(&self, x: i32, z: i32) -> i32 { + pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 { let top = if self.dim == Dim::Nether { 127 } else { 319 }; for y in (horizon_client::chunk::MIN_Y..=top).rev() { let f = self.res.facts.get(self.world.block(x, y, z)); @@ -602,6 +622,7 @@ impl Game<'_> { } self.tick_inhabited(); self.spawn_natural(); + self.tick_patrol_spawner(); let snapshot: Vec = self.mobs.iter().map(seen).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); @@ -688,6 +709,7 @@ impl Game<'_> { for item in gear { self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10); } + self.raider_death_loot(m, pos); let worn = if horizon_client::mobs::equine::is_equine(m.species()) { [None, None, None, None] } else { @@ -703,6 +725,7 @@ impl Game<'_> { // Vexes never drop their sword. if let Some(item) = &item && by_player + && &**item != horizon_client::mobs::raider::BANNER && m.species() != Species::Vex && self.world.random.next_float() < 0.085 { @@ -978,6 +1001,21 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::PatrolTarget { mob, target } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + horizon_client::mobs::raider::set_patrol_target(m, target); + } + } + MobEvent::RaiderTarget { + mob, + target, + aggressive, + } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.ai.target = Some(target); + m.ai.aggressive |= aggressive; + } + } MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 53f9afe02..00ed63cee 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -52,7 +52,7 @@ impl Game<'_> { /// Right-click with a potion, splash/lingering potion or glass bottle. pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result { match &*stack.item { - "minecraft:potion" => { + "minecraft:potion" | "minecraft:ominous_bottle" => { if self.using.is_none() { self.using = Some((self.selected, 0)); } @@ -152,7 +152,8 @@ impl Game<'_> { } /// Drinking a potion while right-click is held; true when handled. pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool { - if &*stack.item != "minecraft:potion" { + let ominous = &*stack.item == "minecraft:ominous_bottle"; + if &*stack.item != "minecraft:potion" && !ominous { return false; } let ticks = ticks + 1; @@ -169,6 +170,10 @@ impl Game<'_> { return true; } self.using = None; + if ominous { + self.drink_ominous_bottle(slot, stack); + return true; + } let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); for e in lasting { self.potions.effects.add(e); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs new file mode 100644 index 000000000..ab3e28827 --- /dev/null +++ b/crates/horizon-client/src/game/raids.rs @@ -0,0 +1,205 @@ +//! Pillager patrols (`PatrolSpawner`) and the village sections they avoid. +use super::{Dim, Game}; +use horizon_client::mobs::{Species, data, raider}; +use horizon_core::random::RandomSource; +use std::collections::HashSet; + +/// Patrol and raid state owned by the game. +#[derive(Default)] +pub(super) struct Raiding { + /// `PatrolSpawner.nextTick`. + patrol_next_tick: i32, +} + +/// `SectionPos` of a block position. +pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) { + (p[0] >> 4, p[1] >> 4, p[2] >> 4) +} +/// `PoiManager.DistanceTracker`: sections from the nearest village centre, +/// 7 when farther than 6. +pub(super) fn sections_to_village(centers: &HashSet<(i32, i32, i32)>, at: (i32, i32, i32)) -> i32 { + centers + .iter() + .map(|c| { + (c.0 - at.0) + .abs() + .max((c.1 - at.1).abs()) + .max((c.2 - at.2).abs()) + }) + .min() + .map_or(7, |d| d.min(7)) +} + +impl Game<'_> { + /// Sections holding a claimed village point of interest (a job site, + /// bed or bell a villager has taken): `PoiManager.isVillageCenter`. + pub(super) fn village_centers(&self) -> HashSet<(i32, i32, i32)> { + let mut out = HashSet::new(); + for m in &self.mobs { + if m.species() != Species::Villager || !m.alive() { + continue; + } + for p in [m.extra.home, m.extra.bed, m.extra.meeting] + .into_iter() + .flatten() + { + out.insert(section(p)); + } + } + out + } + /// `ServerLevel.isCloseToVillage`. + pub(super) fn close_to_village(&self, at: [i32; 3], distance: i32) -> bool { + distance <= 6 && sections_to_village(&self.village_centers(), section(at)) <= distance + } + /// `PatrolSpawner.tick`: every 10 minutes, a fifth of the time in + /// daylight, a patrol of pillagers spawns 24 to 48 blocks from a player + /// who is not near a village. + pub(super) fn tick_patrol_spawner(&mut self) { + if self.dim != Dim::Overworld + || self.world.health_rules.difficulty == horizon_world::food::Difficulty::Peaceful + || !self.ui.rules.bool("spawn_monsters") + || !self.ui.rules.bool("spawn_patrols") + { + return; + } + self.raiding.patrol_next_tick -= 1; + if self.raiding.patrol_next_tick > 0 { + return; + } + let delay = self.world.random.next_int_bound(1200).unwrap_or(0); + self.raiding.patrol_next_tick += 12000 + delay; + let bright = self.sky_darken() < 4; + let r = &mut self.world.random; + if !bright || r.next_int_bound(5).unwrap_or(1) != 0 { + return; + } + // One player: `players.get(random.nextInt(1))`. + let _ = r.next_int_bound(1); + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + if self.spectator() { + return; + } + let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + if self.close_to_village(block, 2) { + return; + } + let r = &mut self.world.random; + let x = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; + let z = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; + let mut at = [block[0] + x, block[1], block[2] + z]; + // hasChunksAt(±10). + for (dx, dz) in [(-10, -10), (10, -10), (-10, 10), (10, 10)] { + if !self + .world + .chunks + .contains_key(&((at[0] + dx) >> 4, (at[2] + dz) >> 4)) + { + return; + } + } + // The `can_pillager_patrol_spawn` attribute: the early game timeline + // (first five days) and the mushroom fields forbid it. + let biome = self.biome_facts(at[0], at[1], at[2]); + if self.world.day_time < 120_000 || biome.mushroom { + return; + } + let f = self.local_difficulty([f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]); + let group = f.effective.ceil() as i32 + 1; + for i in 0..group { + at[1] = self.motion_top(at[0], at[2]); + if !self.spawn_patrol_member(at, i == 0) && i == 0 { + break; + } + let r = &mut self.world.random; + at[0] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); + at[2] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); + } + } + /// A raider's ominous banner (drop chance 2.0: always dropped) and a + /// patrol captain's ominous bottle (`entities/pillager`). + pub(super) fn raider_death_loot(&mut self, m: &horizon_client::mobs::Mob, pos: [f64; 3]) { + if !raider::is_raider(m.species()) { + return; + } + if m.extra.head.as_deref() == Some(raider::BANNER) { + self.spawn_item(raider::ominous_banner(), pos, [0.0, 0.2, 0.0], 10); + } + if m.species() == Species::Pillager && raider::is_captain(m) { + let amplifier = self.world.random.next_int_bound(5).unwrap_or(0) as u8; + let amplifier = (amplifier > 0).then_some(amplifier); + let mut bottle = horizon_client::items::ItemStack::new("minecraft:ominous_bottle", 1); + bottle.data_mut().ominous_amplifier = amplifier; + self.spawn_item(bottle, pos, [0.0, 0.2, 0.0], 10); + } + } + /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the + /// bottle's amplifier, then the dispose sound; the bottle is used up. + pub(super) fn drink_ominous_bottle( + &mut self, + slot: usize, + stack: &horizon_client::items::ItemStack, + ) { + let amplifier = stack.data().and_then(|d| d.ominous_amplifier).unwrap_or(0); + let mut effect = + horizon_client::effects::EffectInstance::new("bad_omen", 120_000, i32::from(amplifier)); + effect.visible = false; + self.potions.effects.add(effect); + let eye = self.eye_position().unwrap_or_default(); + self.audio + .play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0); + if !self.creative + && let Some(s) = self.inventory[slot].as_mut() + { + s.count -= 1; + if s.count == 0 { + self.inventory[slot] = None; + } + } + } + /// `PatrolSpawner.spawnPatrolMember`: a pillager on a valid empty block + /// that may spawn there; the leader picks a target and wears the banner. + fn spawn_patrol_member(&mut self, at: [i32; 3], leader: bool) -> bool { + let state = self.world.block(at[0], at[1], at[2]); + let below = self.world.block(at[0], at[1] - 1, at[2]); + let empty = self.res.mob_data.state(state).flags & data::VALID_EMPTY_SPAWN != 0; + let valid = self.res.mob_data.state(below).flags & data::VALID_SPAWN != 0; + // PatrollingMonster.checkPatrollingMonsterSpawnRules. + if !empty || !valid || self.world.light(at[0], at[1], at[2]) & 15 > 8 { + return false; + } + let pos = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]; + let Some(id) = self.spawn_mob_for("minecraft:pillager", pos, false, true) else { + return false; + }; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { + return false; + }; + if leader { + raider::set_patrol_leader(m, true); + // findPatrolTarget runs before the mob is placed, so the target + // is around the world origin. + raider::find_patrol_target_from(m, [0, 0, 0]); + } + raider::finalize(m, raider::Reason::Patrol); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sections_to_village_is_a_chebyshev_distance_capped_at_seven() { + let mut centers = HashSet::new(); + assert_eq!(sections_to_village(¢ers, (0, 0, 0)), 7); + centers.insert(section([40, 64, 40])); + assert_eq!(sections_to_village(¢ers, (2, 4, 2)), 0); + assert_eq!(sections_to_village(¢ers, (4, 4, 2)), 2); + assert_eq!(sections_to_village(¢ers, (-10, 4, 2)), 7); + assert_eq!(section([-1, -17, 15]), (-1, -2, 0)); + } +} diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d7643d3dd..feb98fa38 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -35,7 +35,23 @@ pub struct StackData { pub writable_pages: Vec, /// `minecraft:written_book_content`. pub written: Option, + /// The raid captain's banner: `minecraft:banner_patterns` with the + /// ominous layers, its item name, rarity and hidden tooltip. + pub ominous_banner: bool, + /// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0). + pub ominous_amplifier: Option, } +/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers. +pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ + ("rhombus", "cyan"), + ("stripe_bottom", "light_gray"), + ("stripe_center", "gray"), + ("border", "light_gray"), + ("stripe_middle", "black"), + ("half_horizontal", "light_gray"), + ("circle", "light_gray"), + ("border", "black"), +]; /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] pub struct WrittenBook { @@ -330,6 +346,39 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()), )); } + if d.ominous_banner { + let layer = |pattern: &str, color: &str| { + Tag::compound([ + ( + "pattern", + Tag::String(format!("minecraft:{pattern}").as_str().into()), + ), + ("color", Tag::String(color.into())), + ]) + }; + entries.push(( + "minecraft:banner_patterns", + Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()), + )); + entries.push(( + "minecraft:tooltip_display", + Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), + )]), + )); + entries.push(( + "minecraft:item_name", + Tag::compound([( + "translate", + Tag::String("block.minecraft.ominous_banner".into()), + )]), + )); + entries.push(("minecraft:rarity", Tag::String("uncommon".into()))); + } + if let Some(a) = d.ominous_amplifier { + entries.push(("minecraft:ominous_bottle_amplifier", Tag::Int(i32::from(a)))); + } if !d.container.is_empty() { let slots = d .container @@ -435,6 +484,15 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, + ominous_banner: matches!( + c.get("minecraft:banner_patterns"), + Some(Tag::List(layers)) if layers.first().is_some_and(|l| + l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus")) + ), + ominous_amplifier: c + .get("minecraft:ominous_bottle_amplifier") + .and_then(int) + .map(|v| v.clamp(0, 4) as u8), trim: c.get("minecraft:trim").and_then(|t| { Some(( Arc::from(t.get("material").and_then(string)?.as_str()), @@ -499,6 +557,19 @@ mod tests { assert_eq!(back.custom_name(), Some("Blade")); } + #[test] + fn ominous_items_round_trip() { + let mut banner = ItemStack::new("minecraft:white_banner", 1); + banner.data_mut().ominous_banner = true; + let tag = encode_components(&banner).unwrap(); + assert!(tag.get("minecraft:banner_patterns").is_some()); + let (_, back) = decode_components(Some(&tag)); + assert!(back.unwrap().ominous_banner); + let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1); + bottle.data_mut().ominous_amplifier = Some(3); + let (_, back) = decode_components(encode_components(&bottle).as_ref()); + assert_eq!(back.unwrap().ominous_amplifier, Some(3)); + } #[test] fn plain_stacks_have_no_components() { let stack = ItemStack::new("minecraft:stone", 64); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f53eb3901..d90acb0b1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -29,6 +29,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod raider; pub mod ravager; pub mod render; pub mod shulker; @@ -476,6 +477,8 @@ pub struct Extra { pub meeting: Option<[i32; 3]>, /// Villager and wandering trader offers and experience. pub trade: Option>, + /// A raider's patrol and raid state. + pub raider: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -660,6 +663,17 @@ pub enum MobEvent { kind: DamageKind, amount: f32, }, + /// A patrol leader hands its patrol target to a companion. + PatrolTarget { + mob: u32, + target: [i32; 3], + }, + /// A raider is told to attack (`HoldGroundAttackGoal` shouting). + RaiderTarget { + mob: u32, + target: Who, + aggressive: bool, + }, /// Drop the loot of a gift table (chicken eggs, armadillo scutes). GiftLoot { table: &'static str, @@ -715,6 +729,8 @@ pub struct Seen { /// A villager's claimed job site and bed. pub job: Option<[i32; 3]>, pub bed: Option<[i32; 3]>, + /// A raider in an active raid. + pub active_raid: bool, } /// The player as mobs see it. #[derive(Clone, Debug)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0ae29a97..45957180f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -173,6 +173,7 @@ pub fn register(m: &mut Mob) { Family::Villager => super::villager::register(m), Family::Creaking => super::creaking::register(m), } + super::raider::register(m); } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). fn pre_tick(m: &mut Mob, events: &mut Vec) { @@ -603,6 +604,10 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { } let Some(p) = &w.player else { return true }; let d = m.distance_sqr(p.position); + // Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`). + if super::raider::keeps_alive(m, d) { + return true; + } let despawn = if m.kind.category == "water_ambient" { 64.0 } else { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs new file mode 100644 index 000000000..95a8f9dea --- /dev/null +++ b/crates/horizon-client/src/mobs/raider.rs @@ -0,0 +1,459 @@ +//! Raiders (`PatrollingMonster` and `Raider`): the patrol state every +//! pillager, vindicator, evoker, witch and ravager carries, the long +//! distance patrol and hold-ground goals, the ominous banner a patrol leader +//! wears, and the saved fields. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::{Cx, Goal, LOOK, MOVE, goal_clone}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::nbt::Tag; + +/// The ominous banner is a white banner with the raid patterns; raiders wear +/// it as their head item. +pub const BANNER: &str = "minecraft:white_banner"; + +/// `PatrollingMonster` and `Raider` state (saved as `patrol_target`, +/// `PatrolLeader`, `Patrolling`, `Wave`, `CanJoinRaid`, `RaidId`). +#[derive(Clone, Debug, Default)] +pub struct State { + pub patrol_leader: bool, + pub patrolling: bool, + pub patrol_target: Option<[i32; 3]>, + /// Goal cooldown after a failed long distance path (game time). + pub patrol_cooldown_until: i64, + pub wave: i32, + pub can_join_raid: bool, + /// The raid this raider belongs to. + pub raid_id: Option, + pub ticks_outside_raid: i32, + pub celebrating: bool, + /// The raid is active (`hasActiveRaid`); set by the game every tick. + pub active_raid: bool, +} + +/// The raider species (`EntityTypeTags.RAIDERS`). +pub fn is_raider(s: Species) -> bool { + matches!( + s, + Species::Pillager + | Species::Vindicator + | Species::Evoker + | Species::Witch + | Species::Ravager + ) +} +/// `canBeLeader`: witches and ravagers never lead. +pub fn can_be_leader(s: Species) -> bool { + is_raider(s) && !matches!(s, Species::Witch | Species::Ravager) +} +pub fn state(m: &Mob) -> Option<&State> { + m.extra.raider.as_deref() +} +pub fn state_mut(m: &mut Mob) -> &mut State { + m.extra.raider.get_or_insert_with(Box::default) +} +pub fn has_active_raid(m: &Mob) -> bool { + state(m).is_some_and(|s| s.active_raid) +} +/// `Raider.isCaptain`: the banner on the head of a patrol leader. +pub fn is_captain(m: &Mob) -> bool { + m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader) +} + +pub fn register(m: &mut Mob) { + if !is_raider(m.species()) { + return; + } + m.extra.raider = Some(Box::default()); + let species = m.species(); + m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); + // The illagers hold their ground in a patrol (Witch and Ravager do not). + if matches!(species, Species::Pillager | Species::Vindicator) { + m.ai.goals.add( + if species == Species::Pillager { 2 } else { 4 }, + HoldGroundAttack::new(10.0), + ); + } +} + +/// `Raid.getOminousBannerInstance`. +pub fn ominous_banner() -> crate::items::ItemStack { + let mut stack = crate::items::ItemStack::new(BANNER, 1); + stack.data_mut().ominous_banner = true; + stack +} + +/// `PatrollingMonster.setPatrolLeader`. +pub fn set_patrol_leader(m: &mut Mob, leader: bool) { + let s = state_mut(m); + s.patrol_leader = leader; + s.patrolling = true; +} +/// `PatrollingMonster.setPatrolTarget`. +pub fn set_patrol_target(m: &mut Mob, target: [i32; 3]) { + let s = state_mut(m); + s.patrol_target = Some(target); + s.patrolling = true; +} +/// `PatrollingMonster.findPatrolTarget`: somewhere within 500 blocks. +pub fn find_patrol_target(m: &mut Mob) { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + find_patrol_target_from(m, at); +} +/// `findPatrolTarget` from a given block position. +pub fn find_patrol_target_from(m: &mut Mob, [x, y, z]: [i32; 3]) { + let dx = -500 + m.random.next_int_bound(1000).unwrap_or(0); + let dz = -500 + m.random.next_int_bound(1000).unwrap_or(0); + let s = state_mut(m); + s.patrol_target = Some([x + dx, y, z + dz]); + s.patrolling = true; +} +/// The leader's ominous banner and its drop chance of 2.0 (always dropped). +pub fn wear_banner(m: &mut Mob) { + m.extra.head = Some(BANNER.into()); +} +/// Why a mob was spawned (`EntitySpawnReason`), as far as raiders care. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + /// Natural spawning: one leader in 17, and witches stay out of raids. + Natural, + /// Commands, eggs and other spawns: one leader in 17. + Other, + Patrol, + Event, +} +/// `PatrollingMonster.finalizeSpawn` and `Raider.finalizeSpawn`: a spawn +/// other than a patrol, raid or structure leads one time in 17, a patrol +/// leader wears the ominous banner, and every raider but a naturally spawned +/// witch can join a raid. +pub fn finalize(m: &mut Mob, reason: Reason) { + if !is_raider(m.species()) { + return; + } + let roll = matches!(reason, Reason::Natural | Reason::Other); + if roll && m.random.next_float() < 0.06 && can_be_leader(m.species()) { + state_mut(m).patrol_leader = true; + } + if state_mut(m).patrol_leader { + wear_banner(m); + } + let witch = m.species() == Species::Witch; + let s = state_mut(m); + if reason == Reason::Patrol { + s.patrolling = true; + } + s.can_join_raid = !witch || reason != Reason::Natural; +} + +/// `PatrollingMonster.removeWhenFarAway`: patrollers and raiders in a raid +/// are only despawned beyond 128 blocks (never inside a raid). +pub fn keeps_alive(m: &Mob, distance_squared: f64) -> bool { + match state(m) { + Some(s) => s.raid_id.is_some() || s.patrolling && distance_squared <= 16384.0, + None => false, + } +} + +/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` position above (x, z). +pub fn heightmap_pos(w: &MobWorld, x: i32, z: i32) -> [i32; 3] { + let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; + let y = (crate::chunk::MIN_Y..top) + .rev() + .find(|&y| { + let f = w.facts.get(w.world.block(x, y, z)); + (f.full_collision || f.fluid != crate::blocks::Fluid::None) + && !f.name.ends_with("leaves") + }) + .map_or(crate::chunk::MIN_Y, |y| y + 1); + [x, y, z] +} + +/// `Vec3.yRot` (the angle is in radians, and the patrol goal passes 90). +fn y_rot(v: Vec3, angle: f32) -> Vec3 { + let (cos, sin) = (f64::from(angle.cos()), f64::from(angle.sin())); + Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin) +} + +/// `PatrollingMonster.LongDistancePatrolGoal`: walk toward the patrol target +/// in 10 block hops (curving around it), the leader dragging its companions. +#[derive(Clone, Debug)] +pub struct LongDistancePatrol { + speed: f64, + leader_speed: f64, +} +impl LongDistancePatrol { + pub fn new(speed: f64, leader_speed: f64) -> Self { + Self { + speed, + leader_speed, + } + } +} +/// Patrol companions within 16 blocks that are not in a raid. +fn companions(m: &Mob, w: &MobWorld) -> Vec { + w.others + .iter() + .filter(|s| { + s.id != m.id + && s.alive + && is_raider(s.species) + && !s.active_raid + && (s.position.x - m.position.x).abs() <= 16.0 + f64::from(m.width()) + && (s.position.y - m.position.y).abs() <= 16.0 + f64::from(m.height()) + && (s.position.z - m.position.z).abs() <= 16.0 + f64::from(m.width()) + }) + .map(|s| s.id) + .collect() +} +impl Goal for LongDistancePatrol { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(s) = state(m) else { return false }; + cx.w.game_time >= s.patrol_cooldown_until + && s.patrolling + && m.ai.target.is_none() + && s.patrol_target.is_some() + && !s.has_rider() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !m.ai.nav.is_done() { + return; + } + let leader = state(m).is_some_and(|s| s.patrol_leader); + let friends = companions(m, cx.w); + let Some(target) = state(m).and_then(|s| s.patrol_target) else { + return; + }; + if state(m).is_some_and(|s| s.patrolling) && friends.is_empty() { + state_mut(m).patrolling = false; + } else if leader && close_to_center(target, m.position, 10.0) { + find_patrol_target(m); + } else { + let to = Vec3::new( + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ); + let own = m.position; + let distance = own.subtract(to); + let to = y_rot(distance, 90.0).scale(0.4).add_vector(to); + let hop = to.subtract(own).normalize().scale(10.0).add_vector(own); + let at = heightmap_pos(cx.w, hop.x.floor() as i32, hop.z.floor() as i32); + let speed = if leader { + self.leader_speed + } else { + self.speed + }; + let to = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]; + if !m.nav_move_to(cx.w, to, speed) { + self.move_randomly(m, cx); + state_mut(m).patrol_cooldown_until = cx.w.game_time + 200; + } else if leader { + for id in friends { + cx.events.push(MobEvent::PatrolTarget { + mob: id, + target: at, + }); + } + } + } + } +} +impl LongDistancePatrol { + fn move_randomly(&self, m: &mut Mob, cx: &mut Cx) -> bool { + let (x, z) = ( + m.position.x.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0), + m.position.z.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0), + ); + let at = heightmap_pos(cx.w, x, z); + m.nav_move_to( + cx.w, + [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])], + self.speed, + ) + } +} +/// `Vec3i.closerToCenterThan`. +fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ) + .distance_squared(at) + < distance * distance +} + +impl State { + /// A ravager carrying a raider (`hasControllingPassenger`). + pub fn has_rider(&self) -> bool { + false + } +} + +/// `Raider.HoldGroundAttackGoal`: while patrolling, stand still and let the +/// patrol shout when something shows up; attack once it comes close. +#[derive(Clone, Debug)] +pub struct HoldGroundAttack { + hostile_radius_sqr: f64, +} +impl HoldGroundAttack { + pub fn new(radius: f64) -> Self { + Self { + hostile_radius_sqr: radius * radius, + } + } +} +/// Raiders within 8 blocks, nearest first (`shoutTargeting`). +fn shout_range(m: &Mob, w: &MobWorld) -> Vec { + w.others + .iter() + .filter(|s| { + s.id != m.id + && s.alive + && is_raider(s.species) + && (s.position.x - m.position.x).abs() <= 8.0 + f64::from(m.width()) + && (s.position.y - m.position.y).abs() <= 8.0 + f64::from(m.height()) + && (s.position.z - m.position.z).abs() <= 8.0 + f64::from(m.width()) + && s.position.distance_squared(m.position) <= 64.0 + }) + .map(|s| s.id) + .collect() +} +impl Goal for HoldGroundAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + let Some(s) = state(m) else { return false }; + s.raid_id.is_none() + && s.patrolling + && m.ai.target.is_some() + && !m.ai.aggressive + && m.ai.last_hurt_by != Some(Who::Player) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.nav.stop(); + if let Some(target) = m.ai.target { + for id in shout_range(m, cx.w) { + cx.events.push(MobEvent::RaiderTarget { + mob: id, + target, + aggressive: false, + }); + } + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(target) = m.ai.target { + for id in shout_range(m, cx.w) { + cx.events.push(MobEvent::RaiderTarget { + mob: id, + target, + aggressive: true, + }); + } + m.ai.aggressive = true; + } + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.target_info(cx.w) else { return }; + if m.distance_sqr(t.position) > self.hostile_radius_sqr { + m.look_at([t.position.x, t.eye_y, t.position.z]); + if m.random.next_int_bound(50).unwrap_or(1) == 0 { + let sound = m.kind.sounds[0]; + if !sound.is_empty() { + m.voice(sound, cx.events); + } + } + } else { + m.ai.aggressive = true; + } + } +} + +/// The saved fields (`PatrollingMonster` and `Raider.addAdditionalSaveData`). +pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { + let Some(s) = state(m) else { return }; + match s.patrol_target { + Some(p) => { + map.insert("patrol_target".into(), Tag::IntArray(p.to_vec())); + } + None => { + map.remove(&"patrol_target".into()); + } + } + map.insert("PatrolLeader".into(), Tag::Byte(i8::from(s.patrol_leader))); + map.insert("Patrolling".into(), Tag::Byte(i8::from(s.patrolling))); + map.insert("Wave".into(), Tag::Int(s.wave)); + map.insert("CanJoinRaid".into(), Tag::Byte(i8::from(s.can_join_raid))); + match s.raid_id { + Some(id) => { + map.insert("RaidId".into(), Tag::Int(id)); + } + None => { + map.remove(&"RaidId".into()); + } + } +} +pub fn read_nbt(m: &mut Mob, tag: &Tag) { + if !is_raider(m.species()) { + return; + } + let int = |t: Option<&Tag>| match t { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + Some(Tag::Short(v)) => Some(i32::from(*v)), + _ => None, + }; + let flag = |t: Option<&Tag>| int(t).unwrap_or(0) != 0; + let s = state_mut(m); + s.patrol_target = match tag.get("patrol_target") { + Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), + _ => None, + }; + s.patrol_leader = flag(tag.get("PatrolLeader")); + s.patrolling = flag(tag.get("Patrolling")); + s.wave = int(tag.get("Wave")).unwrap_or(0); + s.can_join_raid = flag(tag.get("CanJoinRaid")); + s.raid_id = int(tag.get("RaidId")); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raiders_and_leaders() { + assert!(is_raider(Species::Ravager) && is_raider(Species::Witch)); + assert!(!is_raider(Species::Zombie)); + assert!(can_be_leader(Species::Pillager) && can_be_leader(Species::Evoker)); + assert!(!can_be_leader(Species::Witch) && !can_be_leader(Species::Ravager)); + } + #[test] + fn long_distance_patrol_turns_by_ninety_radians() { + // PatrollingMonster passes 90.0F to Vec3.yRot (radians). + let v = y_rot(Vec3::new(10.0, 3.0, 0.0), 90.0); + let (c, s) = (90f64.cos(), 90f64.sin()); + assert!((v.x - 10.0 * c).abs() < 1e-4 && (v.z + 10.0 * s).abs() < 1e-4); + assert_eq!(v.y, 3.0); + } + #[test] + fn closer_to_center_uses_block_centres() { + let at = Vec3::new(10.5, 64.5, 10.5); + assert!(close_to_center([10, 64, 10], at, 1.0)); + assert!(!close_to_center([30, 64, 10], at, 10.0)); + } +} From 44adeb0d3cf64879e8f300d40a20e90c53d39cef Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:58:26 +0200 Subject: [PATCH 5/7] Add bad omen, raid omen and raids Drinking an ominous bottle gives Bad Omen; inside a village it turns into Raid Omen, and when that runs out a raid starts, or grows, around the village points villagers have claimed (the raid_trigger statistic and the voluntary exile trigger fire on the first omen). Raids are saved in data/minecraft/raids.dat and send waves of pillagers, vindicators, evokers, witches and ravagers (ravagers carrying pillagers, evokers or vindicators) by difficulty and omen level, from a ring that closes in as the countdown runs down, with the raid horn and a red notched boss bar that shows the raiders left, Victory or Defeat. Raiders walk to the village, move between beds, take back a dropped captain banner, celebrate a lost village, are enchanted with Quick Charge or Sharpness at high omen levels and are dropped from the raid when idle or far away. Killing one makes the player a hero; a won raid grants Hero of the Village and the hero_of_the_village trigger. Villagers hide in their beds during a wave, ring the bell before one, celebrate a victory with fireworks, and toss gifts to a hero. /raid start, stop, check, spawnleader, setomen, glow and sound are available. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/command/vanilla.rs | 22 + crates/horizon-client/src/game.rs | 2 + .../horizon-client/src/game/advancements.rs | 14 + crates/horizon-client/src/game/commands.rs | 2 + .../horizon-client/src/game/commands/raid.rs | 108 ++ crates/horizon-client/src/game/creatures.rs | 8 + crates/horizon-client/src/game/dragon.rs | 3 +- crates/horizon-client/src/game/fireworks.rs | 2 +- crates/horizon-client/src/game/raids.rs | 894 +++++++++++++- crates/horizon-client/src/game/wither.rs | 5 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 16 + crates/horizon-client/src/mobs/illager.rs | 32 +- crates/horizon-client/src/mobs/raider.rs | 227 +++- crates/horizon-client/src/mobs/villager.rs | 221 +++- crates/horizon-client/src/raid.rs | 1069 +++++++++++++++++ 16 files changed, 2606 insertions(+), 20 deletions(-) create mode 100644 crates/horizon-client/src/game/commands/raid.rs create mode 100644 crates/horizon-client/src/raid.rs diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index 28d29d7ab..0c9f74161 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -111,6 +111,28 @@ pub fn build() -> Dispatcher { d.executes(dur, "weather"); } + // raid start | stop | check | sound | spawnleader | setomen | glow + let raid = d.literal(root, "raid"); + d.requires(raid, 3); + let start = d.literal(raid, "start"); + let level = d.argument(start, "omenlvl", integer(0)); + d.executes(level, "raid.start"); + for (name, id) in [ + ("stop", "raid.stop"), + ("check", "raid.check"), + ("spawnleader", "raid.spawnleader"), + ("glow", "raid.glow"), + ] { + let n = d.literal(raid, name); + d.executes(n, id); + } + let sound = d.literal(raid, "sound"); + let kind = d.argument(sound, "type", ArgType::Greedy); + d.executes(kind, "raid.sound"); + let setomen = d.literal(raid, "setomen"); + let level = d.argument(setomen, "level", integer(0)); + d.executes(level, "raid.setomen"); + // kill [] let kill = d.literal(root, "kill"); d.requires(kill, GAMEMASTERS); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5865d0adb..96c01535d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2442,6 +2442,7 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } + self.tick_omens(); self.tick_effects(); self.tick_burning(); self.tick_using(); @@ -6519,6 +6520,7 @@ impl Game<'_> { .save(&chunks, self.res.assets.registry, &self.res.biomes)?; self.save_entities()?; self.save_maps(); + self.save_raids(); self.save_fight(); self.save_stats(); self.save_advancements(); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 50382bb9d..d0392b35b 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -261,12 +261,26 @@ impl Game<'_> { } } pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView { + // mainhand, offhand, head, chest, legs, feet. + let slot = |i: &Option>| { + i.as_ref().map(|id| item_view(&ItemStack::new(id, 1))) + }; + let mut equipment: [Option; 7] = Default::default(); + if !horizon_client::mobs::equine::is_equine(m.species()) { + equipment[0] = slot(&m.extra.main_hand); + equipment[1] = slot(&m.extra.off_hand); + equipment[2] = slot(&m.extra.head); + equipment[3] = slot(&m.extra.chest); + equipment[4] = slot(&m.extra.legs); + equipment[5] = slot(&m.extra.feet); + } EntityView { kind: m.kind.id.clone(), position: [m.position.x, m.position.y, m.position.z], on_fire: m.fire_ticks > 0, baby: m.is_baby(), on_ground: m.on_ground, + equipment, ..Default::default() } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 5dfff0315..31d900003 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2,6 +2,7 @@ //! entity selectors resolved against the game, vanilla feedback and errors. mod effects; pub(super) mod execute; +mod raid; mod text_commands; use super::{Dim, Game, Screen, chat::PLAYER_NAME}; @@ -418,6 +419,7 @@ impl Game<'_> { | "teleport.targets.location" | "teleport.targets.destination" => self.cmd_teleport(id, ctx), id if id.starts_with("time.") => self.cmd_time(id, ctx), + id if id.starts_with("raid.") => self.cmd_raid(id, ctx), "weather" => self.cmd_weather(ctx), "kill" => self.cmd_kill(ctx), "summon" => self.cmd_summon(ctx), diff --git a/crates/horizon-client/src/game/commands/raid.rs b/crates/horizon-client/src/game/commands/raid.rs new file mode 100644 index 000000000..762ae7e90 --- /dev/null +++ b/crates/horizon-client/src/game/commands/raid.rs @@ -0,0 +1,108 @@ +//! `RaidCommand`: `/raid start|stop|check|spawnleader|setomen|glow|sound`. +use super::{Game, R, Text, err}; +use horizon_client::{command::Context, mobs::raider}; + +impl Game<'_> { + pub(in crate::game) fn cmd_raid(&mut self, id: &str, ctx: &Context) -> R { + let Some(player) = self.player.as_ref().map(|p| p.position) else { + return Ok(0); + }; + let at = [ + player.x.floor() as i32, + player.y.floor() as i32, + player.z.floor() as i32, + ]; + let fail = |game: &mut Self, message: &str| { + game.command_failure(Text::literal(message)); + }; + match id { + "raid.start" => { + if self.raiding_nearby(at).is_some() { + fail(self, "Raid already started close by"); + return Ok(-1); + } + let level = Self::int(ctx, "omenlvl").unwrap_or(0); + match self.raid_command_create(at, level) { + true => self.feedback(Text::literal("Created a raid in your local village")), + false => fail(self, "Failed to create a raid in your local village"), + } + Ok(1) + } + "raid.stop" => match self.raiding_nearby(at) { + Some(raid) => { + self.raid_command_stop(raid); + self.feedback(Text::literal("Stopped raid")); + Ok(1) + } + None => { + fail(self, "No raid here"); + Ok(-1) + } + }, + "raid.check" => match self.raiding_nearby(at).filter(|id| self.raid_started(*id)) { + Some(raid) => { + self.feedback(Text::literal("Found a started raid!")); + let status = self.raid_status_text(raid); + self.feedback(Text::literal(&status)); + Ok(1) + } + None => { + fail(self, "Found no started raids"); + Ok(0) + } + }, + "raid.spawnleader" => { + let kind = "minecraft:pillager"; + match self.spawn_mob_for(kind, [player.x, player.y, player.z], true, true) { + Some(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + raider::set_patrol_leader(m, true); + raider::finalize(m, raider::Reason::Other); + } + self.feedback(Text::literal("Spawned a raid captain")); + Ok(1) + } + None => { + fail(self, "Pillager failed to spawn"); + Ok(0) + } + } + } + "raid.setomen" => { + let level = Self::int(ctx, "level").unwrap_or(0); + let Some(raid) = self.raiding_nearby(at) else { + fail(self, "No raid found here"); + return Ok(1); + }; + if level > horizon_client::raid::MAX_OMEN_LEVEL { + fail( + self, + &format!( + "Sorry, the max raid omen level you can set is {}", + horizon_client::raid::MAX_OMEN_LEVEL + ), + ); + } else { + let before = self.raid_set_omen(raid, level); + self.feedback(Text::literal(format!( + "Changed village's raid omen level from {before} to {level}" + ))); + } + Ok(1) + } + "raid.glow" => { + if let Some(raid) = self.raiding_nearby(at) { + self.raid_glow(raid); + } + Ok(1) + } + "raid.sound" => { + let at = [player.x + 5.0, player.y, player.z]; + self.audio + .play("minecraft:event.raid.horn", Some(at), 1.0, 1.0); + Ok(1) + } + _ => Err(err("commands.help.failed", &[])), + } + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index b7f6c0699..1198680e5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -151,6 +151,7 @@ impl Game<'_> { gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), + hero: self.potions.effects.get("hero_of_the_village").is_some(), }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -623,6 +624,7 @@ impl Game<'_> { self.tick_inhabited(); self.spawn_natural(); self.tick_patrol_spawner(); + self.tick_raids(); let snapshot: Vec = self.mobs.iter().map(seen).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); @@ -646,6 +648,7 @@ impl Game<'_> { push_apart(&mut mobs); } self.mobs.append(&mut mobs); + self.sync_riders(); for m in dead { self.mob_died(&m); } @@ -666,6 +669,7 @@ impl Game<'_> { let view = self.mob_entity(m); self.trigger_entity("minecraft:player_killed_entity", "entity", &view); } + self.raider_died(m, by_player); let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; if !m.is_baby() { @@ -1001,6 +1005,10 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::Firework { at, color, flight } => { + self.villager_firework(at, color, flight) + } + MobEvent::ThrowGift { table, from, to } => self.throw_gift(&table, from, to), MobEvent::PatrolTarget { mob, target } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { horizon_client::mobs::raider::set_patrol_target(m, target); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 398b9a208..be4b4ec1f 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1842,7 +1842,8 @@ impl Game<'_> { /// The boss bar (`BossHealthOverlay`): name and the pink progress bar. pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) { let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End); - self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 }); + let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 }); + self.draw_raid_bar(batch, y); let Some(d) = dragon else { return; }; diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 2bd400d96..4f0c3fa9c 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -37,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec) { .unwrap_or((1, Vec::new())) } impl Game<'_> { - fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket { + pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket { let (flight, explosions) = fireworks_of(stack); let r = &mut self.world.random; let tri = |r: &mut horizon_core::random::LegacyRandom| { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index ab3e28827..ba5d1bc87 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1,14 +1,28 @@ -//! Pillager patrols (`PatrolSpawner`) and the village sections they avoid. +//! Pillager patrols (`PatrolSpawner`), the raid omen, and raids (`Raids`): +//! their waves, boss bar, victory and the raiders' bookkeeping. use super::{Dim, Game}; -use horizon_client::mobs::{Species, data, raider}; -use horizon_core::random::RandomSource; -use std::collections::HashSet; +use horizon_client::mobs::villager as mobs_villager; +use horizon_client::{ + effects::EffectInstance, + hud::{HudBatch, rgba}, + mobs::{Mob, Species, data, raider}, + raid::{self, Action, BarName, RaidLevel, RaiderInfo, RaiderType, Raids, Spawn}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::{HashMap, HashSet}; /// Patrol and raid state owned by the game. #[derive(Default)] pub(super) struct Raiding { /// `PatrolSpawner.nextTick`. patrol_next_tick: i32, + raids: Raids, + loaded: bool, + /// `ServerPlayer.raidOmenPosition`. + omen_position: Option<[i32; 3]>, + /// Beds near each raid's centre, rescanned now and then (`HOME` points + /// of interest for `RaiderMoveThroughVillageGoal`). + homes: HashMap>)>, } /// `SectionPos` of a block position. @@ -30,6 +44,878 @@ pub(super) fn sections_to_village(centers: &HashSet<(i32, i32, i32)>, at: (i32, .map_or(7, |d| d.min(7)) } +/// The level as a raid sees it, with this tick's village and raider data. +struct Lvl<'a, 'g> { + game: &'a Game<'g>, + difficulty: i32, + centers: &'a HashSet<(i32, i32, i32)>, + raiders: &'a HashMap>, +} +impl RaidLevel for Lvl<'_, '_> { + fn difficulty(&self) -> i32 { + self.difficulty + } + fn has_chunk_at(&self, p: [i32; 3]) -> bool { + self.game.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) + } + fn is_village(&self, p: [i32; 3]) -> bool { + sections_to_village(self.centers, section(p)) <= 1 + } + fn village_sections_near(&self, p: [i32; 3]) -> Vec<[i32; 3]> { + let (sx, sy, sz) = section(p); + let mut out = Vec::new(); + for dx in -2..=2 { + for dy in -2..=2 { + for dz in -2..=2 { + let s = (sx + dx, sy + dy, sz + dz); + let center = [s.0 * 16 + 8, s.1 * 16 + 8, s.2 * 16 + 8]; + if self.is_village(center) { + out.push(center); + } + } + } + } + out + } + fn raiders(&self, raid: i32) -> Vec { + self.raiders.get(&raid).cloned().unwrap_or_default() + } + fn surface_height(&self, x: i32, z: i32) -> i32 { + self.game.surface_height(x, z) + } + fn is_ticking(&self, p: [i32; 3]) -> bool { + [(-10, -10), (10, -10), (-10, 10), (10, 10)] + .iter() + .all(|(dx, dz)| self.has_chunk_at([p[0] + dx, p[1], p[2] + dz])) + } + fn can_spawn_at(&self, p: [i32; 3]) -> bool { + if !self.is_ticking(p) { + return false; + } + let g = self.game; + let w = g.mob_world_base(&[]); + horizon_client::mobs::spawning::placement_ok(Species::Ravager, &w, p[0], p[1], p[2]) + || w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:snow" + && g.res.facts.is_air(g.world.block(p[0], p[1], p[2])) + } +} + +/// `DyeColor.getFireworkColor`. +const FIREWORK_COLORS: [u32; 16] = [ + 0xF0F0F0, 0xEB8844, 0xC354CD, 0x6689D3, 0xDECF2A, 0x41CD34, 0xD88198, 0x434343, 0xABABAB, + 0x287697, 0x7B2FBE, 0x253192, 0x51301A, 0x3B511A, 0xB3312C, 0x1E1B1B, +]; + +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} + +impl Game<'_> { + /// `Heightmap.Types.WORLD_SURFACE`: the first free block above the + /// highest non-air one. + pub(super) fn surface_height(&self, x: i32, z: i32) -> i32 { + let top = if self.dim == Dim::Nether { 127 } else { 319 }; + (horizon_client::chunk::MIN_Y..=top) + .rev() + .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) + .map_or(horizon_client::chunk::MIN_Y, |y| y + 1) + } + /// Every claimed village point of interest (job sites, beds, bells). + fn village_pois(&self) -> Vec<[i32; 3]> { + let mut out: Vec<[i32; 3]> = Vec::new(); + for m in &self.mobs { + if m.species() != Species::Villager || !m.alive() { + continue; + } + for p in [m.extra.home, m.extra.bed, m.extra.meeting] + .into_iter() + .flatten() + { + if !out.contains(&p) { + out.push(p); + } + } + } + out + } + fn difficulty_id(&self) -> i32 { + use horizon_world::food::Difficulty; + match self.world.health_rules.difficulty { + Difficulty::Peaceful => 0, + Difficulty::Easy => 1, + Difficulty::Normal => 2, + Difficulty::Hard => 3, + } + } + fn player_block(&self) -> Option<[i32; 3]> { + self.player.as_ref().map(|p| block_of(p.position)) + } + fn raids_path(&self) -> std::path::PathBuf { + self.world_root.join("data/minecraft/raids.dat") + } + fn load_raids(&mut self) { + if self.raiding.loaded { + return; + } + self.raiding.loaded = true; + let seed = self.world.random.next_long(); + if let Some(tag) = horizon_client::save::read_dat(&self.raids_path()) + && let Some(data) = tag.get("data") + { + self.raiding.raids = Raids::from_nbt(data, seed); + } + } + /// `Raids` as `data/minecraft/raids.dat`, when it changed. + pub(super) fn save_raids(&mut self) { + if !self.raiding.loaded || !self.raiding.raids.dirty || self.remote.is_some() { + return; + } + let tag = horizon_world::nbt::Tag::compound([ + ("data", self.raiding.raids.to_nbt()), + ( + "DataVersion", + horizon_world::nbt::Tag::Int(horizon_world::DATA_VERSION), + ), + ]); + if horizon_client::save::write_dat(&self.raids_path(), tag).is_ok() { + self.raiding.raids.dirty = false; + } + } + + /// `BadOmenMobEffect` and `RaidOmenMobEffect`, before the effects tick: + /// Bad Omen inside a village becomes Raid Omen, which starts or extends a + /// raid when it runs out. + pub(super) fn tick_omens(&mut self) { + if self.dim != Dim::Overworld || self.spectator() { + return; + } + let Some(pos) = self.player_block() else { + return; + }; + self.load_raids(); + if let Some(amp) = self.potions.effects.amplifier("bad_omen") + && self.difficulty_id() != 0 + && sections_to_village(&self.village_centers(), section(pos)) <= 1 + && self + .raiding + .raids + .nearby(pos) + .is_none_or(|(_, r)| r.omen_level < raid::MAX_OMEN_LEVEL) + { + self.potions.effects.list.retain(|e| e.id != "bad_omen"); + self.potions + .effects + .add(EffectInstance::new("raid_omen", 600, amp)); + self.raiding.omen_position = Some(pos); + let eye = self.eye_position().unwrap_or_default(); + self.audio + .play("minecraft:event.mob_effect.raid_omen", Some(eye), 1.0, 1.0); + } + let due = self + .potions + .effects + .get("raid_omen") + .filter(|e| e.duration == 1) + .map(|e| e.amplifier); + if let Some(amp) = due + && let Some(at) = self.raiding.omen_position.take() + { + self.create_or_extend_raid(at, Some(amp)); + } + } + /// `Raids.createOrExtendRaid`: the raid centres on the claimed village + /// points within 64 blocks. + fn create_or_extend_raid(&mut self, at: [i32; 3], amplifier: Option) -> Option { + if !self.ui.rules.bool("raids") || self.dim != Dim::Overworld { + return None; + } + let near: Vec<[i32; 3]> = self + .village_pois() + .into_iter() + .filter(|p| (0..3).map(|i| f64::from(p[i] - at[i]).powi(2)).sum::() <= 4096.0) + .collect(); + let center = if near.is_empty() { + at + } else { + let n = near.len() as f64; + let mean = |i: usize| near.iter().map(|p| f64::from(p[i])).sum::() / n; + [ + mean(0).floor() as i32, + mean(1).floor() as i32, + mean(2).floor() as i32, + ] + }; + let seed = self.world.random.next_long(); + let difficulty = self.difficulty_id(); + let (id, triggered) = self + .raiding + .raids + .create_or_extend(center, difficulty, amplifier, seed); + if triggered { + self.stats.custom("raid_trigger", 1); + self.trigger_player("minecraft:voluntary_exile"); + } + Some(id) + } + /// `ServerLevel.getRaidAt`. + pub(super) fn raiding_nearby(&self, at: [i32; 3]) -> Option { + self.raiding.raids.nearby(at).map(|(id, _)| id) + } + pub(super) fn raid_started(&self, id: i32) -> bool { + self.raiding.raids.get(id).is_some_and(|r| r.started) + } + /// `/raid start`: a raid in the local village at the given omen level. + pub(super) fn raid_command_create(&mut self, at: [i32; 3], omen_level: i32) -> bool { + self.load_raids(); + let Some(id) = self.create_or_extend_raid(at, None) else { + return false; + }; + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.omen_level = omen_level; + } + self.raiding.raids.dirty = true; + true + } + pub(super) fn raid_command_stop(&mut self, id: i32) { + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.stop(); + } + } + pub(super) fn raid_set_omen(&mut self, id: i32, level: i32) -> i32 { + let Some(r) = self.raiding.raids.map.get_mut(&id) else { + return 0; + }; + std::mem::replace(&mut r.omen_level, level) + } + pub(super) fn raid_glow(&mut self, id: i32) { + for m in &mut self.mobs { + if raider::state(m).is_some_and(|s| s.raid_id == Some(id)) { + m.add_effect("glowing", 1000, 1); + } + } + } + /// The `/raid check` summary line. + pub(super) fn raid_status_text(&self, id: i32) -> String { + let Some(r) = self.raiding.raids.get(id) else { + return String::new(); + }; + let members: Vec<&Mob> = self + .mobs + .iter() + .filter(|m| m.alive() && raider::state(m).is_some_and(|s| s.raid_id == Some(id))) + .collect(); + let health: f32 = members.iter().map(|m| m.health).sum(); + format!( + "Num groups spawned: {} Raid omen level: {} Num mobs: {} Raid health: {} / {}", + r.groups_spawned, + r.omen_level, + members.len(), + health, + r.total_health + ) + } + + /// The living raiders by raid. + fn raider_infos(&self, centers: &HashSet<(i32, i32, i32)>) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + for m in &self.mobs { + if !m.alive() || m.removed { + continue; + } + let Some(s) = raider::state(m) else { continue }; + let Some(id) = s.raid_id else { continue }; + let position = block_of(m.position); + out.entry(id).or_default().push(RaiderInfo { + id: m.id, + wave: s.wave, + health: m.health, + position, + age: m.age, + no_action_time: m.ai.no_action_time, + ticks_outside: s.ticks_outside_raid, + in_village: sections_to_village(centers, section(position)) <= 1, + }); + } + out + } + /// `ServerLevel.tick` for the raids and their raiders. + pub(super) fn tick_raids(&mut self) { + if self.remote.is_some() || self.dim != Dim::Overworld { + return; + } + self.load_raids(); + let centers = self.village_centers(); + let infos = self.raider_infos(¢ers); + let mut raids = std::mem::take(&mut self.raiding.raids); + let actions = { + let lvl = Lvl { + game: self, + difficulty: self.difficulty_id(), + centers: ¢ers, + raiders: &infos, + }; + raids.tick(&lvl, self.ui.rules.bool("raids"), self.player_block()) + }; + self.raiding.raids = raids; + for (id, action) in actions { + self.apply_raid_action(id, action); + } + self.sync_raiders(¢ers); + self.sync_villager_raids(&infos); + } + fn apply_raid_action(&mut self, id: i32, action: Action) { + match action { + Action::Spawn { pos, wave, spawns } => self.spawn_wave(id, pos, wave, &spawns), + Action::Horn { pos } => self.raid_horn(id, pos), + Action::Remove { id: mob } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + let s = raider::state_mut(m); + s.raid_id = None; + s.ticks_outside_raid = 0; + s.active_raid = false; + } + } + Action::SetOutside { id: mob, ticks } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + raider::state_mut(m).ticks_outside_raid = ticks; + } + } + Action::Victory { heroes, amplifier } => { + let me = self.level.player_uuid; + if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() { + let mut effect = + EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier); + effect.visible = false; + self.potions.effects.add(effect); + self.stats.custom("raid_win", 1); + self.trigger_player("minecraft:hero_of_the_village"); + } + } + } + } + /// `Raid.playSound`: the horn, 13 blocks away from the player toward the + /// wave, for players within 64 blocks or in the raid. + fn raid_horn(&mut self, id: i32, pos: [i32; 3]) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let in_raid = self.raiding.raids.get(id).is_some_and(|r| r.bar.player); + let (rx, rz) = (f64::from(pos[0]) + 0.5, f64::from(pos[2]) + 0.5); + let distance = ((rx - p.x).powi(2) + (rz - p.z).powi(2)).sqrt(); + if distance <= 64.0 || in_raid { + let k = 13.0 / distance.max(1e-4); + let at = [p.x + k * (rx - p.x), p.y, p.z + k * (rz - p.z)]; + self.audio + .play("minecraft:event.raid.horn", Some(at), 1.0, 1.0); + } + } + /// `Raid.spawnGroup`: a wave of raiders around `pos`, ravagers carrying + /// their riders. + fn spawn_wave(&mut self, raid_id: i32, pos: [i32; 3], wave: i32, spawns: &[Spawn]) { + let odds = self + .raiding + .raids + .get(raid_id) + .map_or(0.0, raid::Raid::enchant_odds); + for sp in spawns { + let Some(id) = self.spawn_raider(sp.kind, pos, raid_id, wave, sp.leader, odds) else { + continue; + }; + if let Some(kind) = sp.rider + && let Some(rider) = self.spawn_raider(kind, pos, raid_id, wave, false, odds) + { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == rider) { + raider::state_mut(m).vehicle = Some(id); + m.extra.passenger = true; + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + raider::state_mut(m).rider = true; + } + } + } + } + /// `Raid.joinRaid` for a new raider, with `applyRaidBuffs`. + fn spawn_raider( + &mut self, + kind: RaiderType, + pos: [i32; 3], + raid_id: i32, + wave: i32, + leader: bool, + odds: f32, + ) -> Option { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.0, + f64::from(pos[2]) + 0.5, + ]; + let id = self.spawn_mob_for(kind.entity(), at, false, true)?; + let m = self.mobs.iter_mut().find(|m| m.id == id)?; + if leader { + raider::set_patrol_leader(m, true); + } + raider::finalize(m, raider::Reason::Event); + let s = raider::state_mut(m); + s.raid_id = Some(raid_id); + s.wave = wave; + s.can_join_raid = true; + s.ticks_outside_raid = 0; + s.active_raid = true; + m.on_ground = true; + // applyRaidBuffs: Quick Charge crossbows and Sharpness axes. + let enchant = m.random.next_float() <= odds; + match kind { + RaiderType::Pillager if enchant => { + raider::state_mut(m).enchant = if wave > raid::num_groups(2) { + 2 + } else if wave > raid::num_groups(1) { + 1 + } else { + 0 + }; + } + RaiderType::Vindicator => { + let level = if !enchant { + 0 + } else if wave > raid::num_groups(2) { + 2 + } else { + 1 + }; + raider::state_mut(m).enchant = level; + if level > 0 { + m.attrs.attack_damage += 1.0 + 0.5 * f32::from(level - 1); + } + } + _ => {} + } + Some(id) + } + + /// Per-tick raid bookkeeping of every raider (and the ravagers they + /// ride): the raid's state for the goals, joining and recruiting, + /// the banner of a fallen captain, idle time. + fn sync_raiders(&mut self, centers: &HashSet<(i32, i32, i32)>) { + let now = self.world.game_time; + let golems: HashSet = self + .mobs + .iter() + .filter(|m| m.species() == Species::IronGolem) + .map(|m| m.id) + .collect(); + // Living leaders and carried riders. + let mut leaders: HashSet<(i32, i32)> = HashSet::new(); + let mut ridden: HashSet = HashSet::new(); + let mut positions: Vec<(u32, Vec3, bool)> = Vec::new(); + for m in &self.mobs { + let Some(s) = raider::state(m) else { continue }; + if !m.alive() { + continue; + } + if let (Some(id), true) = (s.raid_id, s.patrol_leader) { + leaders.insert((id, s.wave)); + } + if let Some(v) = s.vehicle { + ridden.insert(v); + } + positions.push((m.id, m.position, s.active_raid)); + } + let banners: Vec<(usize, Vec3)> = self + .dropped + .iter() + .enumerate() + .filter(|(_, e)| { + &*e.stack.item == raider::BANNER + && e.stack.data().is_some_and(|d| d.ominous_banner) + && e.pickup_delay == 0 + }) + .map(|(i, e)| (i, e.position)) + .collect(); + let mut taken: Vec = Vec::new(); + let mut recruit: Vec<(i32, i32, Vec3)> = Vec::new(); + let homes = self.raid_homes(); + for m in &mut self.mobs { + let species = m.species(); + if !raider::is_raider(species) { + continue; + } + let alive = m.alive(); + let position = m.position; + let block = block_of(position); + let in_village = sections_to_village(centers, section(block)) <= 1; + let has_rider = ridden.contains(&m.id); + let target_golem = matches!(m.ai.target, Some(horizon_client::mobs::Who::Mob(t)) if golems.contains(&t)); + let target_player = m.ai.target == Some(horizon_client::mobs::Who::Player); + let (health, age, range) = (m.health, m.age, m.attrs.follow_range); + let raids = &mut self.raiding.raids; + let s = m.extra.raider.get_or_insert_with(Box::default); + s.rider = has_rider; + s.in_village = in_village; + if s.raid_id.is_some_and(|id| raids.get(id).is_none()) { + s.raid_id = None; + s.ticks_outside_raid = 0; + } + match s.raid_id.and_then(|id| raids.get(id)) { + Some(r) => { + s.active_raid = r.active; + s.raid_over = r.is_over(); + s.raid_loss = r.is_loss(); + s.raid_center = r.center; + s.homes = s.raid_id.and_then(|id| homes.get(&id).cloned()); + } + None => { + s.active_raid = false; + s.raid_over = false; + s.raid_loss = false; + s.homes = None; + s.banner_at = None; + } + } + if !alive { + continue; + } + // Raider.updateNoActionTime adds two per tick, and a raider + // fighting a player or golem in a raid is never idle. + if s.raid_id.is_some() { + m.ai.no_action_time = if target_player || target_golem { + 0 + } else { + m.ai.no_action_time + 1 + }; + } + // Raider.aiStep: join the raid the raider stands in. + if s.raid_id.is_none() + && s.can_join_raid + && now % 20 == 0 + && m.ai.no_action_time <= 2400 + && let Some((id, r)) = raids.nearby(block) + { + let wave = r.groups_spawned; + s.raid_id = Some(id); + s.wave = wave; + s.ticks_outside_raid = 0; + if let Some(r) = raids.map.get_mut(&id) { + r.total_health += health; + } + } + // PathfindToRaidGoal.recruitNearby. + if s.active_raid + && !s.raid_over + && !s.in_village + && age % 20 == 0 + && let Some(id) = s.raid_id + { + recruit.push((id, s.wave, position)); + } + // ObtainRaidLeaderBannerGoal. + s.banner_at = None; + if let Some(id) = s.raid_id + && s.active_raid + && !s.raid_over + && raider::can_be_leader(species) + && m.extra.head.as_deref() != Some(raider::BANNER) + && !leaders.contains(&(id, s.wave)) + { + let near = banners + .iter() + .filter(|(i, p)| { + !taken.contains(i) + && (p.x - position.x).abs() <= range + && (p.z - position.z).abs() <= range + && (p.y - position.y).abs() <= 8.0 + }) + .min_by(|a, b| { + a.1.distance_squared(position) + .total_cmp(&b.1.distance_squared(position)) + }); + if let Some((i, p)) = near { + s.banner_at = Some([p.x, p.y, p.z]); + if p.distance_squared(position) < 1.414 * 1.414 { + // pickUpItem: the banner becomes the wave's leader. + taken.push(*i); + leaders.insert((id, s.wave)); + s.banner_at = None; + s.patrol_leader = true; + s.patrolling = true; + m.extra.head = Some(raider::BANNER.into()); + } + } + } + } + taken.sort_unstable(); + for i in taken.into_iter().rev() { + self.dropped.remove(i); + } + // Recruiting: raiders nearby that are in no raid join this one. + for (id, wave, at) in recruit { + let now_nearby: Vec = positions + .iter() + .filter(|(_, p, active)| { + !active + && (p.x - at.x).abs() <= 16.0 + && (p.y - at.y).abs() <= 16.0 + && (p.z - at.z).abs() <= 16.0 + }) + .map(|(i, _, _)| *i) + .collect(); + for mid in now_nearby { + let Some(m) = self.mobs.iter_mut().find(|m| m.id == mid) else { + continue; + }; + let health = m.health; + let idle = m.ai.no_action_time; + let s = raider::state_mut(m); + if s.raid_id.is_none() && s.can_join_raid && idle <= 2400 { + s.raid_id = Some(id); + s.wave = wave; + s.ticks_outside_raid = 0; + s.active_raid = true; + if let Some(r) = self.raiding.raids.map.get_mut(&id) { + r.total_health += health; + } + } + } + } + } + /// Beds within 64 blocks of each raid's centre (the `HOME` points of + /// interest), rescanned every five seconds. + fn raid_homes(&mut self) -> HashMap>> { + let now = self.world.game_time; + let ids: Vec<(i32, [i32; 3])> = self + .raiding + .raids + .map + .iter() + .filter(|(_, r)| r.active && !r.is_over() && r.started) + .map(|(id, r)| (*id, r.center)) + .collect(); + self.raiding + .homes + .retain(|id, _| ids.iter().any(|(i, _)| i == id)); + for (id, c) in ids { + if self + .raiding + .homes + .get(&id) + .is_some_and(|(at, _)| now - at < 100) + { + continue; + } + let mut beds = Vec::new(); + let mut known: HashMap = HashMap::new(); + for y in c[1] - 32..=c[1] + 32 { + for z in c[2] - 64..=c[2] + 64 { + for x in c[0] - 64..=c[0] + 64 { + let state = self.world.block(x, y, z); + if self.res.facts.is_air(state) { + continue; + } + let bed = *known.entry(state.0).or_insert_with(|| { + self.res.facts.get(state).name.ends_with("_bed") + && self.res.assets.registry.state(state).is_some_and(|s| { + s.properties.get("part").map(String::as_str) == Some("head") + }) + }); + if bed { + beds.push([x, y, z]); + } + } + } + } + self.raiding + .homes + .insert(id, (now, std::sync::Arc::new(beds))); + } + self.raiding + .homes + .iter() + .map(|(id, (_, v))| (*id, v.clone())) + .collect() + } + /// A raider riding a ravager sits on its back (`Entity.positionRider` + /// with the ravager's passenger attachment and a 0.6 riding offset). + pub(super) fn sync_riders(&mut self) { + let vehicles: HashMap = self + .mobs + .iter() + .filter(|m| m.species() == Species::Ravager) + .map(|m| { + ( + m.id, + ( + m.position, + m.previous, + m.body_yaw, + m.previous_body_yaw, + m.alive(), + ), + ) + }) + .collect(); + for m in &mut self.mobs { + let Some(v) = raider::state(m).and_then(|s| s.vehicle) else { + continue; + }; + match vehicles.get(&v) { + Some(&(pos, prev, yaw, prev_yaw, true)) => { + let place = |p: Vec3, yaw: f32| { + let a = f64::from(yaw).to_radians(); + // The attachment's z offset of -0.0625, rotated. + Vec3::new( + p.x + a.sin() * -0.0625, + p.y + 2.2625 - 0.6, + p.z - a.cos() * -0.0625, + ) + }; + m.position = place(pos, yaw); + m.previous = place(prev, prev_yaw); + m.velocity = Vec3::ZERO; + m.fall_distance = 0.0; + m.on_ground = false; + m.body_yaw = yaw; + m.previous_body_yaw = prev_yaw; + m.extra.passenger = true; + // Raiders on a ravager never walk off on their own. + m.ai.nav.stop(); + } + _ => { + raider::state_mut(m).vehicle = None; + m.extra.passenger = false; + } + } + } + } + /// `Raider.die`: the killing player becomes a hero of the village. + pub(super) fn raider_died(&mut self, m: &Mob, by_player: bool) { + let Some(id) = raider::state(m).and_then(|s| s.raid_id) else { + return; + }; + if by_player + && let Some(uuid) = self.level.player_uuid + && let Some(r) = self.raiding.raids.map.get_mut(&id) + { + r.add_hero(uuid); + } + } + + /// `SetRaidStatus` / `ResetRaidStatus` for villagers: which raid package + /// they follow, by the raid nearest to them. + fn sync_villager_raids(&mut self, infos: &HashMap>) { + let raids = &self.raiding.raids; + let random = &mut self.world.random; + for m in &mut self.mobs { + if m.species() != Species::Villager { + continue; + } + let at = block_of(m.position); + let status = match raids.nearby(at) { + Some((id, r)) if !r.is_stopped() && !r.is_loss() => { + let alive = infos.get(&id).map_or(0, Vec::len); + if r.is_victory() { + mobs_villager::RAID_VICTORY + } else if r.has_first_wave_spawned() && !r.is_between_waves(alive) { + mobs_villager::RAID + } else { + mobs_villager::PRE_RAID + } + } + _ => mobs_villager::RAID_NONE, + }; + let ext = mobs_villager::ext_mut(m); + // ResetRaidStatus clears at once; SetRaidStatus one tick in twenty. + if status == mobs_villager::RAID_NONE + || ext.raid != status && random.next_int_bound(20).unwrap_or(1) == 0 + { + ext.raid = status; + } + } + } + + /// The raid boss bars (`BossHealthOverlay`): a red notched bar with the + /// raid's title. Returns the next free row. + pub(super) fn draw_raid_bar(&self, batch: &mut HudBatch, mut y: f32) -> f32 { + let atlas = &self.res.atlas; + for raid in self.raiding.raids.map.values() { + if !raid.bar.visible || !raid.bar.player || raid.is_stopped() { + continue; + } + let x = (batch.width / 2.0 - 91.0).floor(); + batch.sprite(atlas, "gui/sprites/boss_bar/red_background", x, y); + batch.sprite(atlas, "gui/sprites/boss_bar/notched_10_background", x, y); + let p = raid.bar.progress; + // Mth.lerpDiscrete(progress, 0, 182). + let width = (p * 181.0).floor() as i32 + i32::from(p > 0.0); + if width > 0 { + let fraction = width as f32 / 182.0; + batch.sprite_part(atlas, "gui/sprites/boss_bar/red_progress", x, y, fraction); + batch.sprite_part( + atlas, + "gui/sprites/boss_bar/notched_10_progress", + x, + y, + fraction, + ); + } + let title = self.translate("event.minecraft.raid", "Raid"); + let name = match raid.bar.name { + BarName::Raid => title, + BarName::Remaining(n) => format!( + "{title} - {}", + self.translate( + "event.minecraft.raid.raiders_remaining", + "Raiders Remaining: %s" + ) + .replace("%s", &n.to_string()) + ), + BarName::Victory => { + self.translate("event.minecraft.raid.victory.full", "Raid - Victory") + } + BarName::Defeat => { + self.translate("event.minecraft.raid.defeat.full", "Raid - Defeat") + } + }; + let w = HudBatch::text_width(atlas, &name); + batch.text( + atlas, + &name, + (batch.width / 2.0 - w / 2.0).floor(), + y - 9.0, + rgba(255, 255, 255, 255), + true, + ); + y += 19.0; + } + y + } + /// A firework a villager launches to celebrate (`CelebrateVillagersSurvivedRaid`). + pub(super) fn villager_firework(&mut self, at: [f64; 3], color: usize, flight: u8) { + let mut stack = horizon_client::items::ItemStack::new("minecraft:firework_rocket", 1); + stack.data_mut().fireworks = Some(( + flight, + vec![horizon_client::particles::FireworkExplosion { + shape: horizon_client::particles::FireworkShape::Burst, + colors: vec![FIREWORK_COLORS[color & 15]], + fade: Vec::new(), + trail: false, + twinkle: false, + }], + )); + let rocket = self.new_rocket(Vec3::new(at[0], at[1], at[2]), &stack, false); + self.rockets.push(rocket); + } + /// `BehaviorUtils.throwItem`: a hero's gift tossed toward the player. + pub(super) fn throw_gift(&mut self, table: &str, from: [f64; 3], to: [f64; 3]) { + let drops = self + .res + .items + .loot_table(table, false, None, &mut self.world.random); + let d = Vec3::new(to[0] - from[0], to[1] - from[1], to[2] - from[2]).normalize(); + for stack in drops { + self.spawn_item(stack, from, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10); + } + } +} + impl Game<'_> { /// Sections holding a claimed village point of interest (a job site, /// bed or bell a villager has taken): `PoiManager.isVillageCenter`. diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index d6cd6371d..3668e5f9f 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -75,9 +75,9 @@ impl Game<'_> { Ok(()) } /// The wither boss bars (purple, below the dragon's), within range. - pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) { + pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 { let Some(p) = self.player.as_ref() else { - return; + return y; }; let atlas = &self.res.atlas; for m in self @@ -117,6 +117,7 @@ impl Game<'_> { ); y += 19.0; } + y } pub(super) fn wither_near(&self) -> bool { self.player.as_ref().is_some_and(|p| { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4d9ef4fbc..714f49308 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -53,6 +53,7 @@ pub mod packs; pub mod particles; pub mod pose; pub mod projectiles; +pub mod raid; pub mod save; pub mod screen_effects; pub mod settings; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index d90acb0b1..fa4da287e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -479,6 +479,8 @@ pub struct Extra { pub trade: Option>, /// A raider's patrol and raid state. pub raider: Option>, + /// A villager's raid activity and gossip. + pub villager: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -663,6 +665,18 @@ pub enum MobEvent { kind: DamageKind, amount: f32, }, + /// A villager launches a firework rocket (celebrating a won raid). + Firework { + at: [f64; 3], + color: usize, + flight: u8, + }, + /// A villager throws a hero's gift (a loot table) toward the player. + ThrowGift { + table: String, + from: [f64; 3], + to: [f64; 3], + }, /// A patrol leader hands its patrol target to a companion. PatrolTarget { mob: u32, @@ -753,6 +767,8 @@ pub struct PlayerView { pub hurt_by: Option<(Who, i64)>, /// `getLastHurtMob` and when. pub last_hurt: Option<(Who, i64)>, + /// The Hero of the Village effect. + pub hero: bool, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 155e9ea5e..2351916ad 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -384,8 +384,10 @@ impl CrossbowAttack { pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal { CrossbowAttack::new(speed, radius) } -/// `CrossbowItem.getChargeDuration` without Quick Charge. -const CHARGE: i32 = 25; +/// `CrossbowItem.getChargeDuration` (25 ticks, 5 fewer per level of Quick Charge). +pub fn charge_ticks(m: &Mob) -> i32 { + 25 - 5 * i32::from(super::raider::state(m).map_or(0, |s| s.enchant)) +} fn holding_crossbow(m: &Mob) -> bool { m.extra.main_hand.as_deref() == Some("minecraft:crossbow") } @@ -469,7 +471,7 @@ impl Goal for CrossbowAttack { } Crossbow::Charging => { m.extra.using_item += 1; - if m.extra.using_item >= CHARGE { + if m.extra.using_item >= charge_ticks(m) { m.extra.using_item = 0; m.extra.flag = false; self.state = Crossbow::Charged; @@ -534,6 +536,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { enum ArmPose { Spellcasting, Crossed, + Celebrating, Neutral, Attacking, CrossbowHold, @@ -554,16 +557,22 @@ fn arm_pose(m: &Mob) -> ArmPose { } } Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting, + Species::Evoker if celebrating(m) => ArmPose::Celebrating, Species::Evoker => ArmPose::Crossed, _ => { if m.ai.aggressive { ArmPose::Attacking + } else if celebrating(m) { + ArmPose::Celebrating } else { ArmPose::Crossed } } } } +fn celebrating(m: &Mob) -> bool { + super::raider::state(m).is_some_and(|s| s.celebrating) +} /// Whether the held item shows (vindicators only draw their axe when angry). pub fn shows_item(m: &Mob) -> bool { m.species() != Species::Vindicator || m.ai.aggressive @@ -637,8 +646,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { ArmPose::CrossbowCharge => { p.yrot("right_arm", -0.8); p.xrot("right_arm", -0.970_796_35); - let a = - (m.extra.using_item as f32 + s.partial).clamp(0.0, CHARGE as f32) / CHARGE as f32; + let charge = charge_ticks(m) as f32; + let a = (m.extra.using_item as f32 + s.partial).clamp(0.0, charge) / charge; p.yrot("left_arm", 0.4 + (0.85 - 0.4) * a); p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a); } @@ -655,6 +664,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { v[5] = z_rot; } } + ArmPose::Celebrating => { + for (arm, x, z_rot) in [ + ("right_arm", -5.0, 2.670_354), + ("left_arm", 5.0, -PI * 0.75), + ] { + let v = p.get(arm); + v[2] = 0.0; + v[0] = x; + v[3] = (s.age * 0.6662).cos() * 0.05; + v[4] = 0.0; + v[5] = z_rot; + } + } ArmPose::Crossed | ArmPose::Neutral => {} } if pose == ArmPose::Crossed { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 95a8f9dea..e2f053801 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -30,6 +30,28 @@ pub struct State { pub celebrating: bool, /// The raid is active (`hasActiveRaid`); set by the game every tick. pub active_raid: bool, + /// The raid is won or lost (`Raid.isOver`), lost (`isLoss`). + pub raid_over: bool, + pub raid_loss: bool, + pub raid_center: [i32; 3], + /// Standing in or beside a village (`ServerLevel.isVillage`). + pub in_village: bool, + /// A dropped ominous banner this raider may fetch. + pub banner_at: Option<[f64; 3]>, + /// Beds around the raid's centre. + pub homes: Option>>, + /// The ravager this raider rides, and (for a ravager) that it carries one. + pub vehicle: Option, + pub rider: bool, + /// Quick Charge (pillager crossbows) or Sharpness (vindicator axes) from + /// the raid's enchanting. + pub enchant: u8, +} +impl State { + /// A ravager carrying a raider (`hasControllingPassenger`). + pub fn has_rider(&self) -> bool { + self.rider + } } /// The raider species (`EntityTypeTags.RAIDERS`). @@ -67,6 +89,10 @@ pub fn register(m: &mut Mob) { } m.extra.raider = Some(Box::default()); let species = m.species(); + m.ai.goals.add(1, ObtainBanner); + m.ai.goals.add(3, PathfindToRaid); + m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); + m.ai.goals.add(5, Celebration); m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); // The illagers hold their ground in a patrol (Witch and Ravager do not). if matches!(species, Species::Pillager | Species::Vindicator) { @@ -292,10 +318,203 @@ fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { < distance * distance } -impl State { - /// A ravager carrying a raider (`hasControllingPassenger`). - pub fn has_rider(&self) -> bool { - false +/// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when +/// the wave has no living leader (the game finds the banner and picks it up). +#[derive(Clone, Debug)] +pub struct ObtainBanner; +impl Goal for ObtainBanner { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + state(m).is_some_and(|s| s.banner_at.is_some()) + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some()) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(at) = state(m).and_then(|s| s.banner_at) { + m.nav_move_to(cx.w, at, 1.15); + } + } +} + +/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in +/// hops of up to 15 blocks. +#[derive(Clone, Debug)] +pub struct PathfindToRaid; +impl PathfindToRaid { + fn valid(s: &State) -> bool { + s.active_raid && !s.raid_over && !s.in_village + } +} +impl Goal for PathfindToRaid { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.ai.target.is_none() && state(m).is_some_and(|s| !s.has_rider() && Self::valid(s)) + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + state(m).is_some_and(Self::valid) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(c) = state(m).map(|s| s.raid_center) else { + return; + }; + if m.ai.nav.is_done() { + let to = [ + f64::from(c[0]) + 0.5, + f64::from(c[1]), + f64::from(c[2]) + 0.5, + ]; + if let Some(at) = + m.default_random_pos_towards(cx.w, 15, 4, to, std::f64::consts::FRAC_PI_2) + { + m.nav_move_to(cx.w, at, 1.0); + } + } + } +} + +/// `Raider.RaiderMoveThroughVillageGoal`: walk to a bed of the village not +/// visited lately, then onwards to the next one. +#[derive(Clone, Debug)] +pub struct MoveThroughVillage { + speed: f64, + distance: f64, + poi: Option<[i32; 3]>, + visited: Vec<[i32; 3]>, + stuck: bool, +} +impl MoveThroughVillage { + pub fn new(speed: f64, distance: f64) -> Self { + Self { + speed, + distance, + poi: None, + visited: Vec::new(), + stuck: false, + } + } +} +impl Goal for MoveThroughVillage { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + if self.visited.len() > 2 { + self.visited.remove(0); + } + let Some(s) = state(m) else { return false }; + if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() { + return false; + } + let Some(homes) = s.homes.clone() else { + return false; + }; + let near: Vec<[i32; 3]> = homes + .iter() + .copied() + .filter(|p| !self.visited.contains(p) && close_to_center(*p, m.position, 48.0)) + .collect(); + if near.is_empty() { + return false; + } + self.poi = Some(near[m.random.next_int_bound(near.len() as i32).unwrap_or(0) as usize]); + true + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + let Some(p) = self.poi else { return false }; + !m.ai.nav.is_done() + && m.ai.target.is_none() + && !close_to_center(p, m.position, f64::from(m.width()) + self.distance) + && !self.stuck + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.no_action_time = 0; + if let Some(p) = self.poi { + m.nav_move_to( + cx.w, + [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])], + self.speed, + ); + } + self.stuck = false; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + if let Some(p) = self.poi + && close_to_center(p, m.position, self.distance) + { + self.visited.push(p); + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = self.poi else { return }; + if !m.ai.nav.is_done() { + return; + } + let to = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + let next = m + .default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::PI / 10.0) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2)); + match next { + Some(at) => { + m.nav_move_to(cx.w, at, self.speed); + } + None => self.stuck = true, + } + } +} + +/// `Raider.RaiderCelebration`: after a lost village, cheer and jump. +#[derive(Clone, Debug)] +pub struct Celebration; +impl Goal for Celebration { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.alive() + && m.ai.target.is_none() + && state(m).is_some_and(|s| s.raid_loss && s.raid_id.is_some()) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + state_mut(m).celebrating = true; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + state_mut(m).celebrating = false; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.random + .next_int_bound(super::goals::reduced(100)) + .unwrap_or(1) + == 0 + { + let sound = match m.species() { + Species::Pillager => "entity.pillager.celebrate", + Species::Vindicator => "entity.vindicator.celebrate", + Species::Evoker => "entity.evoker.celebrate", + Species::Ravager => "entity.ravager.celebrate", + _ => "entity.witch.celebrate", + }; + m.voice(sound, cx.events); + } + if m.random + .next_int_bound(super::goals::reduced(50)) + .unwrap_or(1) + == 0 + { + m.ai.jumping = true; + } } } diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 105db50f2..5ed95eb3a 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -5,11 +5,11 @@ //! (work and restock at the job site, meet at the bell, sleep in the bed), //! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake. use super::{ - Mob, MobEvent, MobWorld, Species, + Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, goals::{ - Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, - goal_clone, + Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, + Stroll, goal_clone, }, }; use horizon_core::random::RandomSource; @@ -74,6 +74,8 @@ pub fn register(m: &mut Mob) { AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75), ); g.add(1, Panic::new(0.75)); + g.add(2, RaidBehavior::default()); + g.add(3, GiftToHero::default()); g.add(3, JobSite::default()); g.add(3, AcquireHome::default()); g.add(4, Schedule::default()); @@ -594,3 +596,216 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("right_leg", 0.0); p.yrot("left_leg", 0.0); } + +// ---- Raids: the raid activities and the gift for a hero. + +pub const RAID_NONE: u8 = 0; +/// A raid is near but no wave is on (`Activity.PRE_RAID`). +pub const PRE_RAID: u8 = 1; +/// A wave is on (`Activity.RAID`). +pub const RAID: u8 = 2; +/// The raid was won: the villagers celebrate. +pub const RAID_VICTORY: u8 = 3; + +/// Villager state beyond `Extra`'s scratch fields. +#[derive(Clone, Debug, Default)] +pub struct Ext { + /// Which raid package the villager follows. + pub raid: u8, +} +pub fn ext(m: &Mob) -> Option<&Ext> { + m.extra.villager.as_deref() +} +pub fn ext_mut(m: &mut Mob) -> &mut Ext { + m.extra.villager.get_or_insert_with(Box::default) +} +fn raid_status(m: &Mob) -> u8 { + ext(m).map_or(RAID_NONE, |e| e.raid) +} + +/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at +/// home (`LocateHidingPlace`), before one they gather at the bell and ring it +/// (`RingBell`), and after a victory they look for the sky to celebrate +/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`). +#[derive(Clone, Debug, Default)] +struct RaidBehavior { + next_move: i32, +} +impl Goal for RaidBehavior { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + raid_status(m) != RAID_NONE && !sleeping(m) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.next_move = 0; + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.next_move -= 1; + let p = m.position; + match raid_status(m) { + RAID => { + // LocateHidingPlace(24, 0.7, 1): back to the bed. + let Some(home) = m.extra.bed else { return }; + if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { + if distance(m, home) <= 24.0 { + m.nav_move_to(cx.w, center(home), 0.7); + } + self.next_move = 40; + } + } + PRE_RAID => { + // RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75). + let Some(bell) = m.extra.meeting else { return }; + if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) { + m.nav_move_to(cx.w, center(bell), 0.75); + self.next_move = 40; + } + if distance(m, bell) < 3.0 + && m.random.next_float() > 0.95 + && cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell" + { + cx.events.push(MobEvent::SoundId( + "minecraft:block.bell.use".into(), + center(bell), + 2.0, + 1.0, + )); + } + } + RAID_VICTORY => { + let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if cx.w.can_see_sky(x, y, z) { + // CelebrateVillagersSurvivedRaid.tick. + if m.random.next_int_bound(100).unwrap_or(1) == 0 { + m.voice("entity.villager.celebrate", cx.events); + } + if m.random.next_int_bound(200).unwrap_or(1) == 0 { + let color = m.random.next_int_bound(16).unwrap_or(0) as usize; + let flight = m.random.next_int_bound(3).unwrap_or(0) as u8; + cx.events.push(MobEvent::Firework { + at: [p.x, m.eye_y(), p.z], + color, + flight, + }); + } + m.nav_stop(); + } else if self.next_move <= 0 || m.ai.nav.is_done() { + // MoveToSkySeeingSpot: a random spot with a view of the sky. + for _ in 0..5 { + if let Some(at) = m.land_random_pos(cx.w, 15, 7) + && cx.w.can_see_sky( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ) + { + m.nav_move_to(cx.w, at, 0.5); + break; + } + } + self.next_move = 40; + } + } + _ => {} + } + } +} + +/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and +/// throws a gift of its profession, every so often. +#[derive(Clone, Debug)] +struct GiftToHero { + until_next: i32, + started: i64, + given: bool, +} +impl Default for GiftToHero { + fn default() -> Self { + Self { + until_next: 600, + started: 0, + given: false, + } + } +} +/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`). +fn gift_table(m: &Mob) -> String { + if m.is_baby() { + return "minecraft:gameplay/hero_of_the_village/baby_gift".into(); + } + let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15]; + let name = match profession { + "none" | "nitwit" => "unemployed", + other => other, + }; + format!("minecraft:gameplay/hero_of_the_village/{name}_gift") +} +fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool { + let Some(p) = &cx.w.player else { return false }; + p.hero + && p.alive + && !p.spectator + && m.position.distance_squared(p.position) <= 16.0 * 16.0 + && m.sees(cx.w, Who::Player) +} +impl Goal for GiftToHero { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !hero_in_view(m, cx) || sleeping(m) { + return false; + } + if self.until_next > 0 { + self.until_next -= 1; + return false; + } + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + hero_in_view(m, cx) && !self.given + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.given = false; + self.started = cx.w.game_time; + if let Some(p) = &cx.w.player { + m.look_at(p.eye); + } + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0); + m.nav_stop(); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + m.look_at(p.eye); + let near = m.position.distance_squared(p.position) < 25.0; + if near { + if cx.w.game_time - self.started > 20 { + cx.events.push(MobEvent::ThrowGift { + table: gift_table(m), + from: [m.position.x, m.eye_y() - 0.3, m.position.z], + to: [p.position.x, p.position.y, p.position.z], + }); + self.given = true; + } + m.nav_stop(); + } else if m.ai.nav.is_done() { + m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5); + } + } +} diff --git a/crates/horizon-client/src/raid.rs b/crates/horizon-client/src/raid.rs new file mode 100644 index 000000000..a3be4d191 --- /dev/null +++ b/crates/horizon-client/src/raid.rs @@ -0,0 +1,1069 @@ +//! Raids (`Raid` and `Raids`): the raid omen that starts one, the waves of +//! raiders each difficulty sends, the boss bar, victory and loss, and +//! `data/minecraft/raids.dat`. The world is reached through [`RaidLevel`] and +//! the results come back as [`Action`]s, so the rules can be tested alone. +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::nbt::Tag; +use std::collections::BTreeMap; + +pub const MAX_OMEN_LEVEL: i32 = 5; +/// `Raid.RAID_TIMEOUT_TICKS`. +const TIMEOUT: i64 = 48_000; +const PRE_RAID_TICKS: i32 = 300; +const POST_RAID_LIMIT: i32 = 40; +const CELEBRATION_TICKS: i32 = 600; +/// `Raids.getNearbyRaid(pos, 9216)`: within 96 blocks. +pub const VALID_RAID_RADIUS_SQR: f64 = 9216.0; +/// `RAID_REMOVAL_THRESHOLD_SQR`: a raider this far from the centre leaves. +const REMOVAL_THRESHOLD_SQR: f64 = 12544.0; +/// `HERO_OF_THE_VILLAGE_DURATION`. +pub const HERO_DURATION: i32 = 48_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Status { + Ongoing, + Victory, + Loss, + Stopped, +} +impl Status { + pub fn name(self) -> &'static str { + match self { + Self::Ongoing => "ongoing", + Self::Victory => "victory", + Self::Loss => "loss", + Self::Stopped => "stopped", + } + } + fn from_name(s: &str) -> Self { + match s { + "victory" => Self::Victory, + "loss" => Self::Loss, + "stopped" => Self::Stopped, + _ => Self::Ongoing, + } + } +} + +/// `Raid.RaiderType`, in spawn order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RaiderType { + Vindicator, + Evoker, + Pillager, + Witch, + Ravager, +} +impl RaiderType { + pub const ALL: [Self; 5] = [ + Self::Vindicator, + Self::Evoker, + Self::Pillager, + Self::Witch, + Self::Ravager, + ]; + pub fn entity(self) -> &'static str { + match self { + Self::Vindicator => "minecraft:vindicator", + Self::Evoker => "minecraft:evoker", + Self::Pillager => "minecraft:pillager", + Self::Witch => "minecraft:witch", + Self::Ravager => "minecraft:ravager", + } + } + /// The health `addWaveMob` counts toward the bar. + pub fn health(self) -> f32 { + match self { + Self::Witch => 26.0, + Self::Ravager => 100.0, + _ => 24.0, + } + } + pub fn can_be_leader(self) -> bool { + !matches!(self, Self::Witch | Self::Ravager) + } + /// `spawnsPerWaveBeforeBonus`, by wave number. + fn spawns(self) -> [i32; 8] { + match self { + Self::Vindicator => [0, 0, 2, 0, 1, 4, 2, 5], + Self::Evoker => [0, 0, 0, 0, 0, 1, 1, 2], + Self::Pillager => [0, 4, 3, 3, 4, 4, 4, 2], + Self::Witch => [0, 0, 0, 0, 3, 0, 0, 1], + Self::Ravager => [0, 0, 0, 1, 0, 1, 0, 2], + } + } +} +/// `Raid.getNumGroups`: waves per difficulty (0 peaceful to 3 hard). +pub fn num_groups(difficulty: i32) -> i32 { + match difficulty { + 1 => 3, + 2 => 5, + 3 => 7, + _ => 0, + } +} + +/// One raider of a wave, with the raider riding it (ravagers only). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Spawn { + pub kind: RaiderType, + pub leader: bool, + pub rider: Option, +} + +/// A raider that belongs to a raid, as the level reports it. +#[derive(Clone, Debug)] +pub struct RaiderInfo { + pub id: u32, + pub wave: i32, + pub health: f32, + pub position: [i32; 3], + /// `tickCount`. + pub age: u32, + pub no_action_time: i32, + pub ticks_outside: i32, + pub in_village: bool, +} + +/// What a raid asks of the world. +pub trait RaidLevel { + /// The world difficulty, 0 (peaceful) to 3 (hard). + fn difficulty(&self) -> i32; + fn has_chunk_at(&self, pos: [i32; 3]) -> bool; + /// `ServerLevel.isVillage`: within one section of a village centre. + fn is_village(&self, pos: [i32; 3]) -> bool; + /// Centres of the village sections within two sections of `pos`. + fn village_sections_near(&self, pos: [i32; 3]) -> Vec<[i32; 3]>; + /// The living raiders of a raid. + fn raiders(&self, raid: i32) -> Vec; + /// `Heightmap.WORLD_SURFACE` height at a column. + fn surface_height(&self, x: i32, z: i32) -> i32; + /// The chunks around the position are loaded and ticking. + fn is_ticking(&self, pos: [i32; 3]) -> bool; + /// A ravager may spawn there (or on snow), in loaded chunks. + fn can_spawn_at(&self, pos: [i32; 3]) -> bool; +} + +/// What the game must do after a raid tick. +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + /// Spawn the raiders of a wave around `pos`. + Spawn { + pos: [i32; 3], + wave: i32, + spawns: Vec, + }, + /// The raid horn, heard by players near or in the raid. + Horn { + pos: [i32; 3], + }, + /// A raider leaves the raid (far away, despawned or idle outside). + Remove { + id: u32, + }, + SetOutside { + id: u32, + ticks: i32, + }, + /// The raid was won: heroes get the effect at `level` (amplifier). + Victory { + heroes: Vec<[i32; 4]>, + amplifier: i32, + }, +} + +/// The raid boss bar's title. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BarName { + Raid, + Remaining(i32), + Victory, + Defeat, +} +#[derive(Clone, Debug)] +pub struct Bar { + pub name: BarName, + pub progress: f32, + pub visible: bool, + /// The local player is in the raid (`ServerBossEvent.getPlayers`). + pub player: bool, +} + +#[derive(Clone, Debug)] +pub struct Raid { + pub started: bool, + pub active: bool, + pub ticks_active: i64, + pub omen_level: i32, + pub groups_spawned: i32, + pub cooldown_ticks: i32, + pub post_raid_ticks: i32, + pub total_health: f32, + pub num_groups: i32, + pub status: Status, + pub center: [i32; 3], + pub heroes: Vec<[i32; 4]>, + pub bar: Bar, + celebration_ticks: i32, + wave_spawn_pos: Option<[i32; 3]>, + random: LegacyRandom, +} +impl Raid { + /// `new Raid(center, difficulty)`. + pub fn new(center: [i32; 3], difficulty: i32, seed: i64) -> Self { + Self { + started: false, + active: true, + ticks_active: 0, + omen_level: 0, + groups_spawned: 0, + cooldown_ticks: PRE_RAID_TICKS, + post_raid_ticks: 0, + total_health: 0.0, + num_groups: num_groups(difficulty), + status: Status::Ongoing, + center, + heroes: Vec::new(), + bar: Bar { + name: BarName::Raid, + progress: 0.0, + visible: true, + player: false, + }, + celebration_ticks: 0, + wave_spawn_pos: None, + random: LegacyRandom::new(seed), + } + } + pub fn is_over(&self) -> bool { + self.is_victory() || self.is_loss() + } + pub fn is_victory(&self) -> bool { + self.status == Status::Victory + } + pub fn is_loss(&self) -> bool { + self.status == Status::Loss + } + pub fn is_stopped(&self) -> bool { + self.status == Status::Stopped + } + pub fn has_first_wave_spawned(&self) -> bool { + self.groups_spawned > 0 + } + /// `isBetweenWaves`: the next wave is counting down. + pub fn is_between_waves(&self, raiders_alive: usize) -> bool { + self.has_first_wave_spawned() && raiders_alive == 0 && self.cooldown_ticks > 0 + } + pub fn stop(&mut self) { + self.active = false; + self.bar.player = false; + self.status = Status::Stopped; + } + fn has_bonus_wave(&self) -> bool { + self.omen_level > 1 + } + fn is_final_wave(&self) -> bool { + self.groups_spawned == self.num_groups + } + fn has_spawned_bonus_wave(&self) -> bool { + self.groups_spawned > self.num_groups + } + fn has_more_waves(&self) -> bool { + if self.has_bonus_wave() { + !self.has_spawned_bonus_wave() + } else { + !self.is_final_wave() + } + } + fn should_spawn_bonus_group(&self, alive: usize) -> bool { + self.is_final_wave() && alive == 0 && self.has_bonus_wave() + } + fn should_spawn_group(&self, alive: usize) -> bool { + self.cooldown_ticks == 0 + && (self.groups_spawned < self.num_groups || self.should_spawn_bonus_group(alive)) + && alive == 0 + } + /// `Raid.absorbRaidOmen`: the omen level rises by the effect's level. + /// True when this is the omen that first triggers the raid. + pub fn absorb_omen(&mut self, amplifier: i32) -> bool { + self.omen_level = (self.omen_level + amplifier + 1).clamp(0, MAX_OMEN_LEVEL); + !self.has_first_wave_spawned() + } + /// `Raid.getEnchantOdds`. + pub fn enchant_odds(&self) -> f32 { + match self.omen_level { + 2 => 0.1, + 3 => 0.25, + 4 => 0.5, + 5 => 0.75, + _ => 0.0, + } + } + pub fn add_hero(&mut self, uuid: [i32; 4]) { + if !self.heroes.contains(&uuid) { + self.heroes.push(uuid); + } + } + /// `Raid.getDefaultNumSpawns` and `getPotentialBonusSpawns`. + fn wave_count(&mut self, kind: RaiderType, wave: i32, difficulty: i32, bonus: bool) -> i32 { + let index = if bonus { self.num_groups } else { wave } as usize; + let base = kind.spawns()[index.min(7)]; + let easy = difficulty == 1; + let normal = difficulty == 2; + let extra = match kind { + RaiderType::Vindicator | RaiderType::Pillager => { + if easy { + self.random.next_int_bound(2).unwrap_or(0) + } else if normal { + 1 + } else { + 2 + } + } + RaiderType::Evoker => return base, + RaiderType::Witch => { + if easy || wave <= 2 || wave == 4 { + return base; + } + 1 + } + RaiderType::Ravager => i32::from(!easy && bonus), + }; + base + if extra > 0 { + self.random.next_int_bound(extra + 1).unwrap_or(0) + } else { + 0 + } + } + /// The raiders of wave `wave` (`spawnGroup`): per type the counted + /// spawns, the first able raider leading, and ravagers carrying a + /// pillager (the last normal wave) or an evoker and vindicators (hard). + pub fn compose_wave(&mut self, wave: i32, difficulty: i32, bonus: bool) -> Vec { + let mut out = Vec::new(); + let mut leader_set = false; + for kind in RaiderType::ALL { + let count = self.wave_count(kind, wave, difficulty, bonus); + let mut ravagers = 0; + for _ in 0..count { + let leader = !leader_set && kind.can_be_leader(); + leader_set |= leader; + let mut rider = None; + if kind == RaiderType::Ravager { + if wave == num_groups(2) { + rider = Some(RaiderType::Pillager); + } else if wave >= num_groups(3) { + rider = Some(if ravagers == 0 { + RaiderType::Evoker + } else { + RaiderType::Vindicator + }); + } + ravagers += 1; + } + out.push(Spawn { + kind, + leader, + rider, + }); + } + } + out + } + /// The health `joinRaid` adds for a wave. + pub fn wave_health(spawns: &[Spawn]) -> f32 { + spawns + .iter() + .map(|s| s.kind.health() + s.rider.map_or(0.0, RaiderType::health)) + .sum() + } + /// `Raid.findRandomSpawnPos`: a ring around the centre that closes in as + /// the countdown runs down. + fn find_spawn_pos(&mut self, level: &dyn RaidLevel, max_tries: i32) -> Option<[i32; 3]> { + let seconds = self.cooldown_ticks / 20; + let how_far = 0.22 * seconds as f32 - 0.24; + let start = self.random.next_float() * (std::f32::consts::PI * 2.0); + for i in 0..max_tries { + let angle = start + std::f32::consts::PI * i as f32 / 8.0; + let x = self.center[0] + + (angle.cos() * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + let z = self.center[2] + + (angle.sin() * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + let y = level.surface_height(x, z); + if (y - self.center[1]).abs() > 96 { + continue; + } + let pos = [x, y, z]; + if (!level.is_village(pos) || seconds <= 7) && level.can_spawn_at(pos) { + return Some(pos); + } + } + None + } + fn move_center_to_nearby_village(&mut self, level: &dyn RaidLevel) { + let c = self.center; + let d = |p: &[i32; 3]| (0..3).map(|i| f64::from(p[i] - c[i]).powi(2)).sum::(); + if let Some(best) = level + .village_sections_near(c) + .into_iter() + .min_by(|a, b| d(a).total_cmp(&d(b))) + { + self.center = best; + } + } + /// Boss bar progress while raiders are alive (`updateBossbar`). + pub fn update_bar(&mut self, living_health: f32) { + self.bar.progress = if self.total_health > 0.0 { + (living_health / self.total_health).clamp(0.0, 1.0) + } else { + 0.0 + }; + } + /// `Raid.tick`. `raiders` are the living members; `player` is whether + /// the local player's position falls in this raid. + pub fn tick(&mut self, id: i32, level: &dyn RaidLevel, player: bool) -> Vec { + let mut actions = Vec::new(); + if self.is_stopped() { + return actions; + } + let raiders = level.raiders(id); + let alive = raiders.len(); + if self.status == Status::Ongoing { + let was_active = self.active; + self.active = level.has_chunk_at(self.center); + if level.difficulty() == 0 { + self.stop(); + return actions; + } + if was_active != self.active { + self.bar.visible = self.active; + } + if !self.active { + return actions; + } + if !level.is_village(self.center) { + self.move_center_to_nearby_village(level); + } + if !level.is_village(self.center) { + if self.groups_spawned > 0 { + self.status = Status::Loss; + } else { + self.stop(); + } + } + self.ticks_active += 1; + if self.ticks_active >= TIMEOUT { + self.stop(); + return actions; + } + // Raid.updateBossbar, as raiders are hurt, die or leave. + if alive > 0 { + self.update_bar(raiders.iter().map(|r| r.health).sum()); + } else if self.started && !self.has_more_waves() { + self.bar.progress = 0.0; + } + if alive == 0 && self.has_more_waves() { + if self.cooldown_ticks <= 0 { + if self.cooldown_ticks == 0 && self.groups_spawned > 0 { + self.cooldown_ticks = PRE_RAID_TICKS; + self.bar.name = BarName::Raid; + return actions; + } + } else { + let cached = self.wave_spawn_pos.is_some(); + let mut try_find = !cached && self.cooldown_ticks % 5 == 0; + if cached && !self.wave_spawn_pos.is_some_and(|p| level.is_ticking(p)) { + try_find = true; + } + if try_find { + self.wave_spawn_pos = self.find_spawn_pos(level, 8); + } + if self.cooldown_ticks == PRE_RAID_TICKS || self.cooldown_ticks % 20 == 0 { + self.bar.player = player; + } + self.cooldown_ticks -= 1; + self.bar.progress = + ((PRE_RAID_TICKS - self.cooldown_ticks) as f32 / 300.0).clamp(0.0, 1.0); + } + } + if self.ticks_active % 20 == 0 { + self.bar.player = player; + self.update_raiders(&raiders, level, &mut actions); + self.bar.name = if alive > 0 && alive <= 2 { + BarName::Remaining(alive as i32) + } else { + BarName::Raid + }; + } + let mut sound = false; + let mut attempt = 0; + let mut spawned_alive = alive; + while self.should_spawn_group(spawned_alive) { + let pos = self + .wave_spawn_pos + .or_else(|| self.find_spawn_pos(level, 20)); + if let Some(pos) = pos { + self.started = true; + let wave = self.groups_spawned + 1; + let bonus = self.should_spawn_bonus_group(spawned_alive); + let difficulty = level.difficulty(); + let spawns = self.compose_wave(wave, difficulty, bonus); + self.total_health = Self::wave_health(&spawns); + spawned_alive = spawns + .iter() + .map(|s| 1 + usize::from(s.rider.is_some())) + .sum(); + self.wave_spawn_pos = None; + self.groups_spawned += 1; + self.bar.progress = 1.0; + actions.push(Action::Spawn { pos, wave, spawns }); + if !sound { + actions.push(Action::Horn { pos }); + sound = true; + } + } else { + attempt += 1; + } + if attempt > 5 { + self.stop(); + break; + } + } + if self.started && !self.has_more_waves() && alive == 0 { + if self.post_raid_ticks < POST_RAID_LIMIT { + self.post_raid_ticks += 1; + } else { + self.status = Status::Victory; + actions.push(Action::Victory { + heroes: self.heroes.clone(), + amplifier: self.omen_level - 1, + }); + } + } + } else if self.is_over() { + self.celebration_ticks += 1; + if self.celebration_ticks >= CELEBRATION_TICKS { + self.stop(); + return actions; + } + if self.celebration_ticks % 20 == 0 { + self.bar.player = player; + self.bar.visible = true; + if self.is_victory() { + self.bar.progress = 0.0; + self.bar.name = BarName::Victory; + } else { + self.bar.name = BarName::Defeat; + } + } + } + actions + } + /// `Raid.updateRaiders`. + fn update_raiders( + &mut self, + raiders: &[RaiderInfo], + level: &dyn RaidLevel, + actions: &mut Vec, + ) { + let _ = level; + for r in raiders { + let d = (0..3) + .map(|i| f64::from(self.center[i] - r.position[i]).powi(2)) + .sum::(); + let mut remove = d >= REMOVAL_THRESHOLD_SQR; + if !remove && r.age > 600 { + let mut outside = r.ticks_outside; + if !r.in_village && r.no_action_time > 2400 { + outside += 1; + actions.push(Action::SetOutside { + id: r.id, + ticks: outside, + }); + } + remove = outside >= 30; + } + if remove { + self.total_health -= r.health; + actions.push(Action::Remove { id: r.id }); + } + } + } + + pub fn to_nbt(&self) -> Tag { + Tag::compound([ + ("started", Tag::Byte(i8::from(self.started))), + ("active", Tag::Byte(i8::from(self.active))), + ("ticks_active", Tag::Long(self.ticks_active)), + ("raid_omen_level", Tag::Int(self.omen_level)), + ("groups_spawned", Tag::Int(self.groups_spawned)), + ("cooldown_ticks", Tag::Int(self.cooldown_ticks)), + ("post_raid_ticks", Tag::Int(self.post_raid_ticks)), + ("total_health", Tag::Float(self.total_health.to_bits())), + ("group_count", Tag::Int(self.num_groups)), + ("status", Tag::String(self.status.name().into())), + ("center", Tag::IntArray(self.center.to_vec())), + ( + "heroes_of_the_village", + Tag::List( + self.heroes + .iter() + .map(|u| Tag::IntArray(u.to_vec())) + .collect(), + ), + ), + ]) + } + pub fn from_nbt(tag: &Tag, seed: i64) -> Option { + let int = |k: &str| match tag.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + Some(Tag::Short(v)) => Some(i32::from(*v)), + _ => None, + }; + let center = match tag.get("center") { + Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], + _ => return None, + }; + let mut raid = Self::new(center, 0, seed); + raid.started = int("started")? != 0; + raid.active = int("active")? != 0; + raid.ticks_active = match tag.get("ticks_active") { + Some(Tag::Long(v)) => *v, + _ => 0, + }; + raid.omen_level = int("raid_omen_level").unwrap_or(0); + raid.groups_spawned = int("groups_spawned").unwrap_or(0); + raid.cooldown_ticks = int("cooldown_ticks").unwrap_or(PRE_RAID_TICKS); + raid.post_raid_ticks = int("post_raid_ticks").unwrap_or(0); + raid.total_health = match tag.get("total_health") { + Some(Tag::Float(bits)) => f32::from_bits(*bits), + _ => 0.0, + }; + raid.num_groups = int("group_count").unwrap_or(0); + raid.status = match tag.get("status") { + Some(Tag::String(s)) => Status::from_name(&s.to_string_lossy()), + _ => Status::Ongoing, + }; + if let Some(Tag::List(heroes)) = tag.get("heroes_of_the_village") { + for h in heroes { + if let Tag::IntArray(v) = h + && v.len() == 4 + { + raid.heroes.push([v[0], v[1], v[2], v[3]]); + } + } + } + raid.bar.visible = raid.active; + Some(raid) + } +} + +/// `Raids`: the raids of a dimension by id. +#[derive(Clone, Debug)] +pub struct Raids { + pub map: BTreeMap, + next_id: i32, + tick: i32, + /// Changed since the last save. + pub dirty: bool, +} +impl Default for Raids { + fn default() -> Self { + Self { + map: BTreeMap::new(), + next_id: 1, + tick: 0, + dirty: false, + } + } +} +impl Raids { + pub fn get(&self, id: i32) -> Option<&Raid> { + self.map.get(&id) + } + pub fn id_of(&self, raid: &Raid) -> Option { + self.map + .iter() + .find(|(_, r)| std::ptr::eq(*r, raid)) + .map(|(id, _)| *id) + } + /// `Raids.getNearbyRaid`: the closest active raid within 96 blocks. + pub fn nearby(&self, pos: [i32; 3]) -> Option<(i32, &Raid)> { + let mut best: Option<(i32, &Raid, f64)> = None; + for (id, r) in &self.map { + let d = (0..3) + .map(|i| f64::from(r.center[i] - pos[i]).powi(2)) + .sum::(); + if r.active && d < best.map_or(VALID_RAID_RADIUS_SQR, |b| b.2) { + best = Some((*id, r, d)); + } + } + best.map(|(id, r, _)| (id, r)) + } + /// `Raids.createOrExtendRaid`, after the caller found the village centre: + /// the raid at that position (a new one if none), with the omen's level + /// absorbed. Returns the raid id and whether the omen triggered it. + pub fn create_or_extend( + &mut self, + center: [i32; 3], + difficulty: i32, + omen_amplifier: Option, + seed: i64, + ) -> (i32, bool) { + let id = match self.nearby(center) { + Some((id, _)) => id, + None => { + self.next_id += 1; + self.map + .insert(self.next_id, Raid::new(center, difficulty, seed)); + self.next_id + } + }; + let mut triggered = false; + if let Some(raid) = self.map.get_mut(&id) + && (!raid.started || raid.omen_level < MAX_OMEN_LEVEL) + && let Some(amp) = omen_amplifier + { + triggered = raid.absorb_omen(amp); + } + self.dirty = true; + (id, triggered) + } + /// `Raids.tick`: every raid, stopped ones removed. `rules_raids` is the + /// `raids` game rule; `player` the local player's block position. + pub fn tick( + &mut self, + level: &dyn RaidLevel, + rules_raids: bool, + player: Option<[i32; 3]>, + ) -> Vec<(i32, Action)> { + self.tick += 1; + let inside = player.and_then(|p| self.nearby(p).map(|(id, _)| id)); + let mut out = Vec::new(); + let mut gone = Vec::new(); + for (id, raid) in &mut self.map { + if !rules_raids { + raid.stop(); + } + if raid.is_stopped() { + gone.push(*id); + continue; + } + for a in raid.tick(*id, level, inside == Some(*id)) { + out.push((*id, a)); + } + } + for id in gone { + self.map.remove(&id); + self.dirty = true; + } + if self.tick % 200 == 0 || !out.is_empty() { + self.dirty = true; + } + out + } + pub fn to_nbt(&self) -> Tag { + let raids = self + .map + .iter() + .map(|(id, r)| { + let mut tag = r.to_nbt(); + if let Tag::Compound(map) = &mut tag { + map.insert("id".into(), Tag::Int(*id)); + } + tag + }) + .collect(); + Tag::compound([ + ("raids", Tag::List(raids)), + ("next_id", Tag::Int(self.next_id)), + ("tick", Tag::Int(self.tick)), + ]) + } + pub fn from_nbt(tag: &Tag, seed: i64) -> Self { + let mut out = Self::default(); + if let Some(Tag::Int(v)) = tag.get("next_id") { + out.next_id = *v; + } + if let Some(Tag::Int(v)) = tag.get("tick") { + out.tick = *v; + } + if let Some(Tag::List(list)) = tag.get("raids") { + for (i, r) in list.iter().enumerate() { + if let Some(Tag::Int(id)) = r.get("id") + && let Some(raid) = Raid::from_nbt(r, seed.wrapping_add(i as i64)) + { + out.map.insert(*id, raid); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Level { + village: bool, + raiders: Vec, + difficulty: i32, + } + impl RaidLevel for Level { + fn difficulty(&self) -> i32 { + self.difficulty + } + fn has_chunk_at(&self, _: [i32; 3]) -> bool { + true + } + fn is_village(&self, _: [i32; 3]) -> bool { + self.village + } + fn village_sections_near(&self, _: [i32; 3]) -> Vec<[i32; 3]> { + Vec::new() + } + fn raiders(&self, _: i32) -> Vec { + self.raiders.clone() + } + fn surface_height(&self, _: i32, _: i32) -> i32 { + 64 + } + fn is_ticking(&self, _: [i32; 3]) -> bool { + true + } + fn can_spawn_at(&self, _: [i32; 3]) -> bool { + true + } + } + fn count(spawns: &[Spawn], kind: RaiderType) -> usize { + spawns.iter().filter(|s| s.kind == kind).count() + } + + #[test] + fn waves_per_difficulty() { + assert_eq!( + [0, 1, 2, 3].map(num_groups), + [0, 3, 5, 7], + "peaceful, easy, normal, hard" + ); + } + #[test] + fn first_wave_is_four_pillagers_plus_bonus() { + // Normal difficulty always adds one bonus roll (0 or 1) per + // pillager and vindicator slot: wave 1 has 4 pillagers and 0-1 more. + for seed in 0..50 { + let mut raid = Raid::new([0, 64, 0], 2, seed); + let w = raid.compose_wave(1, 2, false); + let pillagers = count(&w, RaiderType::Pillager); + assert!((4..=5).contains(&pillagers), "{pillagers}"); + assert!(count(&w, RaiderType::Vindicator) <= 1); + assert_eq!(count(&w, RaiderType::Ravager), 0); + assert_eq!(w.iter().filter(|s| s.leader).count(), 1); + } + } + #[test] + fn ravagers_carry_riders_by_wave() { + // Wave 5 on normal: the ravager carries a pillager. + let mut raid = Raid::new([0, 64, 0], 2, 1); + let w = raid.compose_wave(5, 2, false); + let ravagers: Vec<_> = w.iter().filter(|s| s.kind == RaiderType::Ravager).collect(); + assert_eq!(ravagers.len(), 1); + assert_eq!(ravagers[0].rider, Some(RaiderType::Pillager)); + // Wave 7 on hard: an evoker rides the first ravager, vindicators the rest. + let mut raid = Raid::new([0, 64, 0], 3, 1); + let w = raid.compose_wave(7, 3, false); + let riders: Vec<_> = w + .iter() + .filter(|s| s.kind == RaiderType::Ravager) + .map(|s| s.rider) + .collect(); + assert!(riders.len() >= 2); + assert_eq!(riders[0], Some(RaiderType::Evoker)); + assert!( + riders[1..] + .iter() + .all(|r| *r == Some(RaiderType::Vindicator)) + ); + // Wave 4 has no ravager. + let mut raid = Raid::new([0, 64, 0], 3, 1); + assert_eq!( + count(&raid.compose_wave(4, 3, false), RaiderType::Ravager), + 0 + ); + } + #[test] + fn witches_arrive_from_wave_five_and_bonus_waves_reuse_the_last_row() { + let mut raid = Raid::new([0, 64, 0], 2, 3); + assert_eq!(count(&raid.compose_wave(3, 2, false), RaiderType::Witch), 0); + assert_eq!(count(&raid.compose_wave(4, 2, false), RaiderType::Witch), 3); + // Bonus wave of a normal raid: the wave-5 row (and a possible + // extra ravager). + let bonus = raid.compose_wave(6, 2, true); + assert_eq!(count(&bonus, RaiderType::Evoker), 1); + assert!((1..=2).contains(&count(&bonus, RaiderType::Ravager))); + assert!(count(&bonus, RaiderType::Witch) <= 1); + } + #[test] + fn only_able_raiders_lead() { + let mut raid = Raid::new([0, 64, 0], 3, 9); + let w = raid.compose_wave(4, 3, false); + assert!( + w.iter() + .filter(|s| s.leader) + .all(|s| s.kind.can_be_leader()) + ); + assert_eq!(w.iter().filter(|s| s.leader).count(), 1); + } + #[test] + fn omen_levels_stack_and_clamp() { + let mut raid = Raid::new([0, 64, 0], 2, 1); + assert!(raid.absorb_omen(1)); + assert_eq!(raid.omen_level, 2); + raid.absorb_omen(4); + assert_eq!(raid.omen_level, MAX_OMEN_LEVEL); + assert_eq!(raid.enchant_odds(), 0.75); + } + #[test] + fn a_raid_counts_down_spawns_and_is_won() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 1, + }; + let mut raid = Raid::new([0, 64, 0], 1, 5); + raid.absorb_omen(0); + let mut spawned = 0; + // 300 ticks of countdown, then the first wave. + for _ in 0..400 { + for a in raid.tick(1, &level, true) { + if let Action::Spawn { wave, .. } = a { + spawned += 1; + assert_eq!(wave, 1); + } + } + if spawned > 0 { + break; + } + } + assert_eq!(spawned, 1); + assert!(raid.started && raid.groups_spawned == 1); + assert_eq!(raid.bar.progress, 1.0); + assert!(raid.total_health > 0.0); + } + #[test] + fn the_last_wave_cleared_wins_after_a_pause() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 1, + }; + let mut raid = Raid::new([0, 64, 0], 1, 5); + raid.started = true; + raid.groups_spawned = raid.num_groups; + raid.cooldown_ticks = 0; + let mut won = false; + for _ in 0..60 { + for a in raid.tick(1, &level, true) { + if let Action::Victory { amplifier, .. } = a { + won = true; + assert_eq!(amplifier, -1); + } + } + } + assert!(won && raid.is_victory()); + // The celebration lasts 600 ticks, then the raid stops. + for _ in 0..600 { + raid.tick(1, &level, true); + } + assert!(raid.is_stopped()); + } + #[test] + fn losing_the_village_loses_the_raid() { + let level = Level { + village: false, + raiders: Vec::new(), + difficulty: 2, + }; + let mut raid = Raid::new([0, 64, 0], 2, 5); + raid.started = true; + raid.groups_spawned = 2; + raid.tick(1, &level, true); + assert!(raid.is_loss()); + // Before any wave, losing the village just cancels the raid. + let mut fresh = Raid::new([0, 64, 0], 2, 5); + fresh.tick(1, &level, true); + assert!(fresh.is_stopped()); + } + #[test] + fn peaceful_stops_raids() { + let level = Level { + village: true, + raiders: Vec::new(), + difficulty: 0, + }; + let mut raid = Raid::new([0, 64, 0], 2, 5); + raid.tick(1, &level, true); + assert!(raid.is_stopped()); + } + #[test] + fn far_or_idle_raiders_leave() { + let raider = |id, x, no_action, outside| RaiderInfo { + id, + wave: 1, + health: 24.0, + position: [x, 64, 0], + age: 1000, + no_action_time: no_action, + ticks_outside: outside, + in_village: false, + }; + let level = Level { + village: true, + raiders: vec![ + raider(1, 500, 0, 0), + raider(2, 10, 3000, 29), + raider(3, 10, 0, 0), + ], + difficulty: 2, + }; + let mut raid = Raid::new([0, 64, 0], 2, 1); + raid.started = true; + raid.groups_spawned = 1; + raid.total_health = 72.0; + raid.ticks_active = 19; + let actions = raid.tick(1, &level, true); + assert!(actions.contains(&Action::Remove { id: 1 })); + assert!(actions.contains(&Action::Remove { id: 2 })); + assert!(!actions.contains(&Action::Remove { id: 3 })); + assert_eq!(raid.total_health, 24.0); + } + #[test] + fn raids_round_trip_through_nbt() { + let mut raids = Raids::default(); + let (id, triggered) = raids.create_or_extend([10, 64, 20], 2, Some(2), 7); + assert_eq!(id, 2); + assert!(triggered); + raids.map.get_mut(&id).unwrap().add_hero([1, 2, 3, 4]); + let back = Raids::from_nbt(&raids.to_nbt(), 1); + let raid = back.get(2).unwrap(); + assert_eq!(raid.center, [10, 64, 20]); + assert_eq!(raid.omen_level, 3); + assert_eq!(raid.num_groups, 5); + assert_eq!(raid.heroes, vec![[1, 2, 3, 4]]); + assert_eq!(raid.status, Status::Ongoing); + } + #[test] + fn a_second_omen_extends_the_nearby_raid() { + let mut raids = Raids::default(); + let (a, _) = raids.create_or_extend([0, 64, 0], 2, Some(0), 1); + let (b, again) = raids.create_or_extend([20, 64, 20], 2, Some(1), 1); + assert_eq!(a, b); + assert!(again); + assert_eq!(raids.get(a).unwrap().omen_level, 3); + let (c, _) = raids.create_or_extend([300, 64, 0], 2, Some(0), 1); + assert_ne!(a, c); + } +} From 7bbc85efa08cb85e32266ba67de4a1f322bcffdd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:16:57 +0200 Subject: [PATCH 6/7] Add villager gossip, breeding and golem defence Villagers remember players through gossip (major and minor, positive and negative, and trading) that fades by the day and spreads when villagers meet, saved with each villager. Hitting a villager earns a minor negative mark, killing one in front of others a major one, and each trade a small positive one; the reputation changes the prices, as does Hero of the Village. Villagers that meet swap gossip, pass surplus food to hungry neighbours (farmers to anyone) and wares to the profession that wants them, pick up food and seeds from the ground into an eight-slot inventory, and willing pairs (twelve food points, awake, adult) make a baby after about fourteen seconds when a free bed is within 48 blocks. Frightened villagers and gossiping groups that slept lately call for an iron golem, and golems defend a village against a player whom a villager nearby holds at minus 100. Bottles from structure loot keep their amplifier. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/entity_nbt.rs | 7 +- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/creatures.rs | 41 +- crates/horizon-client/src/game/trading.rs | 30 +- crates/horizon-client/src/game/villagers.rs | 467 +++++++++++++++ crates/horizon-client/src/gossip.rs | 386 ++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/merchant.rs | 43 ++ crates/horizon-client/src/mobs.rs | 19 + crates/horizon-client/src/mobs/golem.rs | 43 ++ crates/horizon-client/src/mobs/villager.rs | 564 ++++++++++++++++++ crates/horizon-client/src/structure_blocks.rs | 17 +- crates/horizon-world/src/loot.rs | 5 +- 13 files changed, 1613 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/src/game/villagers.rs create mode 100644 crates/horizon-client/src/gossip.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 4dcc75671..46e32f280 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -280,6 +280,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("RestocksToday".into(), Tag::Int(t.restocks_today)); put_offers(map, m); put_memories(map, m); + crate::mobs::villager::write_nbt(m, map); } "minecraft:wandering_trader" => put_offers(map, m), "minecraft:allay" => { @@ -1046,7 +1047,7 @@ fn put_offers(map: &mut Compound, m: &Mob) { } /// The villager brain's `job_site`, `home` and `meeting_point` memories. fn put_memories(map: &mut Compound, m: &Mob) { - let memories: Vec<(&str, Tag)> = [ + let mut memories: Vec<(&str, Tag)> = [ ("minecraft:job_site", m.extra.home), ("minecraft:home", m.extra.bed), ("minecraft:meeting_point", m.extra.meeting), @@ -1060,6 +1061,7 @@ fn put_memories(map: &mut Compound, m: &Mob) { Some((key, Tag::compound([("value", pos)]))) }) .collect(); + crate::mobs::villager::write_memories(m, &mut memories); map.insert( "Brain".into(), Tag::compound([("memories", Tag::compound(memories))]), @@ -1093,6 +1095,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) { m.extra.home = memory("minecraft:job_site"); m.extra.bed = memory("minecraft:home"); m.extra.meeting = memory("minecraft:meeting_point"); + if m.species() == crate::mobs::Species::Villager { + crate::mobs::villager::read_nbt(m, tag); + } let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else { return; }; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 96c01535d..b8f4a8529 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -63,6 +63,7 @@ mod tnt; mod totem; mod trading; mod trident; +mod villagers; mod wither; use horizon_client::{ Result, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 1198680e5..f7068662e 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -93,7 +93,8 @@ impl ProjectileWorld for ProjWorld<'_, '_> { .full_collision } } -fn seen(m: &Mob) -> Seen { +fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { + let villager = m.species() == Species::Villager; Seen { id: m.id, species: m.species(), @@ -102,7 +103,12 @@ fn seen(m: &Mob) -> Seen { eye_y: m.eye_y(), alive: m.alive(), baby: m.is_baby(), - in_love: m.extra.in_love > 0, + // A villager is "in love" when it is willing to breed (`canBreed`). + in_love: if villager { + horizon_client::mobs::villager::can_breed(m) + } else { + m.extra.in_love > 0 + }, tame: m.extra.tame, hostile: m.hostile(), target: m.ai.target, @@ -116,6 +122,12 @@ fn seen(m: &Mob) -> Seen { .then_some(m.extra.bed) .flatten(), active_raid: horizon_client::mobs::raider::has_active_raid(m), + player_rep: match (villager, player) { + (true, Some(uuid)) => { + horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)) + } + _ => 0, + }, } } impl Game<'_> { @@ -152,6 +164,7 @@ impl Game<'_> { hurt_by: self.player_hurt_by(), last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), hero: self.potions.effects.get("hero_of_the_village").is_some(), + uuid: self.level.player_uuid.unwrap_or_default(), }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -280,6 +293,21 @@ impl Game<'_> { "on_ground": m.on_ground, "variant": m.extra.variant, "color": m.extra.color, + "villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({ + "food_level": e.food_level, + "inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::>(), + "gossips": e.gossips.len(), + "last_slept": e.last_slept, + "raid": e.raid, + })), + "raider": horizon_client::mobs::raider::state(m).map(|s| serde_json::json!({ + "raid": s.raid_id, + "wave": s.wave, + "leader": s.patrol_leader, + "patrolling": s.patrolling, + "patrol_target": s.patrol_target, + "vehicle": s.vehicle, + })), }) }) .collect(); @@ -625,7 +653,8 @@ impl Game<'_> { self.spawn_natural(); self.tick_patrol_spawner(); self.tick_raids(); - let snapshot: Vec = self.mobs.iter().map(seen).collect(); + let uuid = self.level.player_uuid; + let snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); @@ -649,6 +678,8 @@ impl Game<'_> { } self.mobs.append(&mut mobs); self.sync_riders(); + self.villager_reputation_tick(); + self.villager_pickups(); for m in dead { self.mob_died(&m); } @@ -670,6 +701,7 @@ impl Game<'_> { self.trigger_entity("minecraft:player_killed_entity", "entity", &view); } self.raider_died(m, by_player); + self.villager_murdered(m, by_player); let held = self.held().cloned(); let pos = [m.position.x, m.position.y + 0.5, m.position.z]; if !m.is_baby() { @@ -1005,6 +1037,9 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other), + MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner), + MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed), MobEvent::Firework { at, color, flight } => { self.villager_firework(at, color, flight) } diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index d7070b3c8..6dea14edb 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -148,7 +148,13 @@ impl Game<'_> { })); } let m = &self.mobs[index]; - let trade = m.extra.trade.as_deref().cloned().unwrap_or_default(); + let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default(); + // Villager.updateSpecialPrices: reputation and Hero of the Village. + if species == Species::Villager { + let reputation = self.villager_reputation(m.id); + merchant::update_special_prices(&mut trade.offers, reputation, self.hero_amplifier()); + } + let m = &self.mobs[index]; if trade.offers.is_empty() { let mut events = Vec::new(); villager::set_unhappy(&mut self.mobs[index], &mut events); @@ -190,6 +196,10 @@ impl Game<'_> { let trade = m.extra.trade.get_or_insert_default(); trade.xp = state.xp; trade.offers = state.offers.clone(); + // setTradingPlayer(null) resets the special prices. + for offer in &mut trade.offers { + offer.special_price_diff = 0; + } } /// Opens a merchant menu for a villager (or a generated one for tests). pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) { @@ -244,6 +254,16 @@ impl Game<'_> { .map(|p| [p.position.x, p.position.y + 0.5, p.position.z]); self.audio .play("minecraft:entity.villager.yes", at, 1.0, 1.0); + // Villager.notifyTrade: the villager remembers the trade. + let villager = s + .merchant + .as_ref() + .filter(|m| m.progress()) + .and_then(|m| m.mob); + if let Some(mob) = villager { + self.villager_traded(mob); + } + let Some(m) = s.merchant.as_mut() else { return }; if level_up { let (profession, variant, level) = (m.profession.clone(), m.variant.clone(), m.level + 1); @@ -254,6 +274,14 @@ impl Game<'_> { } pop += 5; } + // The prices follow the villager's new reputation. + if let Some(mob) = villager { + let reputation = self.villager_reputation(mob); + let hero = self.hero_amplifier(); + if let Some(m) = s.merchant.as_mut() { + merchant::update_special_prices(&mut m.offers, reputation, hero); + } + } if offer.reward_exp && let Some(at) = at { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs new file mode 100644 index 000000000..cbf3d015b --- /dev/null +++ b/crates/horizon-client/src/game/villagers.rs @@ -0,0 +1,467 @@ +//! What villagers do with each other and with the player: gossip and +//! reputation, sharing food and wares, picking up dropped items, making +//! babies, calling iron golems and the prices they ask. +use super::Game; +use horizon_client::{ + gossip::{self, GossipType}, + items::ItemStack, + mobs::{Mob, Species, spawning, villager}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::HashMap; + +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on. +fn golem_floor_ok(name: &str) -> bool { + !matches!( + name, + "minecraft:cobweb" + | "minecraft:cactus" + | "minecraft:glass_pane" + | "minecraft:conduit" + | "minecraft:ice" + | "minecraft:tnt" + | "minecraft:glowstone" + | "minecraft:beacon" + | "minecraft:sea_lantern" + | "minecraft:frosted_ice" + | "minecraft:tinted_glass" + | "minecraft:glass" + ) && !name.ends_with("_stained_glass_pane") + && !name.ends_with("_stained_glass") + && !name.ends_with("leaves") +} + +impl Game<'_> { + fn villager_index(&self, id: u32) -> Option { + self.mobs + .iter() + .position(|m| m.id == id && m.species() == Species::Villager) + } + fn item_max_stack(&self, item: &str) -> u32 { + self.res.items.get(item).map_or(64, |i| i.max_stack) + } + /// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward + /// a point. + fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) { + let at = [from.x, eye - 0.3, from.z]; + let d = Vec3::new(to.x - from.x, to.y - from.y, to.z - from.z).normalize(); + self.spawn_item(stack, at, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10); + } + + /// `TradeWithVillager.tick` for one pair: gossip (at most once in 1200 + /// ticks for both), then surplus food and wanted wares tossed over. + pub(super) fn villager_meet(&mut self, a: u32, b: u32) { + let (Some(ia), Some(ib)) = (self.villager_index(a), self.villager_index(b)) else { + return; + }; + let now = self.world.game_time; + let items = &self.res.items; + let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack); + // Villager.gossip: both must be past their cool-down. + let ready = { + let ea = villager::ext(&self.mobs[ia]); + let eb = villager::ext(&self.mobs[ib]); + ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now)) + }; + let mut golem = false; + if ready { + let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default(); + let me = &mut self.mobs[ia]; + let mut random = me.random.clone(); + let e = villager::ext_mut(me); + e.gossips.transfer_from(&source.gossips, &mut random, 10); + e.last_gossip_time = now; + me.random = random; + villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now; + golem = true; + } + // Surplus food goes to a hungry neighbour (farmers hand it to anyone). + let farmer = villager::is_farmer(&self.mobs[ia]); + let (from, eye, to) = ( + self.mobs[ia].position, + self.mobs[ia].eye_y(), + self.mobs[ib].position, + ); + let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food()); + let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food()); + let mut thrown = Vec::new(); + if excess + && (farmer || wants_more) + && let Some(s) = villager::ext_mut(&mut self.mobs[ia]) + .take_half_stack(|s| villager::food_points(&s.item) > 0, max) + { + thrown.push(s); + } + // A farmer's wheat. + if farmer + && villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32) + && let Some(s) = villager::ext_mut(&mut self.mobs[ia]) + .take_half_stack(|s| &*s.item == "minecraft:wheat", max) + { + thrown.push(s); + } + // Wares the neighbour's profession asks for and ours does not. + let theirs = villager::requested_items(&self.mobs[ib]); + let mine = villager::requested_items(&self.mobs[ia]); + let wanted: Vec<&str> = theirs + .iter() + .copied() + .filter(|i| !mine.contains(i)) + .collect(); + if !wanted.is_empty() + && let Some(s) = villager::ext_mut(&mut self.mobs[ia]) + .take_half_stack(|s| wanted.contains(&&*s.item), max) + { + thrown.push(s); + } + for stack in thrown { + self.villager_throw(from, eye, to, stack); + } + if golem { + self.villager_golem_check(a, 5); + } + } + + /// `Villager.spawnGolemIfNeeded`: when enough villagers nearby that + /// slept recently and saw no golem agree, an iron golem appears. + pub(super) fn villager_golem_check(&mut self, id: u32, needed: usize) { + let Some(i) = self.villager_index(id) else { + return; + }; + let now = self.world.game_time; + if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) { + return; + } + let at = self.mobs[i].position; + let nearby: Vec = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| { + m.species() == Species::Villager + && m.alive() + && (m.position.x - at.x).abs() <= 10.0 + && (m.position.y - at.y).abs() <= 10.0 + && (m.position.z - at.z).abs() <= 10.0 + }) + .map(|(j, _)| j) + .collect(); + let wanting = nearby + .iter() + .filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now))) + .take(5) + .count(); + if wanting < needed { + return; + } + if self.try_spawn_iron_golem(block_of(at)) { + for j in nearby { + villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599; + } + } + } + /// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up + /// and down, LEGACY_IRON_GOLEM)`. + fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool { + for _ in 0..10 { + let r = &mut self.world.random; + let dx = r.next_int_bound(17).unwrap_or(8) - 8; + let dz = r.next_int_bound(17).unwrap_or(8) - 8; + let (x, z) = (start[0] + dx, start[2] + dz); + let mut y = start[1] + 6; + let mut above = self.world.block(x, y, z); + let mut found = None; + for _ in 0..=12 { + y -= 1; + let here = self.world.block(x, y, z); + let f = self.res.facts.get(here); + let above_f = self.res.facts.get(above); + let air_or_liquid = self.res.facts.is_air(above) + || above_f.fluid != horizon_client::blocks::Fluid::None; + let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID + != 0 + || f.name.as_ref() == "minecraft:powder_snow"; + if golem_floor_ok(&f.name) && air_or_liquid && solid { + found = Some(y + 1); + break; + } + above = here; + } + let Some(y) = found else { continue }; + // IronGolem.checkSpawnRules: a floor and three free blocks. + let free = |g: &Self, yy: i32| { + g.res.mob_data.state(g.world.block(x, yy, z)).flags + & horizon_client::mobs::data::VALID_EMPTY_SPAWN + != 0 + }; + if !(0..4).all(|k| free(self, y + k)) { + continue; + } + let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]; + if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + let sound = m.kind.sounds[0]; + if !sound.is_empty() { + let at = m.center(); + self.audio + .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); + } + return true; + } + } + false + } + + /// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48 + /// blocks is taken for the child, who is a baby villager of one of + /// three villager types. + pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) { + let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner)) + else { + return; + }; + villager::ext_mut(&mut self.mobs[ia]).eat_and_digest(); + villager::ext_mut(&mut self.mobs[ib]).eat_and_digest(); + let from = self.mobs[ia].position; + let angry = |g: &mut Self| { + for i in [ia, ib] { + let p = g.mobs[i].position; + g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]); + } + }; + let Some(bed) = self.take_vacant_bed(block_of(from)) else { + angry(self); + return; + }; + // Villager.getBreedOffspring: half the biome's type, a quarter each parent's. + let roll = self.mobs[ia].random.next_double(); + let kind_of = |m: &Mob| m.extra.variant; + let facts = self.biome_facts( + from.x.floor() as i32, + from.y.floor() as i32, + from.z.floor() as i32, + ); + let variant = if roll < 0.5 { + spawning::villager_type(&facts) + } else if roll < 0.75 { + kind_of(&self.mobs[ia]) + } else { + kind_of(&self.mobs[ib]) + }; + let Some(id) = + self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true) + else { + return; + }; + self.mobs[ia].extra.age = 6000; + self.mobs[ib].extra.age = 6000; + if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) { + child.extra.variant = variant; + child.extra.variant2 = villager::NONE; + child.extra.age = -24000; + child.extra.bed = Some(bed); + } + self.particles_at("heart", [from.x, from.y + 1.8, from.z]); + } + /// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head. + fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> { + let claimed: Vec<[i32; 3]> = self + .mobs + .iter() + .filter(|m| m.species() == Species::Villager) + .filter_map(|m| m.extra.bed) + .collect(); + let mut known: HashMap = HashMap::new(); + let mut best: Option<(i32, [i32; 3])> = None; + for y in from[1] - 8..=from[1] + 8 { + for z in from[2] - 48..=from[2] + 48 { + for x in from[0] - 48..=from[0] + 48 { + let state = self.world.block(x, y, z); + if self.res.facts.is_air(state) { + continue; + } + let free_head = *known.entry(state.0).or_insert_with(|| { + self.res.facts.get(state).name.ends_with("_bed") + && self.res.assets.registry.state(state).is_some_and(|s| { + s.properties.get("part").map(String::as_str) == Some("head") + && s.properties.get("occupied").map(String::as_str) + != Some("true") + }) + }); + let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); + if free_head + && d <= 48 * 48 + && !claimed.contains(&[x, y, z]) + && best.is_none_or(|(b, _)| d < b) + { + best = Some((d, [x, y, z])); + } + } + } + } + best.map(|(_, p)| p) + } + fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) { + if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { + let options = horizon_client::particles::ParticleOptions::simple(ty); + self.particles.add(&options, at, [0.0; 3]); + } + } + + /// `Mob.aiStep` item pickup for villagers (`InventoryCarrier`): food, + /// seeds and what their profession wants, from within a block. + pub(super) fn villager_pickups(&mut self) { + if self.dropped.is_empty() || !self.ui.rules.bool("mob_griefing") { + return; + } + let picks_up = self + .res + .items + .item_tags + .get("minecraft:villager_picks_up") + .cloned(); + for i in 0..self.mobs.len() { + let m = &self.mobs[i]; + if m.species() != Species::Villager || !m.alive() { + continue; + } + let (pos, half) = (m.position, f64::from(m.width()) / 2.0 + 1.0); + let top = f64::from(m.height()); + let requested = villager::requested_items(m); + let mut j = 0; + while j < self.dropped.len() { + let e = &self.dropped[j]; + let near = (e.position.x - pos.x).abs() <= half + && (e.position.z - pos.z).abs() <= half + && e.position.y >= pos.y - 0.25 + && e.position.y <= pos.y + top; + let item = e.stack.item.clone(); + let wants = villager::food_points(&item) > 0 + || picks_up.as_ref().is_some_and(|t| t.contains(&*item)) + || requested.contains(&&*item); + if !near || e.pickup_delay > 0 || !wants { + j += 1; + continue; + } + let max = self.item_max_stack(&item); + let stack = self.dropped[j].stack.clone(); + if !villager::ext_mut(&mut self.mobs[i]).can_add(&stack, max) { + j += 1; + continue; + } + let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max); + match rest { + None => { + self.dropped.remove(j); + } + Some(rest) => { + self.dropped[j].stack.count = rest.count; + j += 1; + } + } + } + } + } + + /// `Villager.setLastHurtByMob` and `ServerLevel.onReputationEvent`: a hit + /// from the player counts against it with the villager that was hit. + pub(super) fn villager_reputation_tick(&mut self) { + let Some(uuid) = self.level.player_uuid else { + return; + }; + let mut angry = Vec::new(); + for m in &mut self.mobs { + if m.species() != Species::Villager + || m.ai.last_hurt_by != Some(horizon_client::mobs::Who::Player) + { + continue; + } + let time = m.ai.last_hurt_by_time; + let alive = m.alive(); + let at = m.position; + let e = villager::ext_mut(m); + if e.hurt_seen != time { + e.hurt_seen = time; + e.gossips.add( + uuid, + GossipType::MinorNegative, + gossip::REPUTATION_CHANGE_PER_EVENT, + ); + if alive { + angry.push(at); + } + } + } + for at in angry { + self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]); + } + } + /// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a + /// player kill one remember it as a major wrong. + pub(super) fn villager_murdered(&mut self, victim: &Mob, by_player: bool) { + if victim.species() != Species::Villager || !by_player { + return; + } + let Some(uuid) = self.level.player_uuid else { + return; + }; + let eye = Vec3::new(victim.position.x, victim.eye_y(), victim.position.z); + let witnesses: Vec = { + let w = self.mob_world_base(&[]); + self.mobs + .iter() + .enumerate() + .filter(|(_, m)| { + m.id != victim.id + && m.species() == Species::Villager + && m.alive() + && (m.position.x - victim.position.x).abs() <= 16.0 + && (m.position.y - victim.position.y).abs() <= 16.0 + && (m.position.z - victim.position.z).abs() <= 16.0 + && w.line_of_sight(eye, Vec3::new(m.position.x, m.eye_y(), m.position.z)) + }) + .map(|(i, _)| i) + .collect() + }; + for i in witnesses { + villager::ext_mut(&mut self.mobs[i]).gossips.add( + uuid, + GossipType::MajorNegative, + gossip::REPUTATION_CHANGE_PER_EVENT, + ); + } + } + /// `ReputationEventType.TRADE`: each trade earns a little trust. + pub(super) fn villager_traded(&mut self, id: u32) { + let Some(uuid) = self.level.player_uuid else { + return; + }; + let Some(i) = self.villager_index(id) else { + return; + }; + villager::ext_mut(&mut self.mobs[i]).gossips.add( + uuid, + GossipType::Trading, + gossip::REPUTATION_CHANGE_PER_TRADE, + ); + let p = self.mobs[i].position; + self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]); + } + /// `Villager.getPlayerReputation` of the local player. + pub(super) fn villager_reputation(&self, id: u32) -> i32 { + let Some(uuid) = self.level.player_uuid else { + return 0; + }; + self.villager_index(id) + .and_then(|i| villager::ext(&self.mobs[i])) + .map_or(0, |e| e.gossips.reputation(uuid)) + } + /// The Hero of the Village amplifier of the player, if any. + pub(super) fn hero_amplifier(&self) -> Option { + self.potions.effects.amplifier("hero_of_the_village") + } +} diff --git a/crates/horizon-client/src/gossip.rs b/crates/horizon-client/src/gossip.rs new file mode 100644 index 000000000..63cc7e265 --- /dev/null +++ b/crates/horizon-client/src/gossip.rs @@ -0,0 +1,386 @@ +//! Villager gossip (`GossipContainer` and `GossipType`): what a villager +//! remembers about each player, how it fades by the day, how it spreads from +//! villager to villager and the reputation it adds up to. +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::nbt::Tag; +use std::collections::BTreeMap; + +/// `ReputationEventType` amounts. +pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25; +pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20; +pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2; +/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten. +const DISCARD_THRESHOLD: i32 = 2; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum GossipType { + MajorNegative, + MinorNegative, + MinorPositive, + MajorPositive, + Trading, +} +impl GossipType { + pub const ALL: [Self; 5] = [ + Self::MajorNegative, + Self::MinorNegative, + Self::MinorPositive, + Self::MajorPositive, + Self::Trading, + ]; + pub fn id(self) -> &'static str { + match self { + Self::MajorNegative => "major_negative", + Self::MinorNegative => "minor_negative", + Self::MinorPositive => "minor_positive", + Self::MajorPositive => "major_positive", + Self::Trading => "trading", + } + } + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|t| t.id() == id) + } + fn index(self) -> usize { + self as usize + } + pub fn weight(self) -> i32 { + match self { + Self::MajorNegative => -5, + Self::MinorNegative => -1, + Self::MinorPositive => 1, + Self::MajorPositive => 5, + Self::Trading => 1, + } + } + pub fn max(self) -> i32 { + match self { + Self::MajorNegative => 100, + Self::MinorNegative => 200, + Self::MinorPositive | Self::Trading => 25, + Self::MajorPositive => 20, + } + } + pub fn decay_per_day(self) -> i32 { + match self { + Self::MajorNegative => 10, + Self::MinorNegative => 20, + Self::MinorPositive => 1, + Self::MajorPositive => 0, + Self::Trading => 2, + } + } + pub fn decay_per_transfer(self) -> i32 { + match self { + Self::MajorNegative => 10, + Self::MinorNegative => 20, + Self::MinorPositive => 5, + Self::MajorPositive | Self::Trading => 20, + } + } +} + +/// A UUID as four ints. +pub type Target = [i32; 4]; + +/// One gossip entry (`GossipContainer.GossipEntry`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Entry { + target: Target, + kind: GossipType, + value: i32, +} +impl Entry { + fn weighted(self) -> i32 { + self.value * self.kind.weight() + } +} + +/// `GossipContainer`: per target, the value of each gossip type (0: none). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Gossips { + map: BTreeMap, +} +impl Gossips { + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + pub fn len(&self) -> usize { + self.map.len() + } + pub fn clear(&mut self) { + self.map.clear(); + } + pub fn get(&self, target: Target, kind: GossipType) -> i32 { + self.map.get(&target).map_or(0, |e| e[kind.index()]) + } + /// `getReputation`: the weighted sum of every type for a target. + pub fn reputation(&self, target: Target) -> i32 { + self.map.get(&target).map_or(0, |e| { + GossipType::ALL + .into_iter() + .map(|t| e[t.index()] * t.weight()) + .sum() + }) + } + /// How many targets have a gossip of `kind` whose weighted value passes `test`. + pub fn count_for_type(&self, kind: GossipType, test: impl Fn(f64) -> bool) -> usize { + self.map + .values() + .filter(|e| test(f64::from(e[kind.index()] * kind.weight()))) + .count() + } + /// `add`: sums up to the type's maximum and forgets values below 2. + pub fn add(&mut self, target: Target, kind: GossipType, amount: i32) { + let entries = self.map.entry(target).or_insert([0; 5]); + let old = entries[kind.index()]; + entries[kind.index()] = if old == 0 { + amount + } else { + let sum = old + amount; + if sum > kind.max() { + kind.max().max(old) + } else { + sum + } + }; + let value = entries[kind.index()]; + if value > kind.max() { + entries[kind.index()] = kind.max(); + } + if value < DISCARD_THRESHOLD { + entries[kind.index()] = 0; + } + if entries.iter().all(|v| *v == 0) { + self.map.remove(&target); + } + } + pub fn remove(&mut self, target: Target, kind: GossipType) { + if let Some(e) = self.map.get_mut(&target) { + e[kind.index()] = 0; + if e.iter().all(|v| *v == 0) { + self.map.remove(&target); + } + } + } + /// `decay` (once per day): every type loses its daily amount. + pub fn decay(&mut self) { + self.map.retain(|_, e| { + for kind in GossipType::ALL { + let v = e[kind.index()]; + if v == 0 { + continue; + } + let next = v - kind.decay_per_day(); + e[kind.index()] = if next < DISCARD_THRESHOLD { 0 } else { next }; + } + e.iter().any(|v| *v != 0) + }); + } + fn unpack(&self) -> Vec { + let mut out = Vec::new(); + for (target, e) in &self.map { + for kind in GossipType::ALL { + if e[kind.index()] != 0 { + out.push(Entry { + target: *target, + kind, + value: e[kind.index()], + }); + } + } + } + out + } + /// `selectGossipsForTransfer`: `max_count` picks weighted by magnitude, + /// duplicates counted once. + fn select_for_transfer(&self, random: &mut LegacyRandom, max_count: usize) -> Vec { + let entries = self.unpack(); + if entries.is_empty() { + return Vec::new(); + } + let mut ends = Vec::with_capacity(entries.len()); + let mut total = 0; + for e in &entries { + total += e.weighted().abs(); + ends.push(total - 1); + } + let mut picked: Vec = Vec::new(); + for _ in 0..max_count { + let choice = random.next_int_bound(total).unwrap_or(0); + // Arrays.binarySearch on the strictly increasing range ends. + let index = match ends.binary_search(&choice) { + Ok(i) | Err(i) => i, + }; + if !picked.contains(&index) { + picked.push(index); + } + } + picked.into_iter().map(|i| entries[i]).collect() + } + /// `transferFrom`: gossip heard from another villager, weakened by the + /// retelling. Returns how many gossips were picked. + pub fn transfer_from( + &mut self, + source: &Gossips, + random: &mut LegacyRandom, + max_count: usize, + ) -> usize { + let picked = source.select_for_transfer(random, max_count); + for g in &picked { + let decayed = g.value - g.kind.decay_per_transfer(); + if decayed >= DISCARD_THRESHOLD { + let e = self.map.entry(g.target).or_insert([0; 5]); + let slot = &mut e[g.kind.index()]; + *slot = (*slot).max(decayed); + } + } + picked.len() + } + + pub fn to_nbt(&self) -> Tag { + Tag::List( + self.unpack() + .into_iter() + .map(|e| { + Tag::compound([ + ("Target", Tag::IntArray(e.target.to_vec())), + ("Type", Tag::String(e.kind.id().into())), + ("Value", Tag::Int(e.value)), + ]) + }) + .collect(), + ) + } + pub fn from_nbt(tag: &Tag) -> Self { + let mut out = Self::default(); + let Tag::List(list) = tag else { return out }; + for g in list { + let target = match g.get("Target") { + Some(Tag::IntArray(v)) if v.len() == 4 => [v[0], v[1], v[2], v[3]], + _ => continue, + }; + let kind = match g.get("Type") { + Some(Tag::String(s)) => GossipType::from_id(&s.to_string_lossy()), + _ => None, + }; + let value = match g.get("Value") { + Some(Tag::Int(v)) => *v, + _ => continue, + }; + if let Some(kind) = kind + && value > 0 + { + out.map.entry(target).or_insert([0; 5])[kind.index()] = value; + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PLAYER: Target = [1, 2, 3, 4]; + const OTHER: Target = [5, 6, 7, 8]; + + #[test] + fn reputation_adds_up_weighted() { + let mut g = Gossips::default(); + g.add(PLAYER, GossipType::MinorPositive, 25); + g.add(PLAYER, GossipType::MajorPositive, 20); + g.add(PLAYER, GossipType::Trading, 2); + // 25 + 20 * 5 + 2 + assert_eq!(g.reputation(PLAYER), 127); + g.add(PLAYER, GossipType::MajorNegative, 25); + assert_eq!(g.reputation(PLAYER), 127 - 125); + assert_eq!(g.reputation(OTHER), 0); + } + #[test] + fn values_stop_at_their_maximum() { + let mut g = Gossips::default(); + for _ in 0..10 { + g.add(PLAYER, GossipType::MajorNegative, 25); + } + assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 100); + // The minor negative cap is 200: eight hits of 25 fill it. + for _ in 0..12 { + g.add(PLAYER, GossipType::MinorNegative, 25); + } + assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 200); + assert_eq!(g.reputation(PLAYER), -500 - 200); + } + #[test] + fn small_values_are_forgotten() { + let mut g = Gossips::default(); + g.add(PLAYER, GossipType::Trading, 1); + assert!(g.is_empty()); + g.add(PLAYER, GossipType::Trading, 2); + assert_eq!(g.get(PLAYER, GossipType::Trading), 2); + g.remove(PLAYER, GossipType::Trading); + assert!(g.is_empty()); + } + #[test] + fn gossip_decays_by_the_day() { + let mut g = Gossips::default(); + g.add(PLAYER, GossipType::MajorNegative, 25); + g.add(PLAYER, GossipType::MinorNegative, 25); + g.add(PLAYER, GossipType::MinorPositive, 3); + g.add(PLAYER, GossipType::MajorPositive, 20); + g.decay(); + assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 15); + assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 5); + assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 2); + // Major positive gossip never fades. + assert_eq!(g.get(PLAYER, GossipType::MajorPositive), 20); + g.decay(); + assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 5); + assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 0); + assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 0); + g.decay(); + assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 0); + assert_eq!(g.len(), 1); + } + #[test] + fn retold_gossip_is_weaker() { + let mut source = Gossips::default(); + source.add(PLAYER, GossipType::MajorNegative, 25); + source.add(OTHER, GossipType::Trading, 25); + let mut heard = Gossips::default(); + let mut random = LegacyRandom::new(11); + let n = heard.transfer_from(&source, &mut random, 50); + assert!((1..=2).contains(&n)); + // 25 - 10 per transfer for major negative, 25 - 20 for trading. + let major = heard.get(PLAYER, GossipType::MajorNegative); + let trading = heard.get(OTHER, GossipType::Trading); + assert!(major == 0 || major == 15); + assert!(trading == 0 || trading == 5); + assert!(major + trading > 0); + // A second hearing keeps the stronger value. + heard.transfer_from(&source, &mut random, 50); + assert!(heard.get(PLAYER, GossipType::MajorNegative) <= 15); + // Gossip too weak to survive retelling is dropped. + let mut faint = Gossips::default(); + faint.add(PLAYER, GossipType::Trading, 5); + let mut heard = Gossips::default(); + heard.transfer_from(&faint, &mut random, 10); + assert!(heard.is_empty()); + } + #[test] + fn gossip_round_trips_through_nbt() { + let mut g = Gossips::default(); + g.add(PLAYER, GossipType::MajorNegative, 25); + g.add(PLAYER, GossipType::Trading, 2); + g.add(OTHER, GossipType::MinorPositive, 25); + assert_eq!(Gossips::from_nbt(&g.to_nbt()), g); + } + #[test] + fn counts_by_type() { + let mut g = Gossips::default(); + g.add(PLAYER, GossipType::MajorNegative, 25); + g.add(OTHER, GossipType::MajorNegative, 25); + g.add(OTHER, GossipType::Trading, 25); + assert_eq!(g.count_for_type(GossipType::MajorNegative, |v| v < 0.0), 2); + assert_eq!(g.count_for_type(GossipType::Trading, |v| v < 0.0), 0); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 714f49308..089f6fb82 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -30,6 +30,7 @@ pub mod fog; pub mod font; pub mod gamerules; pub mod gfx; +pub mod gossip; pub mod health; pub mod hud; pub mod hunger; diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index c6b0c9824..a3dde71a9 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -98,6 +98,23 @@ impl Trader { } } +/// `Villager.updateSpecialPrices`: the reputation and Hero of the Village +/// discounts of a player, from scratch. +pub fn update_special_prices(offers: &mut [MerchantOffer], reputation: i32, hero: Option) { + // 0.3F + 0.0625F * amplifier, widened from float. + let hero_modifier = hero.map_or(0.0, |a| f64::from(0.3f32 + 0.0625f32 * a as f32)); + for offer in offers { + offer.special_price_diff = 0; + if reputation != 0 { + offer.special_price_diff -= (reputation as f32 * offer.price_multiplier).floor() as i32; + } + if hero_modifier > 0.0 { + let reduction = + (hero_modifier * f64::from(offer.base_cost_a.stack.count)).floor() as i32; + offer.special_price_diff -= reduction.max(1); + } + } +} /// An `ItemCost`: item and count (component predicates are not used by the /// 26.3 trade data except for one exact match, kept as the stack's data). #[derive(Clone, Debug, PartialEq)] @@ -708,6 +725,32 @@ mod tests { assert!(!can_level_up(5)); } + #[test] + fn reputation_and_heroes_lower_prices() { + let items = items(); + let mut offers = vec![offer(10, None), offer(1, None)]; + // Reputation 50 with a 0.2 multiplier: 10 off, floored per offer. + update_special_prices(&mut offers, 50, None); + assert_eq!(offers[0].special_price_diff, -10); + assert_eq!(offers[0].cost_a_count(&items), 1); + assert_eq!(offers[1].special_price_diff, -10); + // Bad reputation raises the price (-30 * 0.2 = -6 floors to -6). + update_special_prices(&mut offers, -30, None); + assert_eq!(offers[0].special_price_diff, 6); + assert_eq!(offers[0].cost_a_count(&items), 16); + // Hero of the Village I: 0.3 * 10 = 3 off, at least 1. + update_special_prices(&mut offers, 0, Some(0)); + assert_eq!(offers[0].special_price_diff, -3); + assert_eq!(offers[1].special_price_diff, -1); + // Level III: 0.3 + 0.125 = 0.425 -> 4 off a ten emerald price. + update_special_prices(&mut offers, 0, Some(2)); + assert_eq!(offers[0].special_price_diff, -4); + // Both stack, from scratch each time. + update_special_prices(&mut offers, 25, Some(0)); + assert_eq!(offers[0].special_price_diff, -5 - 3); + update_special_prices(&mut offers, 0, None); + assert_eq!(offers[0].special_price_diff, 0); + } #[test] fn offers_follow_the_trade_data() { let items = items(); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index fa4da287e..9261846a1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -665,6 +665,21 @@ pub enum MobEvent { kind: DamageKind, amount: f32, }, + /// Two villagers are close: swap gossip and share food and wares. + VillagerMeet { + mob: u32, + other: u32, + }, + /// Two villagers make a baby. + VillagerBirth { + parent: u32, + partner: u32, + }, + /// A villager asks whether enough neighbours want an iron golem. + GolemCheck { + mob: u32, + needed: usize, + }, /// A villager launches a firework rocket (celebrating a won raid). Firework { at: [f64; 3], @@ -745,6 +760,8 @@ pub struct Seen { pub bed: Option<[i32; 3]>, /// A raider in an active raid. pub active_raid: bool, + /// A villager's reputation of the player (`getPlayerReputation`). + pub player_rep: i32, } /// The player as mobs see it. #[derive(Clone, Debug)] @@ -769,6 +786,8 @@ pub struct PlayerView { pub last_hurt: Option<(Who, i64)>, /// The Hero of the Village effect. pub hero: bool, + /// The player's UUID (villagers' gossip is keyed by it). + pub uuid: [i32; 4], } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index 4993c4764..d12f26788 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -36,6 +36,7 @@ pub fn register_iron(m: &mut Mob) { ); g.add(7, LookAtPlayer::new(6.0)); g.add(8, RandomLookAround::default()); + m.ai.targets.add(1, DefendVillage); m.ai.targets.add(2, HurtByTarget::new()); m.ai.targets.add( 3, @@ -48,6 +49,48 @@ pub fn register_iron(m: &mut Mob) { NearestTarget::new(Prey::Filter(golem_prey), false).interval(5), ); } +/// `DefendVillageTargetGoal`: a player that a villager nearby has no +/// good word for (reputation of -100 or worse) is attacked on sight. +#[derive(Clone, Debug)] +struct DefendVillage; +impl Goal for DefendVillage { + goal_clone!(); + fn flags(&self) -> u8 { + super::goals::TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = &cx.w.player else { return false }; + if !p.alive || p.creative || p.spectator { + return false; + } + // The box around the golem: 10 across, 8 up and down. + let b = m.bounds().inflate(Vec3::new(10.0, 8.0, 10.0)); + if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 { + return false; + } + let bad = cx.w.others.iter().any(|s| { + s.species == Species::Villager + && s.alive + && s.player_rep <= -100 + && b.contains(s.position) + && s.position.distance_squared(m.position) <= 64.0 * 64.0 + }); + bad && m.sees(cx.w, Who::Player) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.target_info(cx.w).is_some_and(|t| { + t.alive + && !(t.is_player && t.creative) + && m.position.distance_squared(t.position) <= 64.0 * 64.0 + }) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.ai.target = Some(Who::Player); + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.ai.target = None; + } +} /// `MoveTowardsTargetGoal`: close in on a target within range. #[derive(Clone, Debug)] struct MoveTowardsTarget { diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 5ed95eb3a..82e7645bd 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -12,6 +12,7 @@ use super::{ Stroll, goal_clone, }, }; +use crate::items::ItemStack; use horizon_core::random::RandomSource; use std::{collections::HashMap, f32::consts::PI}; @@ -75,6 +76,8 @@ pub fn register(m: &mut Mob) { ); g.add(1, Panic::new(0.75)); g.add(2, RaidBehavior::default()); + g.add(3, Social::default()); + g.add(0, GolemCall); g.add(3, GiftToHero::default()); g.add(3, JobSite::default()); g.add(3, AcquireHome::default()); @@ -458,6 +461,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) { _ => 4, }; m.nav_stop(); + ext_mut(m).last_slept = Some(w.game_time); m.velocity = horizon_core::geometry::Vec3::ZERO; m.position = horizon_core::geometry::Vec3::new( f64::from(p[0]) + 0.5, @@ -518,6 +522,23 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { if m.extra.ints[0] > 0 { m.extra.ints[0] -= 1; } + if m.species() == Species::Villager { + let now = w.game_time; + let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0 + && w.others.iter().any(|s| { + s.species == Species::IronGolem + && s.alive + && (s.position.x - m.position.x).abs() <= 16.0 + && (s.position.y - m.position.y).abs() <= 16.0 + && (s.position.z - m.position.z).abs() <= 16.0 + }); + let e = ext_mut(m); + // Villager.maybeDecayGossip and the GolemSensor (every 200 ticks). + e.maybe_decay(now); + if seen_golem { + e.golem_until = now + 599; + } + } // WakeUp / LivingEntity.hurt: morning, a hit or a missing bed. if sleeping(m) { let bed_gone = m @@ -612,6 +633,20 @@ pub const RAID_VICTORY: u8 = 3; pub struct Ext { /// Which raid package the villager follows. pub raid: u8, + /// What the villager remembers of players (`gossips`). + pub gossips: crate::gossip::Gossips, + pub last_gossip_time: i64, + pub last_gossip_decay: i64, + /// `foodLevel`: eaten but not yet digested, in food points. + pub food_level: i32, + /// The eight-slot inventory (`InventoryCarrier`). + pub inventory: Vec, + /// `LAST_SLEPT` memory. + pub last_slept: Option, + /// `GOLEM_DETECTED_RECENTLY` expires at this game time. + pub golem_until: i64, + /// The `last_hurt_by_time` of the player's hit already counted. + pub hurt_seen: i32, } pub fn ext(m: &Mob) -> Option<&Ext> { m.extra.villager.as_deref() @@ -809,3 +844,532 @@ impl Goal for GiftToHero { } } } + +// ---- Gossip, food, breeding and golems. + +/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`). +pub fn food_points(item: &str) -> i32 { + match item { + "minecraft:bread" => 4, + "minecraft:potato" | "minecraft:carrot" | "minecraft:beetroot" => 1, + _ => 0, + } +} +/// The farmer's `requestedItems`. +pub fn farmer_items() -> &'static [&'static str] { + &[ + "minecraft:bread", + "minecraft:potato", + "minecraft:carrot", + "minecraft:wheat", + "minecraft:wheat_seeds", + "minecraft:beetroot", + "minecraft:beetroot_seeds", + "minecraft:torchflower_seeds", + "minecraft:pitcher_pod", + ] +} +/// A villager's `requestedItems` by profession. +pub fn requested_items(m: &Mob) -> &'static [&'static str] { + if super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" { + farmer_items() + } else { + &[] + } +} +pub fn is_farmer(m: &Mob) -> bool { + super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" +} +/// `SimpleContainer(8)`: stacks the villager carries. +const INVENTORY_SLOTS: usize = 8; + +impl Ext { + /// `countFoodPointsInInventory`. + pub fn food_in_inventory(&self) -> i32 { + self.inventory + .iter() + .map(|s| food_points(&s.item) * s.count as i32) + .sum() + } + /// `hasExcessFood` and `wantsMoreFood`. + pub fn has_excess_food(&self) -> bool { + self.food_in_inventory() >= 24 + } + pub fn wants_more_food(&self) -> bool { + self.food_in_inventory() < 12 + } + fn hungry(&self) -> bool { + self.food_level < 12 + } + /// `Villager.eatAndDigestFood`: eat until full, then digest 12 points. + pub fn eat_and_digest(&mut self) { + if self.hungry() { + let mut slot = 0; + while slot < self.inventory.len() && self.hungry() { + let points = food_points(&self.inventory[slot].item); + if points > 0 { + while self.inventory[slot].count > 0 && self.hungry() { + self.food_level += points; + self.inventory[slot].count -= 1; + } + if self.inventory[slot].count == 0 { + self.inventory.remove(slot); + continue; + } + } + slot += 1; + } + } + self.food_level -= 12; + } + /// Whether the stack fits (`SimpleContainer.canAddItem`). + pub fn can_add(&self, stack: &ItemStack, max_stack: u32) -> bool { + self.inventory.len() < INVENTORY_SLOTS + || self + .inventory + .iter() + .any(|s| s.same_item_same_components(stack) && s.count < max_stack) + } + /// `SimpleContainer.addItem`: merge into stacks, then free slots; the + /// part that did not fit is returned. + pub fn add_item(&mut self, mut stack: ItemStack, max_stack: u32) -> Option { + for s in &mut self.inventory { + if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max_stack { + let n = (max_stack - s.count).min(stack.count); + s.count += n; + stack.count -= n; + } + } + while stack.count > 0 && self.inventory.len() < INVENTORY_SLOTS { + let n = stack.count.min(max_stack); + self.inventory.push(ItemStack { + count: n, + ..stack.clone() + }); + stack.count -= n; + } + (stack.count > 0).then_some(stack) + } + pub fn count_item(&self, item: &str) -> u32 { + self.inventory + .iter() + .filter(|s| &*s.item == item) + .map(|s| s.count) + .sum() + } + /// `TradeWithVillager.throwHalfStack`: the half of a big matching stack + /// (or whatever is over 24) leaves the inventory. + pub fn take_half_stack( + &mut self, + wanted: impl Fn(&ItemStack) -> bool, + max_stack: impl Fn(&str) -> u32, + ) -> Option { + for i in 0..self.inventory.len() { + let s = &self.inventory[i]; + if s.count == 0 || !wanted(s) { + continue; + } + let count = if s.count > max_stack(&s.item) / 2 { + s.count / 2 + } else if s.count > 24 { + s.count - 24 + } else { + continue; + }; + let taken = ItemStack { count, ..s.clone() }; + self.inventory[i].count -= count; + if self.inventory[i].count == 0 { + self.inventory.remove(i); + } + return Some(taken); + } + None + } + /// `Villager.wantsToSpawnGolem`: slept within the last day and no golem + /// seen lately. + pub fn wants_golem(&self, now: i64) -> bool { + self.last_slept.is_some_and(|t| now - t < 24000) && now >= self.golem_until + } + /// `maybeDecayGossip`: once a day. + pub fn maybe_decay(&mut self, now: i64) { + if self.last_gossip_decay == 0 { + self.last_gossip_decay = now; + } else if now >= self.last_gossip_decay + 24000 { + self.gossips.decay(); + self.last_gossip_decay = now; + } + } + /// `Villager.gossip` timing: hearing again waits 1200 ticks. + pub fn can_gossip(&self, now: i64) -> bool { + now < self.last_gossip_time || now >= self.last_gossip_time + 1200 + } +} +/// `Villager.canBreed`: enough food, awake and an adult. +pub fn can_breed(m: &Mob) -> bool { + m.species() == Species::Villager + && m.extra.age == 0 + && !sleeping(m) + && ext(m).map_or(0, |e| e.food_level + e.food_in_inventory()) >= 12 +} + +/// The saved fields (`FoodLevel`, `Gossips`, `LastGossipDecay`, `Inventory` +/// and the sleep and golem memories). +pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { + use horizon_world::nbt::Tag; + let Some(e) = ext(m) else { return }; + map.insert( + "FoodLevel".into(), + Tag::Byte(e.food_level.clamp(-128, 127) as i8), + ); + map.insert("Gossips".into(), e.gossips.to_nbt()); + map.insert("LastGossipDecay".into(), Tag::Long(e.last_gossip_decay)); + map.insert( + "Inventory".into(), + Tag::List(e.inventory.iter().map(crate::save::item_to_nbt).collect()), + ); +} +/// The memories of `Brain.memories` the villager keeps besides positions. +pub fn write_memories(m: &Mob, memories: &mut Vec<(&'static str, horizon_world::nbt::Tag)>) { + use horizon_world::nbt::Tag; + let Some(e) = ext(m) else { return }; + if let Some(t) = e.last_slept { + memories.push(( + "minecraft:last_slept", + Tag::compound([("value", Tag::Long(t))]), + )); + } +} +pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) { + use horizon_world::nbt::Tag; + let int = |t: Option<&Tag>| match t { + Some(Tag::Int(v)) => Some(i64::from(*v)), + Some(Tag::Byte(v)) => Some(i64::from(*v)), + Some(Tag::Short(v)) => Some(i64::from(*v)), + Some(Tag::Long(v)) => Some(*v), + _ => None, + }; + let last_slept = int(tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|b| b.get("minecraft:last_slept")) + .and_then(|j| j.get("value"))); + let e = ext_mut(m); + e.food_level = int(tag.get("FoodLevel")).unwrap_or(0) as i32; + e.gossips = tag + .get("Gossips") + .map(crate::gossip::Gossips::from_nbt) + .unwrap_or_default(); + e.last_gossip_decay = int(tag.get("LastGossipDecay")).unwrap_or(0); + e.last_slept = last_slept; + if let Some(Tag::List(items)) = tag.get("Inventory") { + e.inventory = items + .iter() + .filter_map(crate::save::item_from_nbt) + .take(INVENTORY_SLOTS) + .collect(); + } +} + +/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while +/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap +/// gossip and food, and make a baby with a willing partner. +#[derive(Clone, Debug, Default)] +struct Social { + target: Option, + breed: bool, + ticks: i32, + cooldown: i32, + birth_at: i64, +} +impl Social { + fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let breedable = can_breed(m); + let id = m.id; + let nearest = + cx.w.nearby(m.position, 8.0, move |s| { + s.species == Species::Villager && s.id != id + }) + .filter(|s| m.position.distance_squared(s.position) <= 64.0) + .map(|s| (s.id, s.in_love)) + .collect::>(); + let visible: Vec<(u32, bool)> = nearest + .into_iter() + .filter(|(i, _)| m.sees(cx.w, Who::Mob(*i))) + .collect(); + let Some(&(target, partner_willing)) = visible.first() else { + return false; + }; + // RunOne weights: interact 2, breed 1 (when both are willing). + let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0; + self.target = Some(target); + self.breed = breed; + true + } +} +impl Goal for Social { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE { + return false; + } + if self.cooldown > 0 { + self.cooldown -= 1; + return false; + } + match activity(m, cx.w.day_time) { + Activity::Idle => self.pick(m, cx), + Activity::Meet => { + // SocializeAtBell: one tick in a hundred, near the bell. + let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0); + near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && { + let ok = self.pick(m, cx); + self.breed = false; + ok + } + } + _ => false, + } + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(t) = self.target else { return false }; + let Some(s) = cx.w.seen(t) else { return false }; + if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE { + return false; + } + if self.breed { + self.ticks < 350 && can_breed(m) && s.in_love + } else { + self.ticks < 60 + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.ticks = 0; + self.birth_at = 0; + if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) { + let at = [s.position.x, s.position.y, s.position.z]; + m.nav_move_to(cx.w, at, 0.5); + } + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.nav_stop(); + self.target = None; + self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.ticks += 1; + let Some(t) = self.target else { return }; + let Some(s) = cx.w.seen(t) else { return }; + let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y); + m.look_at([at[0], eye, at[2]]); + if m.position.distance_squared(s.position) > 5.0 { + if m.ai.nav.is_done() && self.ticks % 10 == 1 { + m.nav_move_to(cx.w, at, 0.5); + } + return; + } + m.nav_stop(); + if !self.breed { + cx.events.push(MobEvent::VillagerMeet { + mob: m.id, + other: t, + }); + return; + } + let now = cx.w.game_time; + if self.birth_at == 0 { + self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); + } + if now >= self.birth_at { + cx.events.push(MobEvent::VillagerBirth { + parent: m.id, + partner: t, + }); + self.ticks = 1000; + } else if m.random.next_int_bound(35).unwrap_or(1) == 0 { + for p in [m.position, s.position] { + cx.events.push(MobEvent::Particles { + kind: "heart", + at: [p.x, p.y + 1.8, p.z], + count: 1, + }); + } + } + } +} + +/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem +/// every five seconds. +#[derive(Clone, Debug, Default)] +struct GolemCall; +/// `VillagerHostilesSensor`: how close each hostile must be to scare. +fn hostile_range(s: Species) -> f64 { + match s { + Species::Drowned + | Species::Husk + | Species::Vex + | Species::Zombie + | Species::ZombieVillager => 8.0, + Species::Evoker | Species::Ravager => 12.0, + Species::Pillager => 15.0, + Species::Vindicator | Species::Zoglin => 10.0, + _ => 0.0, + } +} +fn frightened(m: &Mob, cx: &Cx) -> bool { + // HURT_BY lasts 100 ticks. + let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100; + hurt || cx.w.others.iter().any(|s| { + s.alive && { + let r = hostile_range(s.species); + r > 0.0 && s.position.distance_squared(m.position) <= r * r + } + }) +} +impl Goal for GolemCall { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !m.is_baby() && frightened(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if cx.w.game_time % 100 == 0 { + cx.events.push(MobEvent::GolemCheck { + mob: m.id, + needed: 3, + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stack(item: &str, count: u32) -> ItemStack { + ItemStack::new(item, count) + } + #[test] + fn eating_fills_the_food_level_then_digests() { + let mut e = Ext { + inventory: vec![stack("minecraft:bread", 3), stack("minecraft:carrot", 5)], + ..Default::default() + }; + assert_eq!(e.food_in_inventory(), 17); + // Hungry below 12: three breads fill it exactly, then 12 digest away. + e.eat_and_digest(); + assert_eq!(e.food_level, 0); + assert_eq!(e.inventory.len(), 1); + assert_eq!(e.inventory[0].count, 5); + // Five carrots are not enough to be full again, and are all eaten. + e.eat_and_digest(); + assert_eq!(e.food_level, 5 - 12); + assert!(e.inventory.is_empty()); + } + #[test] + fn willingness_to_breed_needs_twelve_food_points() { + let mut e = Ext::default(); + assert!(e.wants_more_food() && !e.has_excess_food()); + e.inventory.push(stack("minecraft:bread", 6)); + assert!(e.has_excess_food() && !e.wants_more_food()); + e.food_level = -5; + assert_eq!(e.food_level + e.food_in_inventory(), 19); + } + #[test] + fn the_inventory_has_eight_stacking_slots() { + let mut e = Ext::default(); + assert!(e.add_item(stack("minecraft:bread", 100), 64).is_none()); + assert_eq!(e.inventory.len(), 2); + assert_eq!(e.inventory[0].count, 64); + for i in 0..6 { + assert!( + e.add_item(stack(&format!("minecraft:item_{i}"), 1), 64) + .is_none() + ); + } + assert_eq!(e.inventory.len(), 8); + // Full: another kind is refused, the same kind tops up the stack. + assert!(!e.can_add(&stack("minecraft:stick", 1), 64)); + let left = e.add_item(stack("minecraft:bread", 40), 64).unwrap(); + assert_eq!(left.count, 40 - 28); + } + #[test] + fn half_stacks_are_thrown() { + let mut e = Ext { + inventory: vec![ + stack("minecraft:bread", 10), + stack("minecraft:wheat", 50), + stack("minecraft:wheat", 20), + ], + ..Default::default() + }; + let max = |_: &str| 64; + // Bread is under half a stack and under 24: nothing. + assert!( + e.take_half_stack(|s| &*s.item == "minecraft:bread", max) + .is_none() + ); + // 50 wheat is over half a stack: 25 go. + let t = e + .take_half_stack(|s| &*s.item == "minecraft:wheat", max) + .unwrap(); + assert_eq!(t.count, 25); + assert_eq!(e.count_item("minecraft:wheat"), 25 + 20); + } + #[test] + fn golems_need_sleep_and_no_golem_nearby() { + let mut e = Ext::default(); + assert!(!e.wants_golem(100)); + e.last_slept = Some(0); + assert!(e.wants_golem(23_999)); + assert!(!e.wants_golem(24_000)); + e.last_slept = Some(1000); + e.golem_until = 2000 + 599; + assert!(!e.wants_golem(2500)); + assert!(e.wants_golem(2700)); + } + #[test] + fn gossip_decays_once_a_day_and_heard_gossip_waits() { + let player = [1, 2, 3, 4]; + let mut e = Ext::default(); + e.gossips + .add(player, crate::gossip::GossipType::MajorNegative, 25); + e.maybe_decay(100); + assert_eq!(e.last_gossip_decay, 100); + e.maybe_decay(24_099); + assert_eq!( + e.gossips + .get(player, crate::gossip::GossipType::MajorNegative), + 25 + ); + e.maybe_decay(24_100); + assert_eq!( + e.gossips + .get(player, crate::gossip::GossipType::MajorNegative), + 15 + ); + e.last_gossip_time = 5000; + assert!(!e.can_gossip(5100)); + assert!(e.can_gossip(6200)); + assert!(e.can_gossip(4000)); + } + #[test] + fn villager_food_values() { + assert_eq!(food_points("minecraft:bread"), 4); + assert_eq!(food_points("minecraft:beetroot"), 1); + assert_eq!(food_points("minecraft:apple"), 0); + } +} diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index be1efb6b3..63b835f3d 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -59,11 +59,18 @@ pub fn block_entities( .iter_mut() .zip(loot.fill(&table, seed, 27, Some(biome))) { - *slot = stack.map(|s| ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, + *slot = stack.map(|s| { + let mut item = ItemStack { + item: Arc::from(s.item.as_str()), + count: s.count.max(0) as u32, + damage: s.damage.max(0) as u32, + extra: None, + }; + // An ominous bottle's level (the default, 0, is no component). + if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { + item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); + } + item }); } } diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index 93fd2c75f..d36b00a79 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -23,6 +23,8 @@ pub struct LootStack { pub potion: Option, /// Set by exploration_map (the map_id component of a found map). pub map: bool, + /// Set by set_ominous_bottle_amplifier. + pub ominous_amplifier: Option, } impl LootStack { fn new(item: &str) -> Self { @@ -33,6 +35,7 @@ impl LootStack { enchantments: Vec::new(), potion: None, map: false, + ominous_amplifier: None, } } pub fn is_empty(&self) -> bool { @@ -584,7 +587,7 @@ impl Context<'_> { } } "minecraft:set_ominous_bottle_amplifier" => { - self.int(&f["amplifier"]); + stack.ominous_amplifier = Some(self.int(&f["amplifier"])); } "minecraft:set_instrument" => { let options = data.holder_set("instrument", &f["options"]); From 2b618b1dfefa62e4cb4f19645c6d14184385f44d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:18:31 +0200 Subject: [PATCH 7/7] Let witches heal raiders and name the ominous banner During a raid a witch looks for the other raiders, throws them Regeneration, or Healing once they are almost dead, and the potion cloud heals every raider it reaches. The ominous banner shows its own name and uncommon rarity in tooltips. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/creatures.rs | 26 ++++++++++++++++++ crates/horizon-client/src/game/stations.rs | 7 +++++ crates/horizon-client/src/mobs/witch.rs | 30 ++++++++++++++++++++- 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f7068662e..59145f16c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1636,6 +1636,32 @@ impl Game<'_> { } } } + // A witch's healing potions reach the raiders around the splash. + if matches!( + *effect, + "minecraft:instant_health" | "minecraft:regeneration" + ) { + let center = at; + for m in &mut self.mobs { + let d2 = m.position.distance_squared(center); + if !m.alive() + || d2 >= 16.0 + || !horizon_client::mobs::raider::is_raider(m.species()) + { + continue; + } + let scale = 1.0 - d2.sqrt() / 4.0; + if *effect == "minecraft:instant_health" { + let heal = (4 << *amplifier) as f64 * scale; + m.health = (m.health + heal as f32).min(m.attrs.max_health); + } else { + let t = (f64::from(*ticks) * scale + 0.5) as i32; + if t > 20 { + m.add_effect(effect, t, *amplifier); + } + } + } + } self.audio.play( "minecraft:entity.splash_potion.break", Some(atp), diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index eb6f8c24d..215dc7b91 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1725,6 +1725,10 @@ impl Game<'_> { let e: &Enchantments = &self.res.stations.enchantments; let props = e.props(&stack.item); let mut rarity = props.map_or("common", |p| p.rarity.as_str()); + // The ominous banner's rarity component. + if stack.data().is_some_and(|d| d.ominous_banner) { + rarity = "uncommon"; + } if !stack.enchantments().is_empty() { rarity = match rarity { "common" | "uncommon" => "rare", @@ -1740,6 +1744,9 @@ impl Game<'_> { }; let name = if let Some(n) = stack.custom_name() { n.to_owned() + } else if stack.data().is_some_and(|d| d.ominous_banner) { + e.translate("block.minecraft.ominous_banner") + .map_or_else(|| "Ominous Banner".to_owned(), str::to_owned) } else if stack.data().and_then(|d| d.potion.as_ref()).is_some() || stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 59b4ecff7..9fc0b0171 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -19,6 +19,18 @@ pub fn register(m: &mut Mob) { g.add(3, LookAtPlayer::new(8.0)); g.add(3, RandomLookAround::default()); m.ai.targets.add(1, HurtByTarget::new()); + // NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders. + m.ai.targets.add( + 2, + NearestTarget::new( + super::goals::Prey::Filter(|s| { + super::raider::is_raider(s.species) && s.species != Species::Witch + }), + true, + ) + .interval(1) + .when(|m, _| super::raider::has_active_raid(m)), + ); m.ai.targets .add(3, NearestTarget::player(true).interval(10)); } @@ -129,7 +141,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { }) .map_or(20.0, |s| s.health) }; - let (effect, ticks, amplifier) = if dist >= 8.0 { + // A raider target is healed instead: Healing when nearly dead, else + // Regeneration, and the witch drops the target afterwards. + let heals = match who { + Who::Mob(id) => { + cx.w.seen(id) + .is_some_and(|s| super::raider::is_raider(s.species)) + } + Who::Player => false, + }; + let (effect, ticks, amplifier) = if heals { + m.ai.target = None; + if health <= 4.0 { + ("minecraft:instant_health", 1, 0) + } else { + ("minecraft:regeneration", 900, 0) + } + } else if dist >= 8.0 { ("minecraft:slowness", 1800, 0) } else if health >= 8.0 { ("minecraft:poison", 900, 0)