From 2f74209da1869be4af8fca352fc6892c43932449 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:39:26 +0200 Subject: [PATCH] Port vanilla mob AI framework: goals, A* pathfinding, controls, projectiles Mobs now run vanilla's tick order with a GoalSelector/target selector (priorities, MOVE/LOOK/JUMP/TARGET flags), PathNavigation over the walk/swim/fly/amphibious node evaluators, Move/Look/Jump/BodyRotation controls and LivingEntity travel in air, water and lava. Path types, spawn surfaces and keyframe animations come from a new exporter (VanillaMobDataExporter -> mob-data.json). Farm animals, zombies, skeletons, creepers and spiders get their vanilla goals; projectiles (arrows, snowballs, eggs, ender pearls, fireballs) share one system; natural spawning follows NaturalSpawner with category caps. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 297 +-- crates/horizon-client/src/game/control.rs | 37 + crates/horizon-client/src/game/creatures.rs | 1635 ++++++++++++++++ crates/horizon-client/src/items.rs | 28 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 893 ++++----- crates/horizon-client/src/mobs/ai.rs | 552 ++++++ crates/horizon-client/src/mobs/anim.rs | 453 +++++ crates/horizon-client/src/mobs/control.rs | 400 ++++ crates/horizon-client/src/mobs/data.rs | 177 ++ crates/horizon-client/src/mobs/farm.rs | 127 ++ crates/horizon-client/src/mobs/goals.rs | 1638 +++++++++++++++++ crates/horizon-client/src/mobs/hostile.rs | 173 ++ crates/horizon-client/src/mobs/keyframes.rs | 228 +++ crates/horizon-client/src/mobs/living.rs | 450 +++++ crates/horizon-client/src/mobs/nav.rs | 587 ++++++ crates/horizon-client/src/mobs/path.rs | 1385 ++++++++++++++ crates/horizon-client/src/mobs/render.rs | 507 +++++ crates/horizon-client/src/mobs/spawning.rs | 227 +++ crates/horizon-client/src/mobs/species.rs | 1253 +++++++++++++ crates/horizon-client/src/mobs/undead.rs | 384 ++++ crates/horizon-client/src/mobs/world.rs | 145 ++ crates/horizon-client/src/projectiles.rs | 408 ++++ .../parity/VanillaMobDataExporter.java | 197 ++ tools/prepare_native_client.py | 17 + 25 files changed, 11505 insertions(+), 694 deletions(-) create mode 100644 crates/horizon-client/src/game/creatures.rs create mode 100644 crates/horizon-client/src/mobs/ai.rs create mode 100644 crates/horizon-client/src/mobs/anim.rs create mode 100644 crates/horizon-client/src/mobs/control.rs create mode 100644 crates/horizon-client/src/mobs/data.rs create mode 100644 crates/horizon-client/src/mobs/farm.rs create mode 100644 crates/horizon-client/src/mobs/goals.rs create mode 100644 crates/horizon-client/src/mobs/hostile.rs create mode 100644 crates/horizon-client/src/mobs/keyframes.rs create mode 100644 crates/horizon-client/src/mobs/living.rs create mode 100644 crates/horizon-client/src/mobs/nav.rs create mode 100644 crates/horizon-client/src/mobs/path.rs create mode 100644 crates/horizon-client/src/mobs/render.rs create mode 100644 crates/horizon-client/src/mobs/spawning.rs create mode 100644 crates/horizon-client/src/mobs/species.rs create mode 100644 crates/horizon-client/src/mobs/undead.rs create mode 100644 crates/horizon-client/src/mobs/world.rs create mode 100644 crates/horizon-client/src/projectiles.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobDataExporter.java diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..35ea084a5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,6 +1,7 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. mod control; +mod creatures; use horizon_client::{ Result, assets::Assets, @@ -9,8 +10,8 @@ use horizon_client::{ blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, clock::FixedStep, - entities::{Arrow, ArrowHit, Experience, ExperienceOrb, ItemEntity}, - mobs::{Mob, MobEvent, MobType, MobTypes, MobWorld}, + entities::{Arrow, Experience, ExperienceOrb, ItemEntity}, + mobs::{Mob, MobType, MobTypes}, particles::Particle, containers::{BlockEntity, Providers}, creative::{Creative, Names}, @@ -275,6 +276,7 @@ pub struct Resources { icons: HashMap>, layer_names: HashMap, mob_types: HashMap>, + mob_data: horizon_client::mobs::MobData, providers: Providers, chest_model: Option, nether_environment: Environment, @@ -343,6 +345,7 @@ struct Game<'a> { spawn_search: u32, mobs: Vec, arrows: Vec, + creatures: creatures::Creatures, attack_ticks: u32, last_hurt_by_player: HashSet, chest_open: HashMap<(i32, i32, i32), (f32, f32)>, @@ -935,6 +938,9 @@ impl Game<'_> { Ok(()) } fn use_item(&mut self) -> Result<()> { + if self.interact_mob()? { + return Ok(()); + } let sneaking = self.keys.contains(&KeyCode::ShiftLeft); // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. if !(sneaking && self.held().is_some()) @@ -965,6 +971,9 @@ impl Game<'_> { } let Some(stack) = self.held().cloned() else { return Ok(()) }; let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) }; + if self.throw_item(&stack)? { + return Ok(()); + } if &*stack.item == "minecraft:bow" { if self.using.is_none() { self.using = Some((self.selected, 0)); @@ -2078,17 +2087,8 @@ impl Game<'_> { } } } - // Mobs. - for mob in &self.mobs { - let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; - if d.length_squared() > 128.0 * 128.0 { - continue; - } - let Some(r) = self.res.atlas.sprites.get(&mob.kind.texture).copied() else { continue }; - let light = self.world.light(mob.position.x.floor() as i32, (mob.position.y + mob.kind.eye_height).floor() as i32, mob.position.z.floor() as i32); - let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; - horizon_client::mobs::render(mob, alpha as f32, camera, [r.u0, r.v0, r.u1, r.v1], packed, &mut out); - } + // Mobs and their projectiles. + self.mob_geometry(camera, alpha, &mut out); // Arrows: two crossed quads along the flight direction. if let Some(r) = self.res.atlas.sprites.get("entity/projectiles/arrow").copied() { for a in &self.arrows { @@ -2277,106 +2277,6 @@ impl Game<'_> { // Level.updateSkyBrightness: darkening from the sky light level. (15.0 - 15.0 * sky.sky_light_level).round() as i32 } - fn weighted<'b>(&mut self, entries: &'b [horizon_client::biome::SpawnEntry]) -> Option<&'b horizon_client::biome::SpawnEntry> { - let supported: Vec<&horizon_client::biome::SpawnEntry> = - entries.iter().filter(|e| self.res.mob_types.contains_key(&e.entity)).collect(); - let total: u32 = supported.iter().map(|e| e.weight).sum(); - if total == 0 { - return None; - } - let mut r = self.world.random.next_int_bound(total as i32).ok()? as u32; - supported.into_iter().find(|e| { - if r < e.weight { - true - } else { - r -= e.weight; - false - } - }) - } - fn add_mob(&mut self, kind: &str, x: f64, y: f64, z: f64, persistent: bool) { - let Some(t) = self.res.mob_types.get(kind).cloned() else { return }; - self.next_entity += 1; - let yaw = self.world.random.next_float() * 360.0; - let mut mob = Mob::new(self.next_entity, t, Vec3::new(x, y, z), yaw); - mob.persistent = persistent; - self.mobs.push(mob); - } - /// NaturalSpawner.spawnMobsForChunkGeneration for the creature category. - fn spawn_chunk_creatures(&mut self, cx: i32, cz: i32) { - let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { return }; - let biome = self.res.biomes.get(chunk.biome(8, 64, 8)).clone(); - let Some(entries) = biome.spawns.get("creature").cloned() else { return }; - while self.world.random.next_float() < biome.creature_probability { - let Some(entry) = self.weighted(&entries).cloned() else { return }; - let count = entry.min + self.world.random.next_int_bound((entry.max - entry.min + 1) as i32).unwrap_or(0) as u32; - let mut x = cx * 16 + self.world.random.next_int_bound(16).unwrap_or(0); - let mut z = cz * 16 + self.world.random.next_int_bound(16).unwrap_or(0); - for _ in 0..count { - if let Some(y) = self.land_column(x, z) { - let below = self.world.block(x, y - 1, z); - if self.res.facts.get(below).name.contains("grass") { - self.add_mob(&entry.entity, f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5, true); - } - } - x = (x + self.world.random.next_int_bound(5).unwrap_or(0) - self.world.random.next_int_bound(5).unwrap_or(0)).clamp(cx * 16, cx * 16 + 15); - z = (z + self.world.random.next_int_bound(5).unwrap_or(0) - self.world.random.next_int_bound(5).unwrap_or(0)).clamp(cz * 16, cz * 16 + 15); - } - } - } - /// NaturalSpawner.spawnCategoryForPosition for monsters near the player. - fn spawn_monsters(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { return }; - if self.creative && false { - return; - } - let monsters = self.mobs.iter().filter(|m| m.hostile()).count(); - if monsters >= 70 { - return; - } - let r = &mut self.world.random; - let cx = (p.x.floor() as i32 >> 4) + r.next_int_bound(17).unwrap_or(8) - 8; - let cz = (p.z.floor() as i32 >> 4) + r.next_int_bound(17).unwrap_or(8) - 8; - let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { return }; - let x = cx * 16 + r.next_int_bound(16).unwrap_or(0); - let z = cz * 16 + r.next_int_bound(16).unwrap_or(0); - let top = self.land_column(x, z).unwrap_or(MIN_Y + 1).max(MIN_Y + 1); - let y = MIN_Y + self.world.random.next_int_bound((top - MIN_Y + 1).max(1)).unwrap_or(0); - let biome = self.res.biomes.get(chunk.biome(x, y, z)).clone(); - let Some(entries) = biome.spawns.get("monster").cloned() else { return }; - let Some(entry) = self.weighted(&entries).cloned() else { return }; - let darken = self.sky_darken(); - let pack = entry.min + self.world.random.next_int_bound((entry.max - entry.min + 1) as i32).unwrap_or(0) as u32; - let (mut sx, mut sz) = (x, z); - for _ in 0..pack.min(4) { - sx += self.world.random.next_int_bound(6).unwrap_or(0) - self.world.random.next_int_bound(6).unwrap_or(0); - sz += self.world.random.next_int_bound(6).unwrap_or(0) - self.world.random.next_int_bound(6).unwrap_or(0); - let (fx, fy, fz) = (f64::from(sx) + 0.5, f64::from(y), f64::from(sz) + 0.5); - let d2 = (fx - p.x).powi(2) + (fy - p.y).powi(2) + (fz - p.z).powi(2); - if d2 < 24.0 * 24.0 || d2 > 128.0 * 128.0 { - continue; - } - let free = |g: &Self, yy: i32| { - let f = g.res.facts.get(g.world.block(sx, yy, sz)); - !f.full_collision && f.fluid == Fluid::None - }; - let below = self.res.facts.get(self.world.block(sx, y - 1, sz)); - if !below.full_collision || below.fluid != Fluid::None || !free(self, y) || !free(self, y + 1) { - continue; - } - // Monster.isDarkEnoughToSpawn: sky light vs random(32), then - // block light 0 and darkened brightness within uniform(0, 7). - let light = self.world.light(sx, y, sz); - let (sky, block) = (i32::from(light >> 4), i32::from(light & 15)); - if sky > self.world.random.next_int_bound(32).unwrap_or(0) || block > 0 { - continue; - } - if (sky - darken).max(0) > self.world.random.next_int_bound(8).unwrap_or(0) { - continue; - } - self.add_mob(&entry.entity, fx, fy, fz, false); - } - } fn mob_hit(&self) -> Option<(usize, f64)> { let eye = self.eye_position()?; let dir = view_vector(self.yaw, self.pitch); @@ -2539,7 +2439,13 @@ impl Game<'_> { let dist = ((m.position.x - center[0]).powi(2) + (m.position.y - center[1]).powi(2) + (m.position.z - center[2]).powi(2)).sqrt() / diameter; if dist <= 1.0 && m.alive() { let impact = 1.0 - dist; - m.hurt(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, Some(center), &mut self.world.random); + let source = horizon_client::mobs::Damage { kind: horizon_client::mobs::DamageKind::Explosion, attacker: None, from: Some(center) }; + if m.damage(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, source) { + let (dx, dy, dz) = (m.position.x - center[0], m.position.y - center[1], m.position.z - center[2]); + let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4); + let k = impact * (1.0 - m.kind.knockback_resistance); + m.velocity = Vec3::new(m.velocity.x + dx / l * k, m.velocity.y + dy / l * k, m.velocity.z + dz / l * k); + } } } Ok(()) @@ -2589,152 +2495,7 @@ impl Game<'_> { Arc::new(c) } fn tick_mobs(&mut self) -> Result<()> { - self.attack_ticks = self.attack_ticks.saturating_add(1); - // Generation-time creature packs for newly generated chunks. - let fresh: Vec<(i32, i32)> = self.world.chunks.iter().filter(|(_, c)| c.fresh && c.lit).map(|(k, _)| *k).collect(); - for key in fresh { - if let Some(c) = self.world.chunks.get_mut(&key) { - Arc::make_mut(c).fresh = false; - } - self.spawn_chunk_creatures(key.0, key.1); - } - if self.ticks % 2 == 0 { - self.spawn_monsters(); - } - let player = self.player.as_ref().map(|p| ([p.position.x, p.position.y + 0.5, p.position.z], !p.health.dead_or_dying())); - let daylight = self.sky_darken() < 4 && self.world.weather.levels(1.0).0 < 0.2; - let mut events = Vec::new(); - let mut mobs = std::mem::take(&mut self.mobs); - { - let w = MobWorld { world: &self.world, facts: &self.res.facts, collision: self.collision, player, daylight }; - let random = &mut self.world.random.clone(); - let loaded = |m: &Mob| w.world.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32); - let mut dead = Vec::new(); - mobs.retain_mut(|m| { - if !loaded(m) { - return !m.hostile() || m.persistent; - } - let keep = m.tick(&w, random, &mut events); - if !keep && !m.alive() { - dead.push((m.kind.id.clone(), [m.position.x, m.position.y, m.position.z], m.id)); - } - keep - }); - self.world.random = random.clone(); - for (kind, pos, id) in dead { - let by_player = self.last_hurt_by_player.remove(&id); - let held = self.held().cloned(); - let drops = self.res.items.entity_drops(&kind, by_player, held.as_ref(), &mut self.world.random); - for d in drops { - self.spawn_item(d, [pos[0], pos[1] + 0.5, pos[2]], [0.0, 0.2, 0.0], 10); - } - if by_player { - // Animal: 1 + random(3); Monster: 5. - let hostile = self.res.mob_types.get(&kind).is_some_and(|t| t.category == "monster"); - let xp = if hostile { 5 } else { 1 + self.world.random.next_int_bound(3).unwrap_or(0) as u32 }; - self.spawn_orbs([pos[0], pos[1] + 0.5, pos[2]], xp); - } - } - } - self.mobs = mobs; - for e in events { - match e { - MobEvent::Sound(name, at, volume, pitch) => self.audio.play(&format!("minecraft:{name}"), Some(at), volume, pitch), - MobEvent::AttackPlayer(amount, from) => { - if self.creative { - continue; - } - if let Some(player) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id("minecraft:mob_attack") - && player.hurt(&self.motion.health, self.world.health_rules, id, amount).unwrap_or(false) - { - let (dx, dz) = (player.position.x - from[0], player.position.z - from[2]); - let l = (dx * dx + dz * dz).sqrt().max(1e-4); - player.velocity = Vec3::new(player.velocity.x / 2.0 + dx / l * 0.4, (player.velocity.y / 2.0 + 0.4).min(0.4), player.velocity.z / 2.0 + dz / l * 0.4); - let at = [player.position.x, player.position.y, player.position.z]; - self.audio.play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); - self.hurt_armor(amount); - } - } - MobEvent::Shoot(from, target) => { - // Skeleton.performRangedAttack: aim above by 20% of distance, inaccuracy 14 - 4 * difficulty(2). - let (dx, dz) = (target[0] - from[0], target[2] - from[2]); - let horizontal = (dx * dx + dz * dz).sqrt(); - let dy = target[1] + 0.5 - from[1] + horizontal * 0.2; - let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4); - let spread = 0.0075 * 6.0; - let r = &mut self.world.random; - let mut gauss = || f64::from(r.next_float() + r.next_float() - 1.0) * spread; - let v = [(dx / len + gauss()) * 1.6, (dy / len + gauss()) * 1.6, (dz / len + gauss()) * 1.6]; - let p = Vec3::new(from[0], from[1] - 0.1, from[2]); - self.arrows.push(Arrow { from_player: false, critical: false, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 }); - self.audio.play("minecraft:entity.skeleton.shoot", Some(from), 1.0, 1.0 / (self.world.random.next_float() * 0.4 + 0.8)); - } - MobEvent::Explode(at, radius) => self.explode(at, radius)?, - } - } - // Arrows. - let bounds = self.player.as_ref().map(|p| { - let w = f64::from(p.dimensions.width) / 2.0; - horizon_core::geometry::Aabb::new( - Vec3::new(p.position.x - w, p.position.y, p.position.z - w), - Vec3::new(p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w), - ) - }); - let mut arrows = std::mem::take(&mut self.arrows); - let mut hits = Vec::new(); - let mobs = &mut self.mobs; - let mut random_state = self.world.random.clone(); - let random = &mut random_state; - let mut mob_hits = Vec::new(); - arrows.retain_mut(|a| { - if a.from_player && !a.stuck { - let (keep, _) = a.tick(&self.world, &self.res.facts, None); - for m in mobs.iter_mut().filter(|m| m.alive()) { - let b = m.bounds(); - let (lo, hi) = (b.min_position(), b.max_position()); - let p = a.position; - if p.x > lo.x - 0.3 && p.x < hi.x + 0.3 && p.y > lo.y - 0.3 && p.y < hi.y + 0.3 && p.z > lo.z - 0.3 && p.z < hi.z + 0.3 { - // AbstractArrow.onHitEntity: ceil(speed * base), crits add random(damage / 2 + 2). - let speed = (a.velocity.x.powi(2) + a.velocity.y.powi(2) + a.velocity.z.powi(2)).sqrt(); - let mut damage = (speed * a.base_damage).ceil().max(0.0) as i32; - if a.critical { - damage += random.next_int_bound(damage / 2 + 2).unwrap_or(0); - } - if m.hurt(damage as f32, Some([a.previous.x, a.previous.y, a.previous.z]), random) { - mob_hits.push((m.id, [p.x, p.y, p.z])); - } - return false; - } - } - return keep; - } - let (keep, hit) = a.tick(&self.world, &self.res.facts, if a.from_player { None } else { bounds }); - if let ArrowHit::Player(d) = hit { - hits.push(d); - } - keep - }); - self.arrows = arrows; - self.world.random = random_state; - for (id, at) in mob_hits { - self.last_hurt_by_player.insert(id); - self.audio.play("minecraft:entity.arrow.hit", Some(at), 1.0, 1.2 / (self.world.random.next_float() * 0.2 + 0.9)); - } - for d in hits { - if self.creative { - continue; - } - if let Some(player) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id("minecraft:arrow") - { - let _ = player.hurt(&self.motion.health, self.world.health_rules, id, d); - let at = [player.position.x, player.position.y, player.position.z]; - self.audio.play("minecraft:entity.arrow.hit_player", Some(at), 1.0, 1.0); - self.hurt_armor(d); - } - } - Ok(()) + self.tick_creatures() } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { @@ -3539,14 +3300,13 @@ impl Game<'_> { return; } let Some(eye) = self.eye_position() else { return }; - let dir = view_vector(self.yaw, self.pitch); - // Projectile.shoot: inaccuracy 1.0 as gaussian * 0.0075. - let r = &mut self.world.random; - let mut jitter = || f64::from(r.next_float() + r.next_float() - 1.0) * 0.0075; - let speed = f64::from(power) * 3.0; - let v = [(dir[0] + jitter()) * speed, (dir[1] + jitter()) * speed, (dir[2] + jitter()) * speed]; + // BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1). let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); - self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 }); + let kind = horizon_client::projectiles::ProjectileKind::Arrow { base_damage: 2.0, critical: power >= 1.0, effect: None }; + let mut arrow = horizon_client::projectiles::Projectile::new(kind, p, Some(horizon_client::mobs::Who::Player)); + let (velocity, on_ground) = self.player.as_ref().map_or((Vec3::ZERO, true), |pl| (pl.velocity, pl.ground.on_ground)); + arrow.shoot_from_rotation(&mut self.world.random, self.pitch, self.yaw, 0.0, power * 3.0, 1.0, velocity, on_ground); + self.creatures.projectiles.push(arrow); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); if !self.creative @@ -4630,6 +4390,7 @@ pub fn run() -> Result<()> { })?); eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32()); let facts = BlockFacts::load(&root, &assets.registry)?; + let mob_data = horizon_client::mobs::MobData::load(&root, &facts); eprintln!("load facts: {:.2}s", started.elapsed().as_secs_f32()); let items = Items::load(&root, &assets.registry, &facts)?; eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32()); @@ -4699,6 +4460,7 @@ pub fn run() -> Result<()> { .map(|(w, h, px)| (w, h, px.chunks_exact(4).map(|p| p[3] > 0).collect())) .unwrap_or((1, 1, vec![false])), mob_types: MobTypes::load(&root)?.types.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(), + mob_data, context, threads, player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") @@ -4767,6 +4529,7 @@ pub fn run() -> Result<()> { spawn_search: 0, mobs: Vec::new(), arrows: Vec::new(), + creatures: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..95105eb29 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -21,6 +21,9 @@ const HELP: &[&str] = &[ "give ITEM [COUNT] add items to the inventory", "render-distance N chunks, 2..64", "time TICKS set the time of day", + "summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)", + "mobs [RADIUS] list mobs near the player with their AI state", + "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks", "resume leave the pause menu", "screenshot PATH write the next frame as PNG", "stats [reset] frame-time summary since the last reset", @@ -196,6 +199,40 @@ impl Game<'_> { self.world.day_time = arg(1)?.parse()?; ok() } + "summon" => { + self.require_world()?; + let baby = words.contains(&"baby"); + let nums: Vec = words[2..].iter().filter_map(|w| w.parse().ok()).collect(); + let at = (nums.len() >= 3).then(|| [nums[0], nums[1], nums[2]]); + let id = self.summon(arg(1)?, at, baby)?; + Ok(Some(json!({ "ok": true, "id": id }))) + } + "fill" => { + self.require_world()?; + let c: Vec = (1..=6).map(|i| arg(i).and_then(|v| v.parse::().map_err(|e| e.to_string()))).collect::>()?; + let name = arg(7)?; + let name = if name.contains(':') { name.to_owned() } else { format!("minecraft:{name}") }; + let state = self.res.assets.registry.default_state(&name).ok_or_else(|| format!("unknown block {name}"))?; + let (lo, hi) = ([c[0].min(c[3]), c[1].min(c[4]), c[2].min(c[5])], [c[0].max(c[3]), c[1].max(c[4]), c[2].max(c[5])]); + if (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1) > 1 << 20 { + return Err("fill volume too large".into()); + } + for x in lo[0]..=hi[0] { + for y in lo[1]..=hi[1] { + for z in lo[2]..=hi[2] { + if self.world.loaded(x, z) { + self.world.set(x, y, z, state)?; + } + } + } + } + ok() + } + "mobs" => { + self.require_world()?; + let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?; + Ok(Some(self.control_mobs(radius))) + } "resume" => { if self.screen == Screen::Paused { self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs new file mode 100644 index 000000000..8d0920ef8 --- /dev/null +++ b/crates/horizon-client/src/game/creatures.rs @@ -0,0 +1,1635 @@ +//! Mobs in the game loop: ticking with entity snapshots, natural and +//! chunk-generation spawning (`NaturalSpawner`), mob events (attacks, +//! breeding, conversions, drops), projectiles, player interactions +//! (feeding, shearing, milking, spawn eggs, throwing) and rendering. +use super::{Dim, Game, view_vector}; +use horizon_client::{ + Result, + blocks::Fluid, + collisions::SceneCollisions, + items::ItemStack, + mesher::Vertex, + mobs::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, PlayerView, Seen, SpawnSetup, Species, Who, + farm::Climate, + spawning::{self, BiomeFacts}, + }, + projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3, traverse_blocks}, + position::BlockPos, + random::RandomSource, +}; +use std::sync::Arc; + +/// Mob-system state owned by the game. +#[derive(Default)] +pub(super) struct Creatures { + pub projectiles: Vec, + /// Player status effects applied by mobs: (effect, ticks left, amplifier). + pub player_effects: Vec<(&'static str, i32, i32)>, + pub player_fire: i32, + pub pearl_cooldown: u32, +} +/// MobCategory caps (maxInstancesPerChunk with the 17x17 spawnable chunk area). +const CATEGORIES: [(&str, usize); 7] = [ + ("monster", 70), + ("creature", 10), + ("ambient", 15), + ("axolotls", 5), + ("underground_water_creature", 5), + ("water_creature", 5), + ("water_ambient", 20), +]; + +struct ProjWorld<'a, 'w> { + w: &'a MobWorld<'w>, + targets: Vec<(Who, Aabb)>, +} +impl ProjectileWorld for ProjWorld<'_, '_> { + fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> { + let mut scene = SceneCollisions { + world: self.w.world, + binding: self.w.collision, + }; + let r = traverse_blocks(from, to, 256, |p: BlockPos| { + let state = self.w.world.block(p.x, p.y, p.z); + if self.w.facts.is_air(state) { + return None; + } + let shape = self + .w + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p) + }); + let hit = r.ok().flatten()?; + Some(( + hit.location, + [hit.block.x, hit.block.y, hit.block.z], + hit.direction.normal(), + )) + } + fn in_water(&self, at: Vec3) -> bool { + self.w.fluid( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ) == Fluid::Water + } + fn targets(&self) -> &[(Who, Aabb)] { + &self.targets + } +} +fn seen(m: &Mob) -> Seen { + Seen { + id: m.id, + species: m.species(), + position: m.position, + bounds: m.bounds(), + eye_y: m.eye_y(), + alive: m.alive(), + baby: m.is_baby(), + in_love: m.extra.in_love > 0, + tame: m.extra.tame, + hostile: m.hostile(), + target: m.ai.target, + health: m.health, + variant: m.extra.variant, + } +} +impl Game<'_> { + fn player_view(&self) -> Option { + let p = self.player.as_ref()?; + let w = f64::from(p.dimensions.width) / 2.0; + let bounds = Aabb::new( + Vec3::new(p.position.x - w, p.position.y, p.position.z - w), + Vec3::new( + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ), + ); + Some(PlayerView { + position: p.position, + bounds, + eye: [ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ], + alive: !p.health.dead_or_dying(), + creative: self.creative, + sneaking: self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft), + look: view_vector(self.yaw, self.pitch), + main_hand: self.held().map(|s| s.item.clone()), + off_hand: None, + head: self.armor[0].as_ref().map(|s| s.item.clone()), + armor_cover: self.armor.iter().filter(|a| a.is_some()).count() as f32 / 4.0, + }) + } + /// Biome facts at a position for finalizeSpawn and variant rules. + pub(super) fn biome_facts(&self, x: i32, y: i32, z: i32) -> BiomeFacts { + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + return BiomeFacts::default(); + }; + let b = self.res.biomes.get(chunk.biome(x, y, z)); + let tags = &self.res.mob_data; + let has = |t: &str| tags.biome_has(t, &b.name); + let climate = if has("minecraft:spawns_warm_variant_farm_animals") { + Climate::Warm + } else if has("minecraft:spawns_cold_variant_farm_animals") { + Climate::Cold + } else { + Climate::Temperate + }; + BiomeFacts { + climate, + temperature: b.temperature, + snowy: has("minecraft:spawns_snow_foxes") + || b.name.contains("snow") + || b.name.contains("frozen"), + swamp: b.name.contains("swamp"), + ocean: has("minecraft:is_ocean"), + mushroom: b.name == "minecraft:mushroom_fields", + desert: b.name == "minecraft:desert", + jungle: has("minecraft:is_jungle"), + } + } + /// 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 { + let kind = if kind.contains(':') { + kind.to_owned() + } else { + format!("minecraft:{kind}") + }; + let t = self.res.mob_types.get(&kind).cloned()?; + self.next_entity += 1; + let yaw = self.world.random.next_float() * 360.0; + let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), yaw); + mob.persistent = persistent; + let facts = self.biome_facts( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ); + spawning::finalize(&mut mob, &facts); + let id = mob.id; + self.mobs.push(mob); + Some(id) + } + /// The `summon` command: spawn a mob in front of the player or at a position. + pub(super) fn summon(&mut self, kind: &str, at: Option<[f64; 3]>, baby: bool) -> Result { + let at = match at { + Some(a) => a, + None => { + let p = self.player.as_ref().ok_or("no player yet")?; + let d = view_vector(self.yaw, 0.0); + [ + p.position.x + d[0] * 3.0, + p.position.y, + p.position.z + d[2] * 3.0, + ] + } + }; + let id = self + .spawn_mob(kind, at, true) + .ok_or_else(|| format!("unknown or unsupported mob {kind}"))?; + if baby && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.extra.age = -24000; + } + Ok(id) + } + /// The `mobs` command: nearby mobs with position, health and running goals. + pub(super) fn control_mobs(&self, radius: f64) -> serde_json::Value { + let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position); + let list: Vec = self + .mobs + .iter() + .filter(|m| m.distance_sqr(center) <= radius * radius) + .map(|m| { + serde_json::json!({ + "id": m.id, + "kind": m.kind.id, + "pos": [m.position.x, m.position.y, m.position.z], + "health": m.health, + "baby": m.is_baby(), + "target": m.ai.target.map(|t| format!("{t:?}")), + "goals": m.ai.goals.running_names(), + "targets": m.ai.targets.running_names(), + "path": m.ai.nav.path.as_ref().map(|p| p.nodes.len() - p.next.min(p.nodes.len())), + "on_ground": m.on_ground, + "variant": m.extra.variant, + "color": m.extra.color, + }) + }) + .collect(); + 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 { + 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)); + if (f.full_collision || f.fluid != Fluid::None) && !f.name.ends_with("leaves") { + return y + 1; + } + } + horizon_client::chunk::MIN_Y + } + fn weighted_entry( + &mut self, + entries: &[horizon_client::biome::SpawnEntry], + ) -> Option { + let total: u32 = entries.iter().map(|e| e.weight).sum(); + if total == 0 { + return None; + } + let mut r = self.world.random.next_int_bound(total as i32).ok()? as u32; + for e in entries { + if r < e.weight { + return Some(e.clone()); + } + r -= e.weight; + } + None + } + /// NaturalSpawner.spawnMobsForChunkGeneration (creature packs at generation). + pub(super) fn spawn_generation_creatures(&mut self, cx: i32, cz: i32) { + let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { + return; + }; + let biome = self.res.biomes.get(chunk.biome(8, 64, 8)).clone(); + let Some(entries) = biome.spawns.get("creature").cloned() else { + return; + }; + let (xo, zo) = (cx * 16, cz * 16); + while self.world.random.next_float() < biome.creature_probability { + let Some(entry) = self.weighted_entry(&entries) else { + return; + }; + let count = entry.min + + self + .world + .random + .next_int_bound((entry.max - entry.min + 1) as i32) + .unwrap_or(0) as u32; + let mut x = xo + self.world.random.next_int_bound(16).unwrap_or(0); + let mut z = zo + self.world.random.next_int_bound(16).unwrap_or(0); + let (sx, sz) = (x, z); + let Some(kind) = self.res.mob_types.get(&entry.entity).cloned() else { + continue; + }; + for _ in 0..count { + let mut success = false; + let mut attempts = 0; + while !success && attempts < 4 { + attempts += 1; + let mut y = self.motion_top(x, z); + let placement = self.res.mob_data.placement(&entry.entity); + if placement == horizon_client::mobs::data::Placement::OnGround { + let below = self.world.block(x, y - 1, z); + if self.res.mob_data.state(below).flags & horizon_client::mobs::data::LAND + != 0 + { + y -= 1; + } + } + let ok = { + let w = self.mob_world_base(&[]); + spawning::placement_ok(kind.species, &w, x, y, z) && { + let mut r = self.world.random.clone(); + let rules = spawning::spawn_rules_ok(kind.species, &w, &mut r, x, y, z); + rules + } + }; + if ok { + let width = kind.width; + let fx = + f64::from(x).clamp(f64::from(xo) + width, f64::from(xo) + 16.0 - width); + let fz = + f64::from(z).clamp(f64::from(zo) + width, f64::from(zo) + 16.0 - width); + if self + .spawn_mob(&entry.entity, [fx, f64::from(y), fz], true) + .is_some() + { + success = true; + } + } + x += self.world.random.next_int_bound(5).unwrap_or(0) + - self.world.random.next_int_bound(5).unwrap_or(0); + z += self.world.random.next_int_bound(5).unwrap_or(0) + - self.world.random.next_int_bound(5).unwrap_or(0); + while x < xo || x >= xo + 16 || z < zo || z >= zo + 16 { + x = sx + self.world.random.next_int_bound(5).unwrap_or(0) + - self.world.random.next_int_bound(5).unwrap_or(0); + z = sz + self.world.random.next_int_bound(5).unwrap_or(0) + - self.world.random.next_int_bound(5).unwrap_or(0); + } + } + } + } + } + fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> { + let (rain, thunder) = self.world.weather.levels(1.0); + MobWorld { + world: &self.world, + facts: &self.res.facts, + collision: self.collision, + data: &self.res.mob_data, + player: self.player_view(), + others, + daylight: self.dim != Dim::Nether && self.sky_darken() < 4, + game_time: self.world.game_time, + day_time: self.world.day_time, + raining: rain > 0.2, + thundering: thunder > 0.9, + nether: self.dim == Dim::Nether, + block_tags: &self.res.items.block_tags, + } + } + /// NaturalSpawner.spawnForChunk over the chunks within 8 of the player. + fn spawn_natural(&mut self) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); + let mut counts = [0usize; 7]; + for m in &self.mobs { + if let Some(i) = CATEGORIES.iter().position(|c| c.0 == m.kind.category) { + counts[i] += 1; + } + } + let creature_tick = self.world.game_time % 400 == 0; + let mut chunks: Vec<(i32, i32)> = (-8..=8) + .flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz))) + .filter(|c| self.world.chunks.contains_key(c)) + .collect(); + // ChunkMap: shuffled each tick. + for i in (1..chunks.len()).rev() { + let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + chunks.swap(i, j); + } + for (cx, cz) in chunks { + for (ci, (category, cap)) in CATEGORIES.iter().enumerate() { + if counts[ci] >= *cap || *category == "creature" && !creature_tick { + continue; + } + counts[ci] += self.spawn_category_for_chunk(category, cx, cz, p); + } + } + } + /// NaturalSpawner.spawnCategoryForPosition at a random point in the chunk. + fn spawn_category_for_chunk( + &mut self, + category: &str, + cx: i32, + cz: i32, + player: Vec3, + ) -> usize { + let x0 = cx * 16 + self.world.random.next_int_bound(16).unwrap_or(0); + let z0 = cz * 16 + self.world.random.next_int_bound(16).unwrap_or(0); + let top = self.motion_top(x0, z0) + 1; + let min = horizon_client::chunk::MIN_Y; + let y = min + self.world.random.next_int_bound(top - min + 1).unwrap_or(0); + if y < min + 1 { + return 0; + } + let start = self.res.facts.get(self.world.block(x0, y, z0)); + if start.full_collision { + return 0; + } + let mut spawned = 0; + for _ in 0..3 { + let (mut x, mut z) = (x0, z0); + let mut entry: Option = None; + let mut group = (self.world.random.next_float() * 4.0).ceil() as u32; + let mut cluster = 0; + let mut i = 0; + while i < group { + i += 1; + x += self.world.random.next_int_bound(6).unwrap_or(0) + - self.world.random.next_int_bound(6).unwrap_or(0); + z += self.world.random.next_int_bound(6).unwrap_or(0) + - self.world.random.next_int_bound(6).unwrap_or(0); + let (fx, fz) = (f64::from(x) + 0.5, f64::from(z) + 0.5); + let d2 = (fx - player.x).powi(2) + + (f64::from(y) - player.y).powi(2) + + (fz - player.z).powi(2); + if d2 <= 576.0 { + continue; + } + if entry.is_none() { + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + break; + }; + let biome = self.res.biomes.get(chunk.biome(x, y, z)).clone(); + let Some(list) = biome.spawns.get(category).cloned() else { + break; + }; + let list: Vec<_> = list + .into_iter() + .filter(|e| self.res.mob_types.contains_key(&e.entity)) + .collect(); + let Some(e) = self.weighted_entry(&list) else { + break; + }; + group = e.min + + self + .world + .random + .next_int_bound((e.max - e.min + 1) as i32) + .unwrap_or(0) as u32; + entry = Some(e); + } + let e = entry.clone().unwrap_or_else(|| unreachable!()); + let despawn = if category == "water_ambient" { + 64.0 + } else { + 128.0 + }; + if d2 > despawn * despawn { + continue; + } + let Some(kind) = self.res.mob_types.get(&e.entity).cloned() else { + break; + }; + let ok = { + let w = self.mob_world_base(&[]); + let mut r = self.world.random.clone(); + let placed = spawning::placement_ok(kind.species, &w, x, y, z) + && spawning::spawn_rules_ok(kind.species, &w, &mut r, x, y, z); + let half = kind.width / 2.0; + let room = w.no_collision(Aabb::new( + Vec3::new(fx - half, f64::from(y), fz - half), + Vec3::new(fx + half, f64::from(y) + kind.height, fz + half), + )); + // PathfinderMob.checkSpawnRules: walk target value >= 0 (monsters need darkness). + let light_ok = !kind.category.eq("monster") + || matches!( + kind.species, + Species::Slime | Species::Ghast | Species::MagmaCube + ) + || w.brightness(x, y, z) <= 0.5; + let consumed = r; + (placed && room && light_ok, consumed) + }; + self.world.random = ok.1; + if !ok.0 { + continue; + } + if d2 > 16384.0 && kind.category != "creature" { + continue; + } + if self + .spawn_mob(&e.entity, [fx, f64::from(y), fz], false) + .is_some() + { + cluster += 1; + spawned += 1; + if spawned >= 4 || cluster >= group.max(1) { + return spawned; + } + } + } + } + spawned + } + /// Advance every mob one tick, then apply their events. + pub(super) fn tick_creatures(&mut self) -> Result<()> { + self.attack_ticks = self.attack_ticks.saturating_add(1); + let fresh: Vec<(i32, i32)> = self + .world + .chunks + .iter() + .filter(|(_, c)| c.fresh && c.lit) + .map(|(k, _)| *k) + .collect(); + for key in fresh { + if let Some(c) = self.world.chunks.get_mut(&key) { + Arc::make_mut(c).fresh = false; + } + self.spawn_generation_creatures(key.0, key.1); + } + self.spawn_natural(); + let snapshot: Vec = self.mobs.iter().map(seen).collect(); + let mut events = Vec::new(); + let mut mobs = std::mem::take(&mut self.mobs); + let mut dead = Vec::new(); + { + let w = self.mob_world_base(&snapshot); + let mut scratch = self.world.random.clone(); + mobs.retain_mut(|m| { + if !w + .world + .loaded(m.position.x.floor() as i32, m.position.z.floor() as i32) + { + return !m.hostile() || m.persistent; + } + let keep = m.tick(&w, &mut scratch, &mut events); + if !keep && !m.alive() && !m.removed { + dead.push(m.clone()); + } + keep + }); + push_apart(&mut mobs); + } + self.mobs.append(&mut mobs); + for m in dead { + self.mob_died(&m); + } + self.handle_mob_events(events)?; + self.tick_projectiles()?; + self.tick_player_effects(); + Ok(()) + } + /// LivingEntity.die / dropAllDeathLoot. + fn mob_died(&mut self, m: &Mob) { + let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let held = self.held().cloned(); + let pos = [m.position.x, m.position.y + 0.5, m.position.z]; + if !m.is_baby() { + let mut drops = self.res.items.entity_drops( + &m.kind.id, + by_player, + held.as_ref(), + &mut self.world.random, + ); + if m.species() == Species::Sheep && !m.extra.sheared { + let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; + drops.extend(self.res.items.loot_table( + &format!("minecraft:entities/sheep/{color}"), + by_player, + held.as_ref(), + &mut self.world.random, + )); + } + for d in drops { + if d.count > 0 && &*d.item != "minecraft:air" { + self.spawn_item(d, pos, [0.0, 0.2, 0.0], 10); + } + } + for item in [&m.extra.main_hand] { + // Equipment drop chance 8.5% (+ player kill only). + if let Some(item) = item + && by_player + && self.world.random.next_float() < 0.085 + { + self.spawn_item( + ItemStack { + item: item.clone(), + count: 1, + damage: 0, + }, + pos, + [0.0, 0.2, 0.0], + 10, + ); + } + } + } + if by_player { + let xp = experience_reward(m, &mut self.world.random); + if xp > 0 { + self.spawn_orbs(pos, xp); + } + } + if m.species() == Species::Slime || m.species() == Species::MagmaCube { + // Slime.remove: split into 2-4 smaller slimes. + let size = m.extra.size; + if size > 1 { + let n = 2 + self.world.random.next_int_bound(3).unwrap_or(0); + for k in 0..n { + let off = |kk: i32| (f64::from(kk % 2) - 0.5) * f64::from(size) / 4.0; + let at = [ + m.position.x + off(k), + m.position.y + 0.5, + m.position.z + off(k / 2), + ]; + if let Some(id) = self.spawn_mob(&m.kind.id, at, m.persistent) + && let Some(c) = self.mobs.iter_mut().find(|c| c.id == id) + { + c.extra.size = size / 2; + c.health = c.kind.max_health * (size / 2 * size / 2) as f32; + } + } + } + } + } + pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { + for e in events { + match e { + MobEvent::Sound(name, at, volume, pitch) => { + self.audio + .play(&format!("minecraft:{name}"), Some(at), volume, pitch) + } + MobEvent::SoundId(name, at, volume, pitch) => { + self.audio.play(&name, Some(at), volume, pitch) + } + MobEvent::AttackPlayer(amount, from) => { + self.mob_hits_player(amount, from, "minecraft:mob_attack") + } + MobEvent::Shoot(..) => {} + MobEvent::Explode(at, radius) => self.explode(at, radius)?, + MobEvent::AttackMob { + target, + amount, + source, + } => { + if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { + let hit = t.damage(amount, source); + if hit { + let (kind, center, dead) = (t.kind.clone(), t.center(), !t.alive()); + let pitch = (self.world.random.next_float() + - self.world.random.next_float()) + * 0.2 + + 1.0; + let s = kind.sounds[if dead { 2 } else { 1 }]; + if !s.is_empty() { + self.audio.play( + &format!("minecraft:{s}"), + Some(center), + 1.0, + pitch, + ); + } + } + } + } + MobEvent::SetTarget { mob, target } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.ai.target = Some(target); + } + } + MobEvent::Projectile(p) => self.creatures.projectiles.push(p), + MobEvent::Spawn(mut m) => { + self.next_entity += 1; + m.id = self.next_entity; + self.mobs.push(*m); + } + MobEvent::SpawnKind { kind, at, setup } => { + if let Some(id) = self.spawn_mob(&kind, at, setup.persistent) { + self.apply_setup(id, &setup); + } + } + MobEvent::DropItem { item, count, at } => self.spawn_item( + ItemStack { + item, + count, + damage: 0, + }, + at, + [0.0, 0.2, 0.0], + 10, + ), + MobEvent::SetBlock { pos, state } => { + self.world.set(pos[0], pos[1], pos[2], state)? + } + MobEvent::SetBlockName { pos, name, effect } => { + if effect { + let old = self.world.block(pos[0], pos[1], pos[2]); + self.destroy_particles(pos, old); + let s = self.res.facts.get(old).sounds.break_sound.clone(); + self.audio.play( + &s, + Some([ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]), + 1.0, + 0.8, + ); + } + if let Some(state) = self.res.assets.registry.default_state(name) { + self.world.set(pos[0], pos[1], pos[2], state)?; + } + } + MobEvent::BreakBlock { pos, drop } => { + let old = self.world.block(pos[0], pos[1], pos[2]); + self.destroy_particles(pos, old); + if drop { + let drops = self.res.items.block_drops( + &self.res.assets.registry, + old, + None, + &mut self.world.random, + ); + for d in drops { + self.pop_resource(pos, d); + } + } + self.world.set(pos[0], pos[1], pos[2], self.world.air)?; + } + MobEvent::Particles { .. } => {} + MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount), + MobEvent::EffectPlayer { + effect, + ticks, + amplifier, + } => { + if !self.creative { + self.creatures.player_effects.retain(|e| e.0 != effect); + self.creatures + .player_effects + .push((effect, ticks, amplifier)); + } + } + MobEvent::Ignite { target, seconds } => match target { + Who::Player => { + if !self.creative { + self.creatures.player_fire = + self.creatures.player_fire.max(seconds * 20); + } + } + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.fire_ticks = m.fire_ticks.max(seconds * 20); + } + } + }, + MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::GiftLoot { table, at } => { + let drops = + self.res + .items + .loot_table(table, false, None, &mut self.world.random); + for d in drops { + self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); + } + } + } + } + Ok(()) + } + fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) { + let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { + return; + }; + if setup.baby { + m.extra.age = -24000; + } + if setup.size > 0 { + m.extra.size = setup.size; + } + m.yaw = setup.yaw; + m.body_yaw = setup.yaw; + m.head_yaw = setup.yaw; + m.velocity = Vec3::new(setup.velocity[0], setup.velocity[1], setup.velocity[2]); + if let Some(h) = setup.health { + m.health = h; + } + if let Some(v) = setup.variant { + m.extra.variant = v; + } + } + /// Animal.spawnChildFromBreeding + fn breed(&mut self, parent: u32, partner: u32) { + let Some(p) = self.mobs.iter().find(|m| m.id == parent).cloned() else { + return; + }; + if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) { + q.extra.age = 6000; + q.extra.in_love = 0; + } + if let Some(id) = + self.spawn_mob(&p.kind.id, [p.position.x, p.position.y, p.position.z], true) + && let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) + { + child.extra.age = -24000; + // Offspring inherit a parent's variant (pigs/cows/chickens) or mixed wool. + child.extra.variant = p.extra.variant; + if p.species() == Species::Sheep { + child.extra.color = p.extra.color; + } + } + let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; + self.spawn_orbs([p.position.x, p.position.y, p.position.z], xp); + } + fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) { + if self.creative { + return; + } + if let Some(player) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + && player + .hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false) + { + let (dx, dz) = (player.position.x - from[0], player.position.z - from[2]); + let l = (dx * dx + dz * dz).sqrt().max(1e-4); + player.velocity = Vec3::new( + player.velocity.x / 2.0 + dx / l * 0.4, + (player.velocity.y / 2.0 + 0.4).min(0.4), + player.velocity.z / 2.0 + dz / l * 0.4, + ); + let at = [player.position.x, player.position.y, player.position.z]; + self.audio + .play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); + self.hurt_armor(amount); + } + } + /// Poison, wither, hunger and burning applied to the player by mobs. + fn tick_player_effects(&mut self) { + let in_water = self.player.as_ref().is_some_and(|p| { + let (x, y, z) = ( + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ); + self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water + }); + if self.creatures.player_fire > 0 { + if in_water { + self.creatures.player_fire = 0; + } else { + if self.creatures.player_fire % 20 == 0 { + self.hurt_player_by("minecraft:on_fire", 1.0); + } + self.creatures.player_fire -= 1; + } + } + let mut effects = std::mem::take(&mut self.creatures.player_effects); + for (effect, ticks, amp) in &mut effects { + // MobEffect.shouldApplyEffectTickThisTick intervals. + let interval = |base: i32| (base >> (*amp).max(0)).max(1); + match *effect { + "minecraft:poison" if *ticks % interval(25) == 0 => { + if self + .player + .as_ref() + .is_some_and(|p| p.health.health() > 1.0) + { + self.hurt_player_by("minecraft:magic", 1.0); + } + } + "minecraft:wither" if *ticks % interval(40) == 0 => { + self.hurt_player_by("minecraft:wither", 1.0) + } + "minecraft:hunger" => { + if let Some(p) = self.player.as_mut() { + p.health.food.exhaustion = + (p.health.food.exhaustion + 0.005 * (*amp + 1) as f32).min(40.0); + } + } + _ => {} + } + *ticks -= 1; + } + effects.retain(|e| e.1 > 0); + self.creatures.player_effects = effects; + if self.creatures.pearl_cooldown > 0 { + self.creatures.pearl_cooldown -= 1; + } + } + fn hurt_player_by(&mut self, damage_type: &str, amount: f32) { + if self.creative { + return; + } + if let Some(player) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + { + let _ = player.hurt(&self.motion.health, self.world.health_rules, id, amount); + } + } + fn tick_projectiles(&mut self) -> Result<()> { + let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + let mut hits = Vec::new(); + { + let mut targets: Vec<(Who, Aabb)> = self + .mobs + .iter() + .filter(|m| m.alive()) + .map(|m| (Who::Mob(m.id), m.bounds())) + .collect(); + if let Some(p) = self.player_view() + && p.alive + { + targets.push((Who::Player, p.bounds)); + } + let w = self.mob_world_base(&[]); + let pw = ProjWorld { w: &w, targets }; + projectiles.retain_mut(|p| { + let (keep, hit) = p.tick(&pw); + if hit != Hit::None { + hits.push((p.clone(), hit)); + } + keep + }); + } + self.creatures.projectiles.append(&mut projectiles); + for (p, hit) in hits { + self.projectile_hit(&p, hit)?; + } + Ok(()) + } + fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { + let at = match hit { + Hit::Entity { at, .. } | Hit::Block { at, .. } => at, + Hit::None => return Ok(()), + }; + let atp = [at.x, at.y, at.z]; + let source_kind = match p.kind { + ProjectileKind::Arrow { .. } => DamageKind::Arrow, + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { + DamageKind::Fireball + } + _ => DamageKind::Thrown, + }; + let source = Damage { + kind: source_kind, + attacker: p.owner, + from: Some([p.previous.x, p.previous.y, p.previous.z]), + }; + match (&p.kind, hit) { + (ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => { + let amount = p.arrow_damage(&mut self.world.random); + match who { + Who::Player => { + if !self.creative { + self.mob_hits_player( + amount, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:arrow", + ); + if let Some((e, t)) = effect { + self.creatures.player_effects.push((e, *t, 0)); + } + self.audio.play( + "minecraft:entity.arrow.hit_player", + Some(atp), + 1.0, + 1.0, + ); + } + } + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.damage(amount, source); + } + if p.owner == Some(Who::Player) { + self.last_hurt_by_player.insert(id); + } + let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9); + self.audio + .play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch); + } + } + } + (ProjectileKind::Arrow { .. }, Hit::Block { .. }) => { + let pitch = 1.2 / (self.world.random.next_float() * 0.2 + 0.9); + self.audio + .play("minecraft:entity.arrow.hit", Some(atp), 1.0, pitch); + } + (ProjectileKind::Snowball, hit) => { + if let Hit::Entity { + who: Who::Mob(id), .. + } = hit + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + // Snowball.onHitEntity: 3 damage to blazes, 0 otherwise. + let amount = if m.species() == Species::Blaze { + 3.0 + } else { + 0.0 + }; + m.damage(amount, source); + } + self.item_burst(atp, "minecraft:snowball"); + } + (ProjectileKind::Egg, hit) => { + if let Hit::Entity { + who: Who::Mob(id), .. + } = hit + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.damage(0.0, source); + } + // ThrownEgg.onHit: 1/8 chance of a chick, 1/32 of four. + if self.world.random.next_int_bound(8).unwrap_or(1) == 0 { + let n = if self.world.random.next_int_bound(32).unwrap_or(1) == 0 { + 4 + } else { + 1 + }; + for _ in 0..n { + if let Some(id) = self.spawn_mob("minecraft:chicken", atp, true) + && let Some(c) = self.mobs.iter_mut().find(|m| m.id == id) + { + c.extra.age = -24000; + } + } + } + self.item_burst(atp, "minecraft:egg"); + } + (ProjectileKind::EnderPearl, hit) => { + if let Hit::Entity { + who: Who::Mob(id), .. + } = hit + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + { + m.damage(0.0, source); + } + if p.owner == Some(Who::Player) && self.player.is_some() { + // ThrownEnderpearl: 5% endermite, teleport, 5 damage. + if self.world.random.next_float() < 0.05 { + self.spawn_mob("minecraft:endermite", atp, false); + } + if let Some(pl) = self.player.as_mut() { + pl.position = at; + pl.velocity = Vec3::ZERO; + pl.fall_distance = 0.0; + } + self.previous_position = at; + self.hurt_player_by("minecraft:ender_pearl", 5.0); + self.audio + .play("minecraft:entity.player.teleport", Some(atp), 1.0, 1.0); + } + } + (ProjectileKind::SmallFireball, hit) => match hit { + Hit::Entity { who, .. } => match who { + Who::Player => { + if !self.creative { + self.creatures.player_fire = self.creatures.player_fire.max(100); + self.mob_hits_player( + 5.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:fireball", + ); + } + } + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + if !m.kind.flags.fire_immune { + m.fire_ticks = m.fire_ticks.max(100); + } + m.damage(5.0, source); + } + } + }, + Hit::Block { pos, face, .. } => { + let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; + if self + .res + .facts + .is_air(self.world.block(fire[0], fire[1], fire[2])) + && let Some(state) = + self.res.assets.registry.default_state("minecraft:fire") + { + self.world.set(fire[0], fire[1], fire[2], state)?; + } + } + Hit::None => {} + }, + (ProjectileKind::LargeFireball { power }, hit) => { + if let Hit::Entity { who, .. } = hit { + match who { + Who::Player => self.mob_hits_player( + 6.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:fireball", + ), + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.damage(6.0, source); + } + } + } + } + self.explode(atp, *power as f32)?; + } + ( + ProjectileKind::Potion { + effect, + ticks, + amplifier, + .. + }, + _, + ) => { + // AbstractThrownPotion.applySplash: within 4 blocks, scaled by distance. + if let Some(pv) = self.player_view() { + let d2 = (pv.position.x - at.x).powi(2) + + (pv.position.y - at.y).powi(2) + + (pv.position.z - at.z).powi(2); + if d2 < 16.0 && !self.creative { + let scale = 1.0 - d2.sqrt() / 4.0; + let t = (f64::from(*ticks) * scale + 0.5) as i32; + match *effect { + "minecraft:instant_damage" => self.hurt_player_by( + "minecraft:indirect_magic", + 6.0 * (1 << *amplifier) as f32 * scale as f32, + ), + e if t > 20 => self.creatures.player_effects.push((e, t, *amplifier)), + _ => {} + } + } + } + self.audio.play( + "minecraft:entity.splash_potion.break", + Some(atp), + 1.0, + self.world.random.next_float() * 0.1 + 0.9, + ); + } + (ProjectileKind::LlamaSpit, Hit::Entity { who, .. }) => match who { + Who::Player => self.mob_hits_player( + 1.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:spit", + ), + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.damage(1.0, source); + } + } + }, + _ => {} + } + Ok(()) + } + /// Item break particles (snowballs, eggs). + fn item_burst(&mut self, at: [f64; 3], item: &str) { + let sprite = format!("item/{}", item.trim_start_matches("minecraft:")); + for _ in 0..8 { + let v = [ + (self.world.random.next_double() - 0.5) * 0.08, + self.world.random.next_double() * 0.1, + (self.world.random.next_double() - 0.5) * 0.08, + ]; + let p = horizon_client::particles::Particle::terrain( + &mut self.world.random, + at, + v, + sprite.clone(), + 0xFFFFFF, + ); + self.particles.push(p); + } + } + /// Right click on a mob (Mob.interact / mobInteract). Returns true when consumed. + pub(super) fn interact_mob(&mut self) -> Result { + let Some((index, distance)) = self.mob_hit() else { + return Ok(false); + }; + if let Some(hit) = self.pick() + && let Some(eye) = self.eye_position() + { + let d = ((hit.point[0] - eye[0]).powi(2) + + (hit.point[1] - eye[1]).powi(2) + + (hit.point[2] - eye[2]).powi(2)) + .sqrt(); + if d < distance { + return Ok(false); + } + } + let held = self.held().cloned(); + let item = held + .as_ref() + .map(|h| h.item.to_string()) + .unwrap_or_default(); + let creative = self.creative; + let selected = self.selected; + let m = &mut self.mobs[index]; + if !m.alive() { + return Ok(false); + } + let species = m.species(); + let center = m.center(); + let mut consume = false; + let mut give: Option<&str> = None; + let mut sound: Option<&str> = None; + let mut handled = true; + let mut drops: Vec<(String, u32)> = Vec::new(); + let is_food = m.kind.food.iter().any(|f| *f == item); + match species { + Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => { + give = Some("minecraft:milk_bucket"); + consume = true; + sound = Some("entity.cow.milk"); + } + Species::Mooshroom if item == "minecraft:bowl" && !m.is_baby() => { + give = Some("minecraft:mushroom_stew"); + consume = true; + sound = Some("entity.mooshroom.milk"); + } + Species::Mooshroom if item == "minecraft:shears" && !m.is_baby() => { + // MushroomCow.shear: becomes a cow and drops five mushrooms. + let mushroom = if m.extra.variant == 1 { + "minecraft:brown_mushroom" + } else { + "minecraft:red_mushroom" + }; + drops.push((mushroom.into(), 5)); + m.removed = true; + let setup = SpawnSetup { + yaw: m.yaw, + persistent: true, + ..Default::default() + }; + let pos = [m.position.x, m.position.y, m.position.z]; + sound = Some("entity.mooshroom.shear"); + self.handle_mob_events(vec![MobEvent::SpawnKind { + kind: "minecraft:cow".into(), + at: pos, + setup, + }])?; + } + Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => { + m.extra.sheared = true; + let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; + let stacks = self.res.items.loot_table( + &format!("minecraft:shearing/sheep/{color}"), + false, + None, + &mut self.world.random, + ); + drops.extend(stacks.into_iter().map(|s| (s.item.to_string(), s.count))); + sound = Some("entity.sheep.shear"); + self.damage_held_tool(); + } + Species::Sheep if item.ends_with("_dye") => { + let name = item + .trim_start_matches("minecraft:") + .trim_end_matches("_dye"); + if let Some(c) = horizon_client::mobs::render::DYE_NAMES + .iter() + .position(|d| *d == name) + && m.extra.color as usize != c + && !m.extra.sheared + { + m.extra.color = c as u8; + consume = true; + sound = Some("item.dye.use"); + } else { + handled = false; + } + } + Species::Creeper if item == "minecraft:flint_and_steel" => { + m.extra.flag = true; + sound = Some("item.flintandsteel.use"); + self.damage_held_tool(); + } + _ if is_food && m.kind.flags.animal => { + // Animal.mobInteract: breed adults, speed up babies. + if m.extra.age == 0 && m.extra.in_love <= 0 { + m.extra.in_love = 600; + m.extra.love_player = true; + consume = true; + sound = Some(eat_sound(species)); + } else if m.extra.age < 0 { + // AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age)) = 10%. + let secs = (-m.extra.age / 20) as f32 * 0.1; + m.extra.age = (m.extra.age + (secs as i32) * 20).min(0); + consume = true; + sound = Some(eat_sound(species)); + } else { + handled = false; + } + } + _ => handled = false, + } + if !handled { + return Ok(false); + } + self.swing_arm(); + if let Some(s) = sound { + let pitch = + (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + self.audio + .play(&format!("minecraft:{s}"), Some(center), 1.0, pitch); + } + if consume && !creative { + if let Some(stack) = self.inventory[selected].as_mut() { + stack.count -= 1; + if stack.count == 0 { + self.inventory[selected] = None; + } + } + } + if let Some(g) = give { + let stack = ItemStack { + item: g.into(), + count: 1, + damage: 0, + }; + if self.inventory[selected].is_none() { + self.inventory[selected] = Some(stack); + } else if let Some(rest) = self.give(stack) { + let at = self.eye_position().unwrap_or(center); + self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40); + } + } + for (item, count) in drops { + for _ in 0..count { + let v = [ + (self.world.random.next_float() - self.world.random.next_float()) as f64 * 0.1, + self.world.random.next_float() as f64 * 0.05, + (self.world.random.next_float() - self.world.random.next_float()) as f64 * 0.1, + ]; + self.spawn_item( + ItemStack { + item: item.as_str().into(), + count: 1, + damage: 0, + }, + [center[0], center[1] + 0.5, center[2]], + v, + 10, + ); + } + } + Ok(true) + } + fn damage_held_tool(&mut self) { + if self.creative { + return; + } + if let Some(stack) = self.inventory[self.selected].as_mut() + && let Some(info) = self.res.items.get(&stack.item) + && info.max_damage > 0 + { + stack.damage += 1; + if stack.damage >= info.max_damage { + self.inventory[self.selected] = None; + } + } + } + /// Throwables and spawn eggs (SnowballItem/EggItem/EnderpearlItem/SpawnEggItem.use). + pub(super) fn throw_item(&mut self, stack: &ItemStack) -> Result { + let item = &*stack.item; + let kind = match item { + "minecraft:snowball" => ProjectileKind::Snowball, + "minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg, + "minecraft:ender_pearl" => { + if self.creatures.pearl_cooldown > 0 { + return Ok(true); + } + self.creatures.pearl_cooldown = 20; + ProjectileKind::EnderPearl + } + _ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack), + _ => return Ok(false), + }; + let Some(eye) = self.eye_position() else { + return Ok(false); + }; + let Some(p) = self.player.as_ref() else { + return Ok(false); + }; + let (velocity, on_ground) = (p.velocity, p.ground.on_ground); + let start = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); + let mut proj = Projectile::new(kind.clone(), start, Some(Who::Player)); + proj.shoot_from_rotation( + &mut self.world.random, + self.pitch, + self.yaw, + 0.0, + 1.5, + 1.0, + velocity, + on_ground, + ); + self.creatures.projectiles.push(proj); + let sound = match kind { + ProjectileKind::Snowball => "minecraft:entity.snowball.throw", + ProjectileKind::Egg => "minecraft:entity.egg.throw", + _ => "minecraft:entity.ender_pearl.throw", + }; + let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); + self.audio.play(sound, Some(eye), 0.5, pitch); + self.swing_arm(); + if !self.creative + && let Some(s) = self.inventory[self.selected].as_mut() + { + s.count -= 1; + if s.count == 0 { + self.inventory[self.selected] = None; + } + } + Ok(true) + } + fn use_spawn_egg(&mut self, stack: &ItemStack) -> Result { + let Some(hit) = self.pick() else { + return Ok(false); + }; + let kind = stack.item.trim_end_matches("_spawn_egg").to_owned(); + let p = [ + hit.pos[0] + hit.face[0], + hit.pos[1] + hit.face[1], + hit.pos[2] + hit.face[2], + ]; + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + if self.spawn_mob(&kind, at, true).is_none() { + return Ok(false); + } + self.swing_arm(); + if !self.creative + && let Some(s) = self.inventory[self.selected].as_mut() + { + s.count -= 1; + if s.count == 0 { + self.inventory[self.selected] = None; + } + } + Ok(true) + } + /// Mob models and projectiles for the entity pass. + pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { + let atlas = &self.res.atlas; + let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + for mob in &self.mobs { + let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; + if d.length_squared() > 128.0 * 128.0 { + continue; + } + let light = self.world.light( + mob.position.x.floor() as i32, + (mob.position.y + mob.eye_height()).floor() as i32, + mob.position.z.floor() as i32, + ); + let mut packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) { + packed = 15 * 16 | (15 * 16) << 8; + } + horizon_client::mobs::render::render( + mob, + alpha as f32, + camera, + &lookup, + packed, + &self.res.mob_data, + out, + ); + } + // Projectiles: arrows as crossed quads, the rest as item billboards. + let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); + let forward = glam::Vec3::new( + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ); + let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); + let up = right.cross(forward).normalize_or_zero(); + for a in &self.creatures.projectiles { + let p = glam::DVec3::new( + a.previous.x + (a.position.x - a.previous.x) * alpha, + a.previous.y + (a.position.y - a.previous.y) * alpha, + a.previous.z + (a.position.z - a.previous.z) * alpha, + ) - camera; + let c = p.as_vec3(); + let light = self.world.light( + a.position.x.floor() as i32, + a.position.y.floor() as i32, + a.position.z.floor() as i32, + ); + let mut packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8; + if a.is_fireball() { + packed = 15 * 16 | (15 * 16) << 8; + } + if a.is_arrow() { + let Some(r) = atlas.sprites.get("entity/projectiles/arrow").copied() else { + continue; + }; + let dir = glam::Vec3::new( + a.velocity.x as f32, + a.velocity.y as f32, + a.velocity.z as f32, + ) + .normalize_or(glam::Vec3::X); + let dir = if a.stuck { + glam::Vec3::new( + -a.yaw.to_radians().sin() * a.pitch.to_radians().cos(), + a.pitch.to_radians().sin(), + a.yaw.to_radians().cos() * a.pitch.to_radians().cos(), + ) + .normalize_or(dir) + } else { + dir + }; + let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08; + let upv = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08; + let (u1, v1) = ( + r.u0 + (r.u1 - r.u0) * 0.5, + r.v0 + (r.v1 - r.v0) * (5.0 / 32.0), + ); + for off in [side, upv] { + let q = [ + c - dir * 0.25 - off, + c + dir * 0.25 - off, + c + dir * 0.25 + off, + c - dir * 0.25 + off, + ]; + for (v, uv) in q + .iter() + .zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]]) + { + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } + } + continue; + } + let Some(name) = a.item_sprite() else { + continue; + }; + let Some(r) = atlas.sprites.get(name).copied() else { + continue; + }; + let s = 0.25 * a.sprite_scale(); + for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] + .iter() + .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) + { + let v = c + right * k.0 * s + up * k.1 * s; + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } + } + } +} +fn eat_sound(s: Species) -> &'static str { + match s { + Species::Pig => "entity.pig.eat", + Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat", + Species::Goat => "entity.goat.eat", + Species::Fox => "entity.fox.eat", + Species::Cat => "entity.cat.eat", + Species::Panda => "entity.panda.eat", + _ => "entity.generic.eat", + } +} +/// Mob.getBaseExperienceReward +fn experience_reward(m: &Mob, random: &mut impl RandomSource) -> u32 { + use Species as S; + match m.species() { + S::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute => 10, + S::Slime | S::MagmaCube => m.extra.size.max(1) as u32, + S::Endermite => 3, + S::Bat + | S::Squid + | S::GlowSquid + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Dolphin => 1 + random.next_int_bound(3).unwrap_or(0) as u32, + S::IronGolem | S::SnowGolem | S::Villager | S::WanderingTrader => 0, + _ if m.hostile() => { + 5 + if m.extra.main_hand.is_some() { + 1 + random.next_int_bound(3).unwrap_or(0) as u32 + } else { + 0 + } + } + _ if m.is_baby() => 0, + _ => 1 + random.next_int_bound(3).unwrap_or(0) as u32, + } +} +/// Entity.push between overlapping mobs (LivingEntity.pushEntities). +fn push_apart(mobs: &mut [Mob]) { + let n = mobs.len(); + for i in 0..n { + if !mobs[i].alive() { + continue; + } + let bi = mobs[i].bounds(); + for j in (i + 1)..n { + if !mobs[j].alive() || !bi.intersects(mobs[j].bounds()) { + continue; + } + let (dx, dz) = ( + mobs[j].position.x - mobs[i].position.x, + mobs[j].position.z - mobs[i].position.z, + ); + let mut dd = dx.abs().max(dz.abs()); + if dd >= 0.01 { + dd = dd.sqrt(); + let (mut xa, mut za) = (dx / dd, dz / dd); + let inv = (1.0 / dd).min(1.0); + xa *= inv * 0.05; + za *= inv * 0.05; + mobs[i].velocity.x -= xa; + mobs[i].velocity.z -= za; + mobs[j].velocity.x += xa; + mobs[j].velocity.z += za; + } + } + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 3caf4b445..8f670515c 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -54,7 +54,7 @@ pub struct Items { pub item_tags: HashMap>, loot: HashMap, } -fn load_tags(root: &Path, kind: &str) -> Result>> { +pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>> { let dir = root.join(format!("data/minecraft/tags/{kind}")); let mut raw: HashMap> = HashMap::new(); fn walk(dir: &Path, base: &Path, raw: &mut HashMap>) -> Result<()> { @@ -184,17 +184,22 @@ impl Items { order.push(id); } let mut loot = HashMap::new(); - for kind in ["blocks", "entities"] { - let dir = root.join(format!("data/minecraft/loot_table/{kind}")); - for entry in fs::read_dir(&dir)?.flatten() { + // Every loot table, keyed by its id (blocks/stone, entities/sheep/white, + // gameplay/chicken_lay, shearing/sheep/red...). + fn walk_loot(dir: &Path, base: &Path, loot: &mut HashMap) -> Result<()> { + for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); - if p.extension().is_some_and(|e| e == "json") - && let Some(stem) = p.file_stem().and_then(|s| s.to_str()) - { - loot.insert(format!("minecraft:{kind}/{stem}"), serde_json::from_slice(&fs::read(&p)?)?); + if p.is_dir() { + walk_loot(&p, base, loot)?; + } else if p.extension().is_some_and(|e| e == "json") { + let id = p.strip_prefix(base)?.with_extension("").to_string_lossy().replace('\\', "/"); + loot.insert(format!("minecraft:{id}"), serde_json::from_slice(&fs::read(&p)?)?); } } + Ok(()) } + let loot_root = root.join("data/minecraft/loot_table"); + walk_loot(&loot_root, &loot_root, &mut loot)?; Ok(Self { items, order, @@ -269,6 +274,13 @@ impl Items { ctx.evaluate(table, random) } /// Evaluate an entity's loot table (`minecraft:entities/`). + /// Evaluate any loot table by id (e.g. `minecraft:gameplay/chicken_lay`). + pub fn loot_table(&self, id: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec { + let Some(table) = self.loot.get(id) else { return vec![] }; + let empty = BTreeMap::new(); + let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player }; + ctx.evaluate(table, random) + } pub fn entity_drops(&self, entity: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec { let name = entity.trim_start_matches("minecraft:"); let Some(table) = self.loot.get(&format!("minecraft:entities/{name}")) else { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 00265cade..ee4135429 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -29,6 +29,7 @@ pub mod models; pub mod motion; pub mod particles; pub mod pose; +pub mod projectiles; pub mod save; pub mod settings; pub mod sprint; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 047d99d5a..682ae8606 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1,13 +1,29 @@ -//! Mobs: entity types (dimensions and default attributes exported from vanilla), -//! models (vanilla `LayerDefinitions` baked part trees), `LivingEntity.travel` -//! movement with step-up and jumping, and goal-style AI for the common -//! overworld mobs (strolling, panicking, chasing, melee, creeper swelling). -use crate::{ - blocks::{BlockFacts, Fluid}, - collisions::SceneCollisions, - mesher::Vertex, - world::World, -}; +//! Mobs: entity types (dimensions and default attributes exported from +//! vanilla), models (vanilla `LayerDefinitions` baked part trees) and the +//! `Mob` entity with vanilla's AI framework: goal and target selectors with +//! priorities and control flags (`goals`), A* pathfinding with walk, swim, +//! fly and amphibious node evaluators (`path`, `nav`), move/look/jump/body +//! controls (`control`), `LivingEntity` physics (`living`) and per-species +//! behaviour, models, animations and sounds. +pub mod ai; +pub mod anim; +pub mod data; +pub mod control; +pub mod farm; +pub mod goals; +pub mod hostile; +pub mod keyframes; +pub mod living; +pub mod nav; +pub mod path; +pub mod render; +pub mod species; +pub mod spawning; +pub mod undead; +mod world; + +use crate::{blocks::BlockFacts, mesher::Vertex, world::World}; +pub use data::MobData; use horizon_core::{ geometry::{Aabb, Vec3}, random::{LegacyRandom, RandomSource}, @@ -61,6 +77,7 @@ impl Part { Self { name: name.to_owned(), pose: p, polygons, children } } } +/// Kept for callers of the earlier simple AI; species now select behaviour. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Brain { Passive, @@ -70,31 +87,86 @@ pub enum Brain { Spider, Creeper, } -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Anim { - Quadruped, - Humanoid { zombie_arms: bool }, - Creeper, - Spider, - Chicken, +/// Model animation family (vanilla `EntityModel.setupAnim` implementations). +pub use anim::Anim; +pub use species::Species; + +/// Per-type behaviour switches derived from vanilla classes and tags. +#[derive(Clone, Copy, Debug, Default)] +pub struct Flags { + /// WaterAnimal / fish: not affected by fluid physics (swims with its own control). + pub aquatic_swimmer: bool, + pub fall_immune: bool, + /// FlyingMob-style travel (ghast, phantom): travelFlying without gravity. + pub flying: bool, + /// Spiders: onClimbable while colliding horizontally. + pub climber: bool, + /// Striders stand on lava. + pub lava_walker: bool, + /// LivingEntity.omnidirectionalAirMover (bees, parrots, bats, allays). + pub omnidirectional: bool, + pub fire_immune: bool, + /// EntityTypeTags.BURN_IN_DAYLIGHT + pub burns_in_day: bool, + pub undead: bool, + pub breathes_water: bool, + /// Drowns out of water (fish, squid, dolphins after their air runs out). + pub needs_water: bool, + /// Hurt by water (endermen, blazes, striders out of lava, snow golems). + pub water_sensitive: bool, + pub animal: bool, } #[derive(Clone, Debug)] pub struct MobType { pub id: String, + pub species: Species, pub width: f64, pub height: f64, pub eye_height: f64, pub category: String, pub max_health: f32, pub speed: f64, + pub flying_speed: f64, pub attack_damage: f32, + pub attack_knockback: f64, pub follow_range: f64, pub step_height: f64, + pub armor: f32, + pub armor_toughness: f32, + pub knockback_resistance: f64, + pub jump_strength: f64, + pub gravity: f64, + pub safe_fall_distance: f64, + pub fall_damage_multiplier: f64, + pub water_efficiency: f64, + pub water_slowdown: f32, + /// Air speed for travelFlying mobs (ghast 0.02, phantom 0.2). + pub air_speed: f32, + pub baby_scale: f64, + pub head_rot_speed: f32, + pub max_head_x_rot: f32, + pub max_head_y_rot: f32, + pub ambient_interval: i32, + pub flags: Flags, pub model: Arc, + /// Every baked layer of this entity's models keyed by `model#layer` + /// (e.g. `sheep#wool`, `zombie_baby#main`). + pub layers: HashMap>, pub texture: String, pub brain: Brain, pub anim: Anim, + /// Ambient, hurt and death sound events (without the namespace). pub sounds: [&'static str; 3], + pub step_sound: Option<&'static str>, + /// Animal.isFood items (resolved from the item tag). + pub food: Arc<[String]>, + /// TemptGoal items when they differ from the food. + pub tempt: Arc<[String]>, +} +impl MobType { + pub fn layer(&self, key: &str) -> Option<&Arc> { + self.layers.get(key) + } } pub struct MobTypes { pub types: HashMap, @@ -103,57 +175,74 @@ impl MobTypes { pub fn load(root: &Path) -> crate::Result { let types: Value = serde_json::from_slice(&fs::read(root.join("entity-types.json"))?)?; let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?; - // Vanilla renderers' default texture per supported mob. - let table: [(&str, &str, Brain, Anim, [&str; 3]); 9] = [ - ("pig", "entity/pig/pig_temperate", Brain::Passive, Anim::Quadruped, ["entity.pig.ambient", "entity.pig.hurt", "entity.pig.death"]), - ("cow", "entity/cow/cow_temperate", Brain::Passive, Anim::Quadruped, ["entity.cow.ambient", "entity.cow.hurt", "entity.cow.death"]), - ("sheep", "entity/sheep/sheep", Brain::Passive, Anim::Quadruped, ["entity.sheep.ambient", "entity.sheep.hurt", "entity.sheep.death"]), - ("chicken", "entity/chicken/chicken_temperate", Brain::Chicken, Anim::Chicken, ["entity.chicken.ambient", "entity.chicken.hurt", "entity.chicken.death"]), - ("zombie", "entity/zombie/zombie", Brain::Zombie, Anim::Humanoid { zombie_arms: true }, ["entity.zombie.ambient", "entity.zombie.hurt", "entity.zombie.death"]), - ("skeleton", "entity/skeleton/skeleton", Brain::Skeleton, Anim::Humanoid { zombie_arms: false }, ["entity.skeleton.ambient", "entity.skeleton.hurt", "entity.skeleton.death"]), - ("spider", "entity/spider/spider", Brain::Spider, Anim::Spider, ["entity.spider.ambient", "entity.spider.hurt", "entity.spider.death"]), - ("creeper", "entity/creeper/creeper", Brain::Creeper, Anim::Creeper, ["entity.creeper.primed", "entity.creeper.hurt", "entity.creeper.death"]), - ("cave_spider", "entity/spider/cave_spider", Brain::Spider, Anim::Spider, ["entity.spider.ambient", "entity.spider.hurt", "entity.spider.death"]), - ]; + let item_tags = crate::items::load_tags(root, "item").unwrap_or_default(); + let tag = |name: &str| -> Arc<[String]> { + let mut v: Vec = item_tags.get(&format!("minecraft:{name}")).into_iter().flatten().cloned().collect(); + v.sort(); + v.into() + }; let mut out = HashMap::new(); - for (name, texture, brain, anim, sounds) in table { - let id = format!("minecraft:{name}"); + for def in species::ALL { + let id = format!("minecraft:{}", def.name); let t = &types[&id]; - let model_key = if name == "cave_spider" { "minecraft:cave_spider#main".to_owned() } else { format!("{id}#main") }; - let model_value = models.get(&model_key).or_else(|| models.get(&format!("{id}#main"))); - let Some(model) = model_value else { continue }; - let attr = |k: &str| t["attributes"][k].as_f64(); - let texture = if root.join(format!("assets/minecraft/textures/{texture}.png")).exists() { - texture.to_owned() - } else { - // Fall back to the first texture in the entity's folder. - let folder = texture.rsplit_once('/').map_or(texture, |(a, _)| a); - fs::read_dir(root.join(format!("assets/minecraft/textures/{folder}"))) - .ok() - .and_then(|d| { - let mut names: Vec = d.flatten().filter_map(|e| e.file_name().to_str().map(str::to_owned)).filter(|n| n.ends_with(".png") && !n.contains("baby")).collect(); - names.sort(); - names.first().map(|n| format!("{folder}/{}", n.trim_end_matches(".png"))) - }) - .unwrap_or_else(|| texture.to_owned()) - }; + if t.is_null() { + continue; + } + let model_key = format!("minecraft:{}", def.model); + let Some(model) = models.get(&model_key) else { continue }; + let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64(); + let mut layers = HashMap::new(); + if let Some(all) = models.as_object() { + for prefix in def.layer_prefixes() { + let start = format!("minecraft:{prefix}#"); + for (k, v) in all.iter().filter(|(k, _)| k.starts_with(&start)) { + layers.insert(k.trim_start_matches("minecraft:").to_owned(), Arc::new(Part::parse("root", v))); + } + } + } + let category = t["category"].as_str().unwrap_or("creature").to_owned(); + let speed = attr("movement_speed").unwrap_or(0.25); + let flags = def.flags(t["fire_immune"].as_bool().unwrap_or(false)); out.insert( id.clone(), MobType { + species: def.species, width: t["width"].as_f64().unwrap_or(0.6), height: t["height"].as_f64().unwrap_or(1.8), eye_height: t["eye_height"].as_f64().unwrap_or(1.6), - category: t["category"].as_str().unwrap_or("creature").to_owned(), - max_health: attr("minecraft:max_health").unwrap_or(10.0) as f32, - speed: attr("minecraft:movement_speed").unwrap_or(0.25), - attack_damage: attr("minecraft:attack_damage").unwrap_or(0.0) as f32, - follow_range: attr("minecraft:follow_range").unwrap_or(16.0), - step_height: attr("minecraft:step_height").unwrap_or(0.6), + max_health: attr("max_health").unwrap_or(10.0) as f32, + speed, + flying_speed: attr("flying_speed").unwrap_or(0.4), + attack_damage: attr("attack_damage").unwrap_or(0.0) as f32, + attack_knockback: attr("attack_knockback").unwrap_or(0.0), + follow_range: attr("follow_range").unwrap_or(16.0), + step_height: attr("step_height").unwrap_or(0.6), + armor: attr("armor").unwrap_or(0.0) as f32, + armor_toughness: attr("armor_toughness").unwrap_or(0.0) as f32, + knockback_resistance: attr("knockback_resistance").unwrap_or(0.0), + jump_strength: attr("jump_strength").unwrap_or(0.42), + gravity: attr("gravity").unwrap_or(0.08), + safe_fall_distance: attr("safe_fall_distance").unwrap_or(3.0), + fall_damage_multiplier: attr("fall_damage_multiplier").unwrap_or(1.0), + water_efficiency: attr("water_movement_efficiency").unwrap_or(0.0), + water_slowdown: def.water_slowdown(), + air_speed: def.air_speed(), + baby_scale: def.baby_scale(), + head_rot_speed: def.head_rot_speed(), + max_head_x_rot: def.max_head_x_rot(), + max_head_y_rot: def.max_head_y_rot(), + ambient_interval: def.ambient_interval(), + flags, model: Arc::new(Part::parse("root", model)), - texture, - brain, - anim, - sounds: sounds.map(|s| s), + layers, + texture: def.texture.to_owned(), + brain: def.brain(), + anim: def.anim, + sounds: def.sounds, + step_sound: def.step_sound, + food: def.food_tag().map(tag).unwrap_or_else(|| Arc::from(Vec::new())), + tempt: def.tempt_tag().or(def.food_tag()).map(tag).unwrap_or_else(|| Arc::from(Vec::new())), + category, id, }, ); @@ -161,6 +250,107 @@ impl MobTypes { Ok(Self { types: out }) } } +/// Who caused damage or is being targeted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Who { + Player, + Mob(u32), +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DamageKind { + PlayerAttack, + MobAttack, + Arrow, + Thrown, + Fireball, + Explosion, + Fall, + OnFire, + InFire, + Lava, + Drown, + Magic, + Sting, + Cactus, + Generic, + InWall, +} +/// A damage source: its type, the attacking entity and where it came from. +#[derive(Clone, Copy, Debug)] +pub struct Damage { + pub kind: DamageKind, + pub attacker: Option, + pub from: Option<[f64; 3]>, +} +impl Damage { + pub fn fall() -> Self { + Self { kind: DamageKind::Fall, attacker: None, from: None } + } + pub fn of(kind: DamageKind) -> Self { + Self { kind, attacker: None, from: None } + } + pub fn player(from: [f64; 3]) -> Self { + Self { kind: DamageKind::PlayerAttack, attacker: Some(Who::Player), from: Some(from) } + } + pub fn mob(id: u32, from: [f64; 3]) -> Self { + Self { kind: DamageKind::MobAttack, attacker: Some(Who::Mob(id)), from: Some(from) } + } + /// DamageTypeTags.PANIC_CAUSES + pub fn causes_panic(&self) -> bool { + !matches!(self.kind, DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall) + } + /// DamageTypeTags.BYPASSES_ARMOR + pub fn bypasses_armor(&self) -> bool { + matches!(self.kind, DamageKind::Fall | DamageKind::OnFire | DamageKind::Drown | DamageKind::Magic | DamageKind::InWall | DamageKind::Generic) + } + pub fn is_fire(&self) -> bool { + matches!(self.kind, DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball) + } + pub fn is_projectile(&self) -> bool { + matches!(self.kind, DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball) + } +} +/// Species-specific persistent state (variants, colours, taming, ageing...). +#[derive(Clone, Debug, Default)] +pub struct Extra { + /// AgeableMob.age: negative while a baby. + pub age: i32, + pub in_love: i32, + pub love_player: bool, + /// Texture/model variant index (cat type, horse colour, rabbit type...). + pub variant: u8, + /// Secondary variant (horse markings, tropical fish pattern colours, panda hidden gene). + pub variant2: u8, + pub variant3: u8, + /// Dye colour id (sheep wool, collars). + pub color: u8, + pub sheared: bool, + pub saddled: bool, + pub chested: bool, + pub tame: bool, + pub sitting: bool, + /// Slime/magma cube size (0 = not sized). + pub size: i32, + /// Sheep eat-grass / iron golem attack / ravager animation ticks. + pub anim_ticks: i32, + pub egg_time: i32, + pub anger: i32, + pub carried: Option, + pub charged: bool, + pub levitation: i32, + /// Held item ids (main hand, off hand) and head item. + pub main_hand: Option>, + pub off_hand: Option>, + pub head: Option>, + pub using_item: i32, + pub flag: bool, + pub flag2: bool, + pub counter: i32, + pub counter2: i32, + pub home: Option<[i32; 3]>, + pub point: Option<[f64; 3]>, + pub vector: [f64; 3], +} #[derive(Clone, Debug)] pub struct Mob { pub id: u32, @@ -168,13 +358,19 @@ pub struct Mob { pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, + /// Entity.yRot (movement facing). pub yaw: f32, pub previous_yaw: f32, pub body_yaw: f32, pub previous_body_yaw: f32, + pub head_yaw: f32, + pub previous_head_yaw: f32, + /// Entity.xRot pub head_pitch: f32, + pub previous_head_pitch: f32, pub on_ground: bool, pub horizontal_collision: bool, + pub vertical_collision_below: bool, pub health: f32, pub hurt_time: i32, pub invulnerable: i32, @@ -183,48 +379,127 @@ pub struct Mob { pub limb_position: f32, pub limb_speed: f32, pub previous_limb_speed: f32, - pub target: Option<[f64; 3]>, - pub speed_modifier: f64, - pub panic: i32, - pub attack_cooldown: i32, pub swell: i32, pub previous_swell: i32, pub ambient_timer: i32, pub fall_distance: f64, pub persistent: bool, - pub idle: u32, + pub random: LegacyRandom, + pub ai: Box, + pub extra: Extra, + pub fluids: living::Fluids, + pub no_gravity: bool, + pub climbing: bool, + pub fire_ticks: i32, + pub air: i32, + pub last_hurt: f32, + pub last_damage: Option<(Damage, i64)>, + /// Set by `remove`: the mob disappears without dying (conversion, despawn, pickup). + pub removed: bool, + /// Client-side animation clocks (attack swing, eating, shaking...). + pub anim: anim::AnimState, } /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), + /// A sound event id that is not a static string (variant sounds). + SoundId(String, [f64; 3], f32, f32), AttackPlayer(f32, [f64; 3]), Shoot([f64; 3], [f64; 3]), Explode([f64; 3], f32), + /// Melee or ranged damage to another mob. + AttackMob { target: u32, amount: f32, source: Damage }, + /// Set another mob's attack target (HurtByTargetGoal alerts). + SetTarget { mob: u32, target: Who }, + Projectile(crate::projectiles::Projectile), + /// Spawn a new mob (breeding, slime splitting, chicken eggs...). + Spawn(Box), + /// Spawn a mob by type id at a position (conversions, splits). + SpawnKind { kind: String, at: [f64; 3], setup: SpawnSetup }, + DropItem { item: Arc, count: u32, at: [f64; 3] }, + SetBlock { pos: [i32; 3], state: horizon_world::registry::BlockStateId }, + /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). + BreakBlock { pos: [i32; 3], drop: bool }, + Particles { kind: &'static str, at: [f64; 3], count: u32 }, + Experience { at: [f64; 3], amount: u32 }, + /// Apply an effect to the player (witch potions, bee stings, cave spider poison). + EffectPlayer { effect: &'static str, ticks: i32, amplifier: i32 }, + /// Set an entity on fire. + Ignite { target: Who, seconds: i32 }, + /// Two animals bred: the game spawns the baby and resets the partner. + Breed { parent: u32, partner: u32 }, + /// Replace a block by name (sheep turning grass to dirt), optionally with + /// the destroy effect. + SetBlockName { pos: [i32; 3], name: &'static str, effect: bool }, + /// Drop the loot of a gift table (chicken eggs, armadillo scutes). + GiftLoot { table: &'static str, at: [f64; 3] }, +} +/// How a spawned-by-kind mob should be set up. +#[derive(Clone, Debug, Default)] +pub struct SpawnSetup { + pub baby: bool, + pub size: i32, + pub yaw: f32, + pub velocity: [f64; 3], + pub health: Option, + pub persistent: bool, + pub variant: Option, +} +/// A snapshot of another entity mobs can see this tick. +#[derive(Clone, Debug)] +pub struct Seen { + pub id: u32, + pub species: Species, + pub position: Vec3, + pub bounds: Aabb, + pub eye_y: f64, + pub alive: bool, + pub baby: bool, + pub in_love: bool, + pub tame: bool, + pub hostile: bool, + pub target: Option, + pub health: f32, + pub variant: u8, +} +/// The player as mobs see it. +#[derive(Clone, Debug)] +pub struct PlayerView { + pub position: Vec3, + pub bounds: Aabb, + pub eye: [f64; 3], + pub alive: bool, + pub creative: bool, + pub sneaking: bool, + pub look: [f64; 3], + pub main_hand: Option>, + pub off_hand: Option>, + pub head: Option>, + pub armor_cover: f32, } pub struct MobWorld<'a> { pub world: &'a World, pub facts: &'a BlockFacts, pub collision: &'a BlockCollisionRegistry<'a>, - pub player: Option<([f64; 3], bool)>, + pub data: &'a MobData, + pub player: Option, + pub others: &'a [Seen], pub daylight: bool, -} -fn wrap(a: f32) -> f32 { - let mut a = a % 360.0; - if a >= 180.0 { - a -= 360.0; - } - if a < -180.0 { - a += 360.0; - } - a + pub game_time: i64, + pub day_time: i64, + pub raining: bool, + pub thundering: bool, + pub nether: bool, + pub block_tags: &'a HashMap>, } impl Mob { pub fn new(id: u32, kind: Arc, position: Vec3, yaw: f32) -> Self { - Self { + let mut random = LegacyRandom::new(i64::from(id).wrapping_mul(0x5DEE_CE66D) ^ (position.x.to_bits() as i64) ^ (position.z.to_bits() as i64).rotate_left(17)); + let _ = random.next_int(); + let mut mob = Self { id, health: kind.max_health, - kind, position, previous: position, velocity: Vec3::ZERO, @@ -232,9 +507,13 @@ impl Mob { previous_yaw: yaw, body_yaw: yaw, previous_body_yaw: yaw, + head_yaw: yaw, + previous_head_yaw: yaw, head_pitch: 0.0, + previous_head_pitch: 0.0, on_ground: false, horizontal_collision: false, + vertical_collision_below: false, hurt_time: 0, invulnerable: 0, death_time: 0, @@ -242,23 +521,33 @@ impl Mob { limb_position: 0.0, limb_speed: 0.0, previous_limb_speed: 0.0, - target: None, - speed_modifier: 1.0, - panic: 0, - attack_cooldown: 0, swell: 0, previous_swell: 0, - ambient_timer: -80, + ambient_timer: -kind.ambient_interval, fall_distance: 0.0, persistent: false, - idle: 0, - } + random, + ai: Box::default(), + extra: Extra::default(), + fluids: living::Fluids::default(), + no_gravity: false, + climbing: false, + fire_ticks: 0, + air: 300, + last_hurt: 0.0, + last_damage: None, + removed: false, + anim: anim::AnimState::default(), + kind, + }; + ai::register(&mut mob); + mob } pub fn bounds(&self) -> Aabb { - let w = self.kind.width / 2.0; + let w = f64::from(self.width()) / 2.0; Aabb::new( Vec3::new(self.position.x - w, self.position.y, self.position.z - w), - Vec3::new(self.position.x + w, self.position.y + self.kind.height, self.position.z + w), + Vec3::new(self.position.x + w, self.position.y + f64::from(self.height()), self.position.z + w), ) } pub fn alive(&self) -> bool { @@ -267,357 +556,123 @@ impl Mob { pub fn hostile(&self) -> bool { self.kind.category == "monster" } - /// LivingEntity.hurt with invulnerability frames and knockback. - pub fn hurt(&mut self, amount: f32, from: Option<[f64; 3]>, random: &mut LegacyRandom) -> bool { - if !self.alive() || self.invulnerable > 10 { + pub fn species(&self) -> Species { + self.kind.species + } + /// The player hit this mob (melee): LivingEntity.hurt with knockback. + pub fn hurt(&mut self, amount: f32, from: Option<[f64; 3]>, _random: &mut LegacyRandom) -> bool { + let source = match from { + Some(f) => Damage::player(f), + None => Damage::of(DamageKind::Generic), + }; + self.damage(amount, source) + } + /// LivingEntity.hurtServer: invulnerability frames, armor, knockback and + /// the last-hurt-by bookkeeping goals read. + pub fn damage(&mut self, amount: f32, source: Damage) -> bool { + if !self.alive() || self.removed { return false; } - self.health -= amount; - self.invulnerable = 20; - self.hurt_time = 10; - if let Some(f) = from { - // LivingEntity.knockback(0.4, dx, dz) - let (dx, dz) = (f[0] - self.position.x, f[2] - self.position.z); - let len = (dx * dx + dz * dz).sqrt().max(1e-4); - let strength = 0.4; - self.velocity = Vec3::new( - self.velocity.x / 2.0 - dx / len * strength, - if self.on_ground { (self.velocity.y / 2.0 + strength).min(0.4) } else { self.velocity.y }, - self.velocity.z / 2.0 - dz / len * strength, - ); - if !self.hostile() { - self.panic = 60 + random.next_int_bound(40).unwrap_or(0); - self.target = None; + if source.is_fire() && (self.kind.flags.fire_immune) { + return false; + } + if !ai::accepts_damage(self, &source, amount) { + return false; + } + let mut amount = amount; + if !source.bypasses_armor() && self.kind.armor > 0.0 { + // CombatRules.getDamageAfterAbsorb + let armor = self.kind.armor; + let toughness = 2.0 + self.kind.armor_toughness / 4.0; + let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0); + amount *= 1.0 - effective / 25.0; + } + let mut knock = true; + if self.invulnerable as f32 > 10.0 { + if amount <= self.last_hurt { + return false; } + self.health -= amount - self.last_hurt; + self.last_hurt = amount; + knock = false; + } else { + self.last_hurt = amount; + self.invulnerable = 20; + self.health -= amount; + self.hurt_time = 10; + } + self.last_damage = Some((source, i64::from(self.age))); + if let Some(who) = source.attacker { + self.ai.last_hurt_by = Some(who); + self.ai.last_hurt_by_time = self.age as i32; + if who == Who::Player { + self.ai.last_hurt_by_player = 100; + } + } + if knock + && let Some(f) = source.from + && !matches!(source.kind, DamageKind::Explosion) + { + let (dx, dz) = (f[0] - self.position.x, f[2] - self.position.z); + self.knockback(0.4, dx, dz); + } + ai::after_hurt(self, &source); + if self.health <= 0.0 { + self.health = 0.0; } true } - fn random_target(&self, random: &mut LegacyRandom, w: &MobWorld, radius: i32) -> Option<[f64; 3]> { - // DefaultRandomPos.getPos: ten tries, prefer walkable spots. - for _ in 0..10 { - let x = self.position.x.floor() as i32 + random.next_int_bound(2 * radius + 1).ok()? - radius; - let z = self.position.z.floor() as i32 + random.next_int_bound(2 * radius + 1).ok()? - radius; - let mut y = self.position.y.floor() as i32 + random.next_int_bound(15).ok()? - 7; - if !w.world.loaded(x, z) { - continue; - } - let solid = |y: i32| w.facts.get(w.world.block(x, y, z)).full_collision; - while y > crate::chunk::MIN_Y && !solid(y - 1) { - y -= 1; - } - while solid(y) && y < 319 { - y += 1; - } - let below = w.facts.get(w.world.block(x, y - 1, z)); - if below.fluid != Fluid::None || &*below.name == "minecraft:lava" { - continue; - } - return Some([f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + /// LivingEntity.knockback(power, xd, zd) towards the negative direction. + pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) { + let power = power * (1.0 - self.kind.knockback_resistance); + if power <= 0.0 { + return; } - None + while xd * xd + zd * zd < 1.0e-5 { + xd = (self.random.next_double() - self.random.next_double()) * 0.01; + zd = (self.random.next_double() - self.random.next_double()) * 0.01; + } + let len = (xd * xd + zd * zd).sqrt(); + let (kx, kz) = (xd / len * power, zd / len * power); + self.velocity = Vec3::new( + self.velocity.x / 2.0 - kx, + if self.on_ground { (self.velocity.y / 2.0 + power).min(0.4) } else { self.velocity.y }, + self.velocity.z / 2.0 - kz, + ); } - pub fn tick(&mut self, w: &MobWorld, random: &mut LegacyRandom, events: &mut Vec) -> bool { - self.previous = self.position; - self.previous_yaw = self.yaw; - self.previous_body_yaw = self.body_yaw; - self.previous_swell = self.swell; - self.age += 1; - if self.hurt_time > 0 { - self.hurt_time -= 1; - } - if self.invulnerable > 0 { - self.invulnerable -= 1; - } - if !self.alive() { - self.death_time += 1; - self.velocity = Vec3::new(0.0, self.velocity.y - 0.08, 0.0); - self.travel(w, 0.0); - return self.death_time < 20; - } - let center = [self.position.x, self.position.y + self.kind.eye_height, self.position.z]; - // Ambient sounds (Mob.playAmbientSound every ~80 ticks on average). - self.ambient_timer += 1; - if random.next_int_bound(1000).unwrap_or(1) < self.ambient_timer { - self.ambient_timer = -80; - if self.kind.brain != Brain::Creeper { - let pitch = (random.next_float() - random.next_float()) * 0.2 + 1.0; - events.push(MobEvent::Sound(self.kind.sounds[0], center, 1.0, pitch)); - } - } - let mut forward = 0.0f32; - let player = w.player.filter(|(_, alive)| *alive).map(|(p, _)| p); - let aggressive = match self.kind.brain { - Brain::Zombie | Brain::Skeleton | Brain::Creeper => true, - Brain::Spider => !w.daylight, - _ => false, - }; - let chase = if aggressive { - player.filter(|p| self.distance_to(*p) < self.kind.follow_range.min(24.0)) - } else { - None - }; - if self.attack_cooldown > 0 { - self.attack_cooldown -= 1; - } - if let Some(p) = chase { - let d = self.distance_to(p); - self.face(p, 30.0); - match self.kind.brain { - Brain::Creeper => { - // SwellGoal: fuse within 3 blocks, defuse beyond 7. - if d < 3.0 { - if self.swell == 0 { - events.push(MobEvent::Sound("entity.creeper.primed", center, 1.0, 0.5)); - } - self.swell += 1; - if self.swell >= 30 { - events.push(MobEvent::Explode([self.position.x, self.position.y, self.position.z], 3.0)); - self.health = 0.0; - self.death_time = 20; - return false; - } - } else { - self.swell = (self.swell - 1).max(0); - forward = 1.0; - } - } - Brain::Skeleton => { - // RangedBowAttackGoal: keep ~15 blocks, shoot every 20-40 ticks. - if d > 12.0 { - forward = 1.0; - } - if d < 15.0 && self.attack_cooldown == 0 { - events.push(MobEvent::Shoot(center, p)); - self.attack_cooldown = 20 + random.next_int_bound(20).unwrap_or(0); - } - } - _ => { - forward = 1.0; - let reach = self.kind.width * 2.0 * self.kind.width * 2.0 + 0.6; - let dx = p[0] - self.position.x; - let dz = p[2] - self.position.z; - if dx * dx + dz * dz <= reach.max(2.0) && (p[1] - self.position.y).abs() < 2.0 && self.attack_cooldown == 0 { - events.push(MobEvent::AttackPlayer(self.kind.attack_damage.max(2.0), [self.position.x, self.position.y, self.position.z])); - self.attack_cooldown = 20; - } - } - } - self.speed_modifier = 1.0; - self.idle = 0; - } else { - self.swell = (self.swell - 1).max(0); - if self.panic > 0 { - self.panic -= 1; - if self.target.is_none() || random.next_int_bound(20).unwrap_or(1) == 0 { - self.target = self.random_target(random, w, 5); - } - self.speed_modifier = if self.kind.brain == Brain::Chicken { 1.4 } else { 1.25 }; - } else if self.target.is_none() && random.next_int_bound(120).unwrap_or(1) == 0 { - // RandomStrollGoal(speed 1.0, interval 120) - self.target = self.random_target(random, w, 10); - self.speed_modifier = 1.0; - } - if let Some(t) = self.target { - let dx = t[0] - self.position.x; - let dz = t[2] - self.position.z; - if dx * dx + dz * dz < 0.5 || (self.horizontal_collision && random.next_int_bound(40).unwrap_or(1) == 0) { - self.target = None; - } else { - self.face(t, 30.0); - forward = 1.0; - } - } else if let Some(p) = player - && self.distance_to(p) < 8.0 - && random.next_float() < 0.02 - { - // LookAtPlayerGoal. - self.face(p, 10.0); - } - self.idle += 1; - } - // Body follows head (BodyRotationControl). - self.body_yaw += wrap(self.yaw - self.body_yaw) * 0.3; - // Daylight burning for undead. - if matches!(self.kind.brain, Brain::Zombie | Brain::Skeleton) && w.daylight && self.age % 20 == 0 { - let x = self.position.x.floor() as i32; - let z = self.position.z.floor() as i32; - let y = (self.position.y + self.kind.eye_height).floor() as i32; - if w.world.light(x, y, z) >> 4 == 15 && w.facts.get(w.world.block(x, y, z)).fluid == Fluid::None { - self.hurt(1.0, None, random); - } - } - let speed = (self.kind.speed * self.speed_modifier) as f32 * forward; - self.travel(w, speed); - // Limb animation (WalkAnimationState.update). - let dx = self.position.x - self.previous.x; - let dz = self.position.z - self.previous.z; - let moved = ((dx * dx + dz * dz).sqrt() * 4.0).min(1.0) as f32; - self.previous_limb_speed = self.limb_speed; - self.limb_speed += (moved - self.limb_speed) * 0.4; - self.limb_position += self.limb_speed; - // Despawn far monsters. - if self.hostile() && !self.persistent - && let Some(p) = player - { - let d = self.distance_to(p); - if d > 128.0 || (d > 32.0 && self.idle > 600 && random.next_int_bound(800).unwrap_or(1) == 0) { - return false; - } - } - self.position.y > -128.0 + /// One game tick. Returns false once the mob should be removed. + pub fn tick(&mut self, w: &MobWorld, _random: &mut LegacyRandom, events: &mut Vec) -> bool { + ai::tick(self, w, events) } - fn distance_to(&self, p: [f64; 3]) -> f64 { + pub fn distance_to(&self, p: [f64; 3]) -> f64 { let d = [p[0] - self.position.x, p[1] - self.position.y, p[2] - self.position.z]; (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() } - fn face(&mut self, p: [f64; 3], max: f32) { - let dx = p[0] - self.position.x; - let dz = p[2] - self.position.z; - let target = (dz.atan2(dx).to_degrees() as f32) - 90.0; - self.yaw += wrap(target - self.yaw).clamp(-max, max); + pub fn distance_sqr(&self, p: Vec3) -> f64 { + (p.x - self.position.x).powi(2) + (p.y - self.position.y).powi(2) + (p.z - self.position.z).powi(2) } - /// LivingEntity.travel (ground/air friction, gravity, step-up and jumping). - fn travel(&mut self, w: &MobWorld, speed: f32) { - let x = self.position.x.floor() as i32; - let z = self.position.z.floor() as i32; - let below = w.world.block(x, (self.position.y - 0.5).floor() as i32, z); - let in_water = w.facts.get(w.world.block(x, (self.position.y + 0.2).floor() as i32, z)).fluid != Fluid::None; - let friction = if self.on_ground { w.facts.get(below).friction * 0.91 } else { 0.91 }; - let acceleration = if in_water { - 0.02 - } else if self.on_ground { - f64::from(speed) * (0.216_000_02 / f64::from(friction * friction * friction)) - } else { - 0.02 * f64::from(speed > 0.0) - }; - if speed > 0.0 { - let yaw = f64::from(self.yaw).to_radians(); - self.velocity.x += -yaw.sin() * acceleration; - self.velocity.z += yaw.cos() * acceleration; - // JumpControl: hop when blocked by a full block. - if self.horizontal_collision && self.on_ground { - self.velocity.y = 0.42; - } - } - if in_water { - if speed > 0.0 || self.kind.brain != Brain::Passive { - self.velocity.y += 0.04; - } - self.velocity.y = self.velocity.y.min(0.1); - } - let mut scene = SceneCollisions { world: w.world, binding: w.collision }; - let wanted = self.velocity; - let moved = scene - .resolve(self.bounds(), wanted, self.kind.step_height as f32, self.on_ground) - .unwrap_or(Vec3::ZERO); - self.position = Vec3::new(self.position.x + moved.x, self.position.y + moved.y, self.position.z + moved.z); - self.horizontal_collision = (moved.x - wanted.x).abs() > 1e-6 || (moved.z - wanted.z).abs() > 1e-6; - let vertical = (moved.y - wanted.y).abs() > 1e-6; - self.on_ground = vertical && wanted.y < 0.0; - if vertical { - self.velocity.y = 0.0; - } - if self.horizontal_collision { - if (moved.x - wanted.x).abs() > 1e-6 { - self.velocity.x = 0.0; - } - if (moved.z - wanted.z).abs() > 1e-6 { - self.velocity.z = 0.0; - } - } - // Spiders climb walls. - if self.kind.brain == Brain::Spider && self.horizontal_collision { - self.velocity.y = 0.2; - } - if self.on_ground { - if self.fall_distance > 3.0 { - self.health -= (self.fall_distance - 3.0).ceil() as f32; - self.hurt_time = 10; - } - self.fall_distance = 0.0; - } else if moved.y < 0.0 { - self.fall_distance -= moved.y; - } - let gravity = if self.kind.brain == Brain::Chicken && self.velocity.y < 0.0 { 0.0 } else { 0.08 }; - if !in_water { - self.velocity.y -= gravity; - } - if self.kind.brain == Brain::Chicken && !self.on_ground && self.velocity.y < 0.0 { - // Chicken flapping: slow fall. - self.velocity.y *= 0.6; - } - let drag = if in_water { 0.8 } else { f64::from(friction) }; - self.velocity = Vec3::new(self.velocity.x * drag, self.velocity.y * 0.98, self.velocity.z * drag); + /// Movement speed attribute bonus (baby zombies, sprinting modifiers). + pub fn speed_bonus(&self) -> f64 { + ai::speed_bonus(self) + } + pub fn center(&self) -> [f64; 3] { + [self.position.x, self.position.y + f64::from(self.height()) / 2.0, self.position.z] + } + pub fn sound(&self, event: &'static str, events: &mut Vec) { + let at = [self.position.x, self.eye_y(), self.position.z]; + events.push(MobEvent::Sound(event, at, 1.0, 1.0)); + } + /// Mob.playSound with LivingEntity.getVoicePitch. + pub fn voice(&mut self, event: &'static str, events: &mut Vec) { + let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 + if self.is_baby() { 1.5 } else { 1.0 }; + let at = [self.position.x, self.eye_y(), self.position.z]; + events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch)); } } /// Model geometry for a mob, posed for its animation state, as camera-relative /// vertices textured from the shared atlas. pub fn render(mob: &Mob, alpha: f32, camera: glam::DVec3, uv: [f32; 4], light: u32, out: &mut Vec) { - let a = f64::from(alpha); - let p = glam::DVec3::new( - mob.previous.x + (mob.position.x - mob.previous.x) * a, - mob.previous.y + (mob.position.y - mob.previous.y) * a, - mob.previous.z + (mob.position.z - mob.previous.z) * a, - ) - camera; - let body = mob.previous_body_yaw + wrap(mob.body_yaw - mob.previous_body_yaw) * alpha; - let head_yaw = wrap((mob.previous_yaw + wrap(mob.yaw - mob.previous_yaw) * alpha) - body); - let limb_speed = (mob.previous_limb_speed + (mob.limb_speed - mob.previous_limb_speed) * alpha).min(1.0); - let limb = mob.limb_position - mob.limb_speed * (1.0 - alpha); - let age = mob.age as f32 + alpha; - // LivingEntityRenderer: rotate 180-body, flip, lift 1.501. - let mut base = glam::Mat4::from_translation(p.as_vec3()) - * glam::Mat4::from_rotation_y((180.0 - body).to_radians()); - if mob.death_time > 0 { - let f = ((mob.death_time as f32 + alpha - 1.0) / 20.0 * 1.6).sqrt().min(1.0); - base *= glam::Mat4::from_rotation_z(f * 90.0_f32.to_radians()); - } - if mob.kind.brain == Brain::Creeper { - // CreeperRenderer.scale: swelling. - let s = (mob.previous_swell as f32 + (mob.swell - mob.previous_swell) as f32 * alpha) / 28.0; - let s = s.clamp(0.0, 1.0); - let wobble = 1.0 + (s * 100.0).sin() * s * 0.01; - let s4 = s * s * s * s; - let xz = (1.0 + s4 * 0.4) * wobble; - let y = (1.0 + s4 * 0.1) / wobble; - base *= glam::Mat4::from_scale(glam::Vec3::new(xz, y, xz)); - } - base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)) * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)); - let overlay = u32::from(mob.hurt_time > 0 || mob.death_time > 0); - let swing = |phase: f32| (limb * 0.6662 + phase).cos() * 1.4 * limb_speed; - let pose_for = |part: &Part| -> [f32; 9] { - let mut pose = part.pose; - match (&mob.kind.anim, part.name.as_str()) { - (_, "head") => { - pose[4] = head_yaw.to_radians(); - pose[3] += mob.head_pitch.to_radians(); - } - (Anim::Quadruped, "right_hind_leg") | (Anim::Quadruped, "left_front_leg") => pose[3] = swing(0.0), - (Anim::Quadruped, "left_hind_leg") | (Anim::Quadruped, "right_front_leg") => pose[3] = swing(std::f32::consts::PI), - (Anim::Chicken, "right_leg") => pose[3] = swing(0.0), - (Anim::Chicken, "left_leg") => pose[3] = swing(std::f32::consts::PI), - (Anim::Chicken, "right_wing") => pose[5] = (age * 0.3).sin().abs() * if mob.on_ground { 0.0 } else { 1.0 }, - (Anim::Chicken, "left_wing") => pose[5] = -(age * 0.3).sin().abs() * if mob.on_ground { 0.0 } else { 1.0 }, - (Anim::Humanoid { .. }, "right_leg") => pose[3] = (limb * 0.6662).cos() * 1.4 * limb_speed * 0.5 * 2.0 / 2.0 * 1.0, - (Anim::Humanoid { .. }, "left_leg") => pose[3] = (limb * 0.6662 + std::f32::consts::PI).cos() * 1.4 * limb_speed, - (Anim::Humanoid { zombie_arms: true }, "right_arm") | (Anim::Humanoid { zombie_arms: true }, "left_arm") => { - // AnimationUtils.animateZombieArms - pose[3] = -std::f32::consts::FRAC_PI_2 + (age * 0.067).sin() * 0.05; - } - (Anim::Humanoid { .. }, "right_arm") => pose[3] = (limb * 0.6662 + std::f32::consts::PI).cos() * 2.0 * limb_speed * 0.5, - (Anim::Humanoid { .. }, "left_arm") => pose[3] = (limb * 0.6662).cos() * 2.0 * limb_speed * 0.5, - (Anim::Creeper, "right_hind_leg") | (Anim::Creeper, "left_front_leg") => pose[3] = swing(0.0), - (Anim::Creeper, "left_hind_leg") | (Anim::Creeper, "right_front_leg") => pose[3] = swing(std::f32::consts::PI), - (Anim::Spider, name) if name.contains("leg") => { - let n: f32 = name.chars().filter(|c| c.is_ascii_digit()).collect::().parse().unwrap_or(0.0); - let phase = (n % 4.0) * std::f32::consts::FRAC_PI_2; - pose[4] += (limb * 0.6662 * 2.0 + phase).cos() * 0.4 * limb_speed; - pose[5] += (limb * 0.6662 + phase).sin().abs() * 0.4 * limb_speed; - } - _ => {} - } - pose - }; - render_model(&mob.kind.model, base, &pose_for, uv, light, overlay, out); + render::render_single(mob, alpha, camera, uv, light, out); } /// Load one baked model layer from `entity-models.json` (e.g. `minecraft:chest#main`). pub fn load_model(root: &Path, key: &str) -> Option { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs new file mode 100644 index 000000000..1aebaa162 --- /dev/null +++ b/crates/horizon-client/src/mobs/ai.rs @@ -0,0 +1,552 @@ +//! The per-tick mob update in vanilla order (`Entity.baseTick`, +//! `LivingEntity.baseTick/tick/aiStep`, `Mob.serverAiStep`) and the +//! dispatch to each species family's goals and special behaviour. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + control::{BodyRotation, LookControl, MoveControl}, + farm, + goals::{Cx, GoalSelector}, + hostile, + nav::Navigation, + path::{PATH_TYPES, Path}, + undead, +}; +use crate::blocks::Fluid; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +#[derive(Clone, Debug, Default)] +pub struct Ai { + pub goals: GoalSelector, + pub targets: GoalSelector, + pub nav: Navigation, + pub mov: MoveControl, + pub look: LookControl, + pub body: BodyRotation, + /// JumpControl.jump (requested this tick). + pub jump: bool, + /// LivingEntity.jumping + pub jumping: bool, + pub no_jump_delay: i32, + pub xxa: f32, + pub yya: f32, + pub zza: f32, + pub speed: f32, + pub target: Option, + pub last_hurt_by: Option, + pub last_hurt_by_time: i32, + /// Ticks left during which kills count as player kills. + pub last_hurt_by_player: i32, + pub no_action_time: i32, + pub aggressive: bool, + pub panicking: bool, + pub malus: [Option; PATH_TYPES], + /// A path computed in canUse and consumed by start. + pub pending_path: Option, + /// Sensing: line-of-sight results cached for one tick. + pub seen_cache: Vec<(Who, bool)>, + /// Swing animation progress (attackAnim) and ticks. + pub swing_time: i32, + pub swinging: bool, +} +impl Mob { + /// LivingEntity.swing + pub fn swing(&mut self) { + if !self.ai.swinging || self.ai.swing_time >= 3 || self.ai.swing_time < 0 { + self.ai.swing_time = -1; + self.ai.swinging = true; + } + } +} +pub fn register(m: &mut Mob) { + use Species as S; + match m.species() { + S::Pig | S::Cow | S::Mooshroom | S::Sheep | S::Chicken => farm::register(m), + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::Skeleton + | S::Stray + | S::Bogged + | S::WitherSkeleton => undead::register(m), + S::Creeper | S::Spider | S::CaveSpider => hostile::register(m), + _ => generic(m), + } +} +/// A fallback for species without bespoke goals yet: animals stroll and +/// panic, monsters hunt the player in melee. +fn generic(m: &mut Mob) { + use super::goals::*; + let hostile = m.hostile(); + let g = &mut m.ai.goals; + if hostile { + g.add(1, Float); + g.add(2, MeleeAttack::new(1.0, false)); + g.add(5, Stroll::avoiding_water(0.8)); + g.add(6, LookAtPlayer::new(8.0)); + g.add(6, RandomLookAround::default()); + m.ai.targets.add(1, HurtByTarget::new()); + m.ai.targets.add(2, NearestTarget::player(true)); + } else { + g.add(0, Float); + g.add(1, Panic::new(1.25)); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + } +} +/// One full entity tick. Returns false when the mob is gone. +pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { + if m.removed { + return false; + } + m.previous = m.position; + m.previous_yaw = m.yaw; + m.previous_body_yaw = m.body_yaw; + m.previous_head_yaw = m.head_yaw; + m.previous_head_pitch = m.head_pitch; + m.previous_swell = m.swell; + m.anim.begin_tick(); + m.age += 1; + m.ai.seen_cache.clear(); + if m.ai.last_hurt_by_player > 0 { + m.ai.last_hurt_by_player -= 1; + } + // Mob.tick pre-update hooks (Creeper.tick swells before super.tick). + match m.species() { + Species::Creeper => hostile::creeper_tick(m, events), + _ => {} + } + if m.removed { + return false; + } + base_tick(m, w, events); + if m.death_time >= 20 { + return false; + } + ai_step(m, w, events); + // Mob.tickHeadTurn -> BodyRotationControl.clientTick + if m.alive() { + m.body_rotation_tick(); + } + m.update_walk_animation(); + m.anim.end_tick(m.ai.swinging); + tick_swing(m); + if !m.alive() { + return true; + } + if !check_despawn(m, w) { + m.removed = true; + return false; + } + m.position.y > -128.0 +} +/// LivingEntity.updateSwingTime (6-tick swing duration). +fn tick_swing(m: &mut Mob) { + if m.ai.swinging { + m.ai.swing_time += 1; + if m.ai.swing_time >= 6 { + m.ai.swing_time = 0; + m.ai.swinging = false; + } + } else { + m.ai.swing_time = 0; + } + m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; +} +/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. +fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + m.fluids = w.fluids(m.bounds(), m.eye_y()); + // Fire: water extinguishes, lava ignites, burning hurts every second. + if m.fluids.in_water && m.fire_ticks > 0 { + m.fire_ticks = 0; + events.push(MobEvent::Sound( + "entity.generic.extinguish_fire", + m.center(), + 0.7, + 1.6 + (m.random.next_float() - m.random.next_float()) * 0.4, + )); + } + if m.fluids.in_lava && !m.kind.flags.fire_immune { + m.fire_ticks = m.fire_ticks.max(300); + m.damage(4.0, Damage::of(DamageKind::Lava)); + } + if m.fire_ticks > 0 { + if m.kind.flags.fire_immune { + m.fire_ticks = (m.fire_ticks - 4).max(0); + } else { + if m.fire_ticks % 20 == 0 && !m.fluids.in_lava { + m.damage(1.0, Damage::of(DamageKind::OnFire)); + } + m.fire_ticks -= 1; + } + } + if m.alive() { + // LivingEntity.baseTick: suffocation inside full blocks. + let (ex, ey, ez) = ( + m.position.x.floor() as i32, + m.eye_y().floor() as i32, + m.position.z.floor() as i32, + ); + let at_eye = w.facts.get(w.world.block(ex, ey, ez)); + if at_eye.full_collision && at_eye.solid_render && m.width() < 1.0 { + m.damage(1.0, Damage::of(DamageKind::InWall)); + } + // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). + if m.kind.flags.needs_water { + if !m.fluids.in_water { + m.air -= 1; + if m.air == -20 { + m.air = 0; + m.damage(2.0, Damage::of(DamageKind::Drown)); + } + } else { + m.air = 300; + } + } else if m.fluids.eye_in_water && !m.kind.flags.breathes_water { + m.air -= 1; + if m.air == -20 { + m.air = 0; + m.damage(2.0, Damage::of(DamageKind::Drown)); + } + } else if m.air < 300 { + m.air = (m.air + 4).min(300); + } + if m.kind.flags.water_sensitive + && (m.fluids.in_water || w.raining && w.can_see_sky(ex, ey, ez)) + { + m.damage(1.0, Damage::of(DamageKind::Drown)); + } + } + if m.hurt_time > 0 { + m.hurt_time -= 1; + } + if m.invulnerable > 0 { + m.invulnerable -= 1; + } + if !m.alive() { + m.death_time += 1; + } + // Mob.baseTick: ambient sounds. + if m.alive() { + let roll = m.random.next_int_bound(1000).unwrap_or(999); + let t = m.ambient_timer; + m.ambient_timer += 1; + if roll < t { + m.ambient_timer = -m.kind.ambient_interval; + play_ambient(m, w, events); + } + } +} +fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let sound = match m.species() { + Species::Zombie | Species::Husk if m.is_baby() => m.kind.sounds[0], + Species::Drowned if m.fluids.in_water => "entity.drowned.ambient_water", + Species::Enderman if m.ai.target.is_some() => "entity.enderman.scream", + Species::Wolf if m.ai.target.is_some() => "entity.wolf.growl", + Species::Wolf if m.random.next_int_bound(3).unwrap_or(1) == 0 => { + if m.extra.tame && m.health < m.kind.max_health / 2.0 { + "entity.wolf.whine" + } else { + "entity.wolf.pant" + } + } + Species::Cat if m.extra.tame && m.extra.in_love > 0 => "entity.cat.purr", + Species::Cat if !m.extra.tame => "entity.cat.stray_ambient", + Species::PolarBear if m.is_baby() => "entity.polar_bear.ambient_baby", + Species::Dolphin if !m.fluids.in_water => "entity.dolphin.ambient", + 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::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", + Species::Piglin if m.ai.target.is_some() => "entity.piglin.angry", + Species::Hoglin if m.ai.target.is_some() => "entity.hoglin.angry", + _ => m.kind.sounds[0], + }; + let _ = w; + if !sound.is_empty() { + m.voice(sound, events); + } +} +/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). +fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if m.ai.no_jump_delay > 0 { + m.ai.no_jump_delay -= 1; + } + let v = m.velocity; + m.velocity = Vec3::new( + if v.x.abs() < 0.003 { 0.0 } else { v.x }, + if v.y.abs() < 0.003 { 0.0 } else { v.y }, + if v.z.abs() < 0.003 { 0.0 } else { v.z }, + ); + m.ai.xxa *= 0.98; + m.ai.zza *= 0.98; + if m.alive() { + server_ai_step(m, w, events); + } else { + m.ai.jumping = false; + m.ai.xxa = 0.0; + m.ai.zza = 0.0; + } + m.handle_jumping(); + let input = Vec3::new( + f64::from(m.ai.xxa), + f64::from(m.ai.yya), + f64::from(m.ai.zza), + ); + m.travel(w, input, events); + // Spider.tick: climbing while pressed against a wall. + if m.kind.flags.climber { + m.climbing = m.horizontal_collision; + } + // AgeableMob.aiStep + if m.alive() { + if m.extra.age < 0 { + m.extra.age += 1; + } else if m.extra.age > 0 { + m.extra.age -= 1; + } + // Animal.aiStep + if m.extra.age != 0 { + m.extra.in_love = 0; + } + if m.extra.in_love > 0 { + m.extra.in_love -= 1; + if m.extra.in_love % 10 == 0 { + events.push(MobEvent::Particles { + kind: "heart", + at: [ + m.position.x, + m.position.y + f64::from(m.height()) + 0.5, + m.position.z, + ], + count: 1, + }); + } + } + } + // Mob.aiStep: undead burn in daylight. + if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) { + if m.extra.head.is_none() { + m.fire_ticks = m.fire_ticks.max(160); + } + } + species_ai_step(m, w, events); +} +fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { + if !w.daylight || w.nether { + return false; + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.eye_y().floor() as i32, + m.position.z.floor() as i32, + ); + let br = w.brightness(x, y, z); + let wet = m.fluids.in_water || w.raining && w.can_see_sky(x, y, z); + br > 0.5 && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 && !wet && w.can_see_sky(x, y, z) +} +/// Mob.serverAiStep +fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + m.ai.no_action_time += 1; + let tick_count = m.age as i64; + let id_based = tick_count + i64::from(m.id); + let mut targets = std::mem::take(&mut m.ai.targets); + let mut goals = std::mem::take(&mut m.ai.goals); + { + let mut cx = Cx { w, events }; + if id_based % 2 != 0 && tick_count > 1 { + targets.tick_running(m, &mut cx, false); + goals.tick_running(m, &mut cx, false); + } else { + targets.tick(m, &mut cx); + goals.tick(m, &mut cx); + } + } + m.ai.targets = targets; + m.ai.goals = goals; + m.nav_tick(w); + { + let mut cx = Cx { w, events }; + custom_server_ai_step(m, &mut cx); + } + m.move_control_tick(w); + m.look_control_tick(); + m.jump_control_tick(); +} +fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { + match m.species() { + Species::Sheep => {} + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::Skeleton + | Species::Stray + | Species::Bogged + | Species::WitherSkeleton => undead::custom_server_ai_step(m, cx), + _ => {} + } +} +fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + match m.species() { + Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Sheep => { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + } + _ => {} + } +} +/// Mob.checkDespawn (players are the only despawn reference). +fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { + let creature = m.kind.category == "creature"; + if m.persistent || creature && m.kind.flags.animal { + m.ai.no_action_time = 0; + return true; + } + let Some(p) = &w.player else { return true }; + let d = m.distance_sqr(p.position); + let despawn = if m.kind.category == "water_ambient" { + 64.0 + } else { + 128.0 + }; + if d > despawn * despawn { + return false; + } + if m.ai.no_action_time > 600 + && m.random.next_int_bound(800).unwrap_or(1) == 0 + && d > 32.0 * 32.0 + { + return false; + } + if d < 32.0 * 32.0 { + m.ai.no_action_time = 0; + } + true +} +/// Movement speed bonus multiplier (baby zombies are 50% faster, etc.). +pub fn speed_bonus(m: &Mob) -> f64 { + match m.species() { + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + | Species::Piglin + if m.is_baby() => + { + 1.5 + } + _ => 1.0, + } +} +pub fn sound_volume(m: &Mob) -> f32 { + match m.species() { + Species::Ghast => 5.0, + Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32, + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Bat => 0.1, + Species::Squid | Species::GlowSquid => 0.4, + Species::Horse | Species::Donkey | Species::Mule => 0.8, + _ => 1.0, + } +} +/// PathfinderMob.getWalkTargetValue (Animal and Monster overrides). +pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { + let light = || w.brightness(p[0], p[1], p[2]) - 0.5; + if m.hostile() + && !matches!( + m.species(), + Species::Slime | Species::MagmaCube | Species::Ghast | Species::Phantom + ) + { + return -light(); + } + if m.kind.flags.animal { + if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:grass_block" { + return 10.0; + } + return light(); + } + 0.0 +} +/// Species damage filters (LivingEntity.hurtServer overrides). +pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { + match m.species() { + Species::Enderman if source.is_projectile() => false, + Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider + if source.is_fire() => + { + false + } + _ => true, + } +} +/// Reactions after taking damage (sounds, anger). +pub fn after_hurt(m: &mut Mob, _source: &Damage) { + m.ai.no_action_time = 0; +} +/// Mob.doHurtTarget: attack damage (+ species extras) to the target. +pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { + let mut amount = m.kind.attack_damage; + let from = [m.position.x, m.position.y, m.position.z]; + let source = Damage::mob(m.id, from); + match m.species() { + // Difficulty NORMAL: cave spiders poison for 7 seconds. + Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: 7 * 20, + amplifier: 0, + }), + Species::Husk if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:hunger", + ticks: 140, + amplifier: 0, + }), + Species::WitherSkeleton if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:wither", + ticks: 200, + amplifier: 0, + }), + _ => {} + } + if amount <= 0.0 { + amount = 1.0; + } + // Zombies set their target on fire while burning (Zombie.doHurtTarget). + if m.fire_ticks > 0 && matches!(m.species(), Species::Zombie) && m.random.next_float() < 0.3 { + cx.events.push(MobEvent::Ignite { + target: who, + seconds: 2, + }); + } + match who { + Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)), + Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + target: id, + amount, + source, + }), + } + let _ = Fluid::None; +} +/// Mob.ate (sheep regrow wool, babies grow). +pub fn ate(m: &mut Mob) { + if m.species() == Species::Sheep { + m.extra.sheared = false; + if m.is_baby() { + // AgeableMob.ageUp(60) + m.extra.age = (m.extra.age + 60 * 20).min(0); + } + } +} +/// Species-specific travel (fish, squid, dolphins swim with their own rules). +pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec) -> bool { + let _ = (m, w, input, events); + false +} diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs new file mode 100644 index 000000000..b77a863f8 --- /dev/null +++ b/crates/horizon-client/src/mobs/anim.rs @@ -0,0 +1,453 @@ +//! Model animation: ports of each vanilla `EntityModel.setupAnim` family +//! (quadrupeds, humanoids, creepers, spiders, chickens...) applied to a map of +//! part poses before the model is drawn. +use super::{Mob, Part, keyframes::AnimationState, living::wrap}; +use std::collections::HashMap; +use std::f32::consts::PI; + +/// The setupAnim implementation a model uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Anim { + Quadruped, + Sheep, + Chicken, + Zombie, + Drowned, + ZombieVillager, + Skeleton, + Creeper, + Spider, + Enderman, + Silverfish, + Slime, + MagmaCube, + Witch, + Villager, + IronGolem, + SnowGolem, + Illager, + Piglin, + ZombifiedPiglin, + Hoglin, + Wolf, + Feline, + Fox, + Rabbit, + Horse, + Llama, + Goat, + Panda, + PolarBear, + Parrot, + Bee, + Turtle, + Armadillo, + Frog, + Axolotl, + Squid, + Fish, + Pufferfish, + Dolphin, + Bat, + Phantom, + Ghast, + Blaze, + Strider, + /// The humanoid model of the earlier simple renderer. + Humanoid { + zombie_arms: bool, + }, +} +/// Client-side animation clocks advanced each tick. +#[derive(Clone, Debug, Default)] +pub struct AnimState { + pub attack_anim: f32, + pub attack_anim_o: f32, + pub flap: f32, + pub flap_o: f32, + pub flap_speed: f32, + pub flap_speed_o: f32, + pub flapping: f32, + /// Generic per-species keyframe animation states. + pub states: [AnimationState; 4], + /// Smoothed values (tail wag, interest, squid tentacles...). + pub a: f32, + pub a_o: f32, + pub b: f32, + pub b_o: f32, + pub c: f32, + pub c_o: f32, +} +impl AnimState { + pub fn begin_tick(&mut self) { + self.attack_anim_o = self.attack_anim; + self.a_o = self.a; + self.b_o = self.b; + self.c_o = self.c; + } + pub fn end_tick(&mut self, _swinging: bool) {} +} +/// Part poses for one draw, keyed by part name. +pub struct Poses { + map: HashMap, + dummy: [f32; 9], +} +impl Poses { + pub fn new(model: &Part) -> Self { + let mut map = HashMap::new(); + fn walk(p: &Part, map: &mut HashMap) { + map.insert(p.name.clone(), p.pose); + for c in &p.children { + walk(c, map); + } + } + walk(model, &mut map); + Self { + map, + dummy: [0.0; 9], + } + } + pub fn get(&mut self, name: &str) -> &mut [f32; 9] { + match self.map.get_mut(name) { + Some(p) => p, + None => &mut self.dummy, + } + } + pub fn pose(&self, part: &Part) -> [f32; 9] { + self.map.get(&part.name).copied().unwrap_or(part.pose) + } + pub fn has(&self, name: &str) -> bool { + self.map.contains_key(name) + } + pub fn xrot(&mut self, n: &str, v: f32) { + self.get(n)[3] = v; + } + pub fn yrot(&mut self, n: &str, v: f32) { + self.get(n)[4] = v; + } + pub fn zrot(&mut self, n: &str, v: f32) { + self.get(n)[5] = v; + } + pub fn visible(&mut self, n: &str, v: bool) { + if !v { + let p = self.get(n); + p[6] = 0.0; + p[7] = 0.0; + p[8] = 0.0; + } + } +} +/// The LivingEntityRenderState values setupAnim reads. +#[derive(Clone, Copy, Debug)] +pub struct State { + pub pos: f32, + pub speed: f32, + pub age: f32, + /// Head yaw relative to the body, degrees. + pub y_rot: f32, + /// Head pitch, degrees. + pub x_rot: f32, + pub swing: f32, + pub baby: bool, + pub partial: f32, +} +pub fn state(m: &Mob, alpha: f32) -> State { + let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha; + let head = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; + let mut swing = m.anim.attack_anim - m.anim.attack_anim_o; + if swing < 0.0 { + swing += 1.0; + } + let swing = m.anim.attack_anim_o + swing * alpha; + let alive = m.alive(); + State { + pos: if alive { + m.limb_position - m.limb_speed * (1.0 - alpha) + } else { + 0.0 + }, + speed: if alive { + (m.previous_limb_speed + (m.limb_speed - m.previous_limb_speed) * alpha).min(1.0) + } else { + 0.0 + }, + age: m.age as f32 + alpha, + y_rot: wrap(head - body), + x_rot: m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha, + swing, + baby: m.is_baby(), + partial: alpha, + } +} +fn head(p: &mut Poses, s: &State) { + p.xrot("head", s.x_rot.to_radians()); + p.yrot("head", s.y_rot.to_radians()); +} +/// QuadrupedModel.setupAnim +fn quadruped(p: &mut Poses, s: &State) { + head(p, s); + let (pos, sp) = (s.pos, s.speed); + p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); + p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); + p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * sp); +} +/// AnimationUtils.bobModelPart +fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) { + let q = p.get(n); + q[5] += scale * ((age * 0.09).cos() * 0.05 + 0.05); + q[3] += scale * ((age * 0.067).sin() * 0.05); +} +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum ArmPose { + Empty, + Item, + Bow, + CrossbowHold, + CrossbowCharge, +} +/// HumanoidModel.setupAnim up to (and including) the attack animation hook. +fn humanoid( + p: &mut Poses, + s: &State, + right: ArmPose, + left: ArmPose, + zombie: Option, + holding: bool, +) { + head(p, s); + let (pos, sp) = (s.pos, s.speed); + p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5); + p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5); + p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp); + p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp); + p.yrot("right_leg", 0.005); + p.yrot("left_leg", -0.005); + p.zrot("right_leg", 0.005); + p.zrot("left_leg", -0.005); + let (hx, hy) = (p.get("head")[3], p.get("head")[4]); + for (arm, pose) in [("right_arm", right), ("left_arm", left)] { + match pose { + ArmPose::Empty => p.yrot(arm, 0.0), + ArmPose::Item => { + let x = p.get(arm)[3]; + p.xrot(arm, x * 0.5 - PI / 10.0); + p.yrot(arm, 0.0); + } + ArmPose::Bow => { + let right_main = arm == "right_arm"; + p.yrot("right_arm", -0.1 + hy - if right_main { 0.0 } else { 0.4 }); + p.yrot("left_arm", 0.1 + hy + if right_main { 0.4 } else { 0.0 }); + p.xrot("right_arm", -PI / 2.0 + hx); + p.xrot("left_arm", -PI / 2.0 + hx); + } + ArmPose::CrossbowHold => { + let r = arm == "right_arm"; + let (hold, shoot) = if r { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if r { -0.3 } else { 0.3 } + hy); + p.yrot(shoot, if r { 0.6 } else { -0.6 } + hy); + p.xrot(hold, -PI / 2.0 + hx + 0.1); + p.xrot(shoot, -1.5 + hx); + } + ArmPose::CrossbowCharge => { + let r = arm == "right_arm"; + let (hold, pull) = if r { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if r { -0.8 } else { 0.8 }); + p.xrot(hold, -0.970_796_35); + p.xrot(pull, -0.970_796_35); + p.yrot(pull, 0.6 * if r { 1.0 } else { -1.0 }); + p.xrot(pull, -PI / 2.0); + } + } + } + // setupAttackAnimation (WHACK swing with the right arm). + let swing = s.swing; + if swing > 0.0 { + let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2; + p.yrot("body", body_y); + let age_scale = if s.baby { 0.5 } else { 1.0 }; + { + let r = p.get("right_arm"); + r[2] = body_y.sin() * 5.0 * age_scale; + r[0] = -body_y.cos() * 5.0 * age_scale; + } + { + let l = p.get("left_arm"); + l[2] = -body_y.sin() * 5.0 * age_scale; + l[0] = body_y.cos() * 5.0 * age_scale; + } + p.get("right_arm")[4] += body_y; + p.get("left_arm")[4] += body_y; + p.get("left_arm")[3] += body_y; + let eased = 1.0 - (1.0 - swing).powi(4); + let aa = (eased * PI).sin(); + let bb = (swing * PI).sin() * -(hx - 0.7) * 0.75; + let r = p.get("right_arm"); + r[3] -= aa * 1.2 + bb; + r[4] += body_y * 2.0; + r[5] += (swing * PI).sin() * -0.4; + } + if let Some(aggressive) = zombie { + // AnimationUtils.animateZombieArms + let raise = !s.baby || !holding; + let drop = if raise { + -PI / if aggressive { 1.5 } else { 2.25 } + } else { + 0.0 + }; + let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).sin(); + let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let x = drop + ym * 1.2 - xm * 0.4; + let y = 0.1 - ym * 0.6; + p.xrot("right_arm", x); + p.yrot("right_arm", if raise { -y } else { y }); + p.zrot("right_arm", 0.0); + p.xrot("left_arm", x); + p.yrot("left_arm", if raise { y } else { -y }); + p.zrot("left_arm", 0.0); + } + bob(p, "right_arm", s.age, 1.0); + bob(p, "left_arm", s.age, -1.0); +} +/// Apply the mob's model animation to `p`. +pub fn setup( + m: &Mob, + s: &State, + p: &mut Poses, + w_anims: &HashMap, +) { + let _ = w_anims; + match m.kind.anim { + Anim::Quadruped | Anim::PolarBear | Anim::Panda | Anim::Goat => quadruped(p, s), + Anim::Sheep => { + quadruped(p, s); + // SheepModel: lower the head while eating grass. + let t = m.extra.anim_ticks; + let partial = s.partial; + let pos_scale = if t <= 0 { + 0.0 + } else if (4..=36).contains(&t) { + 1.0 + } else if t < 4 { + (t as f32 - partial) / 4.0 + } else { + -((t - 40) as f32 - partial) / 4.0 + }; + let angle = if t > 4 && t <= 36 { + let f = ((t - 4) as f32 - partial) / 32.0; + PI / 5.0 + 0.219_911_49 * (f * 28.7).sin() + } else if t > 0 { + PI / 5.0 + } else { + s.x_rot.to_radians() + }; + let age_scale = if s.baby { 0.5 } else { 1.0 }; + p.get("head")[1] += pos_scale * 9.0 * age_scale; + p.xrot("head", angle); + } + Anim::Chicken => { + let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; + let flap_speed = + m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; + let angle = (flap.sin() + 1.0) * flap_speed; + p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); + p.xrot("left_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed); + p.zrot("right_wing", angle); + p.zrot("left_wing", -angle); + if !s.baby { + head(p, s); + } + } + Anim::Zombie + | Anim::Drowned + | Anim::ZombieVillager + | Anim::ZombifiedPiglin + | Anim::Humanoid { zombie_arms: true } => { + let holding = m.extra.main_hand.is_some(); + let right = if holding { + ArmPose::Item + } else { + ArmPose::Empty + }; + humanoid(p, s, right, ArmPose::Empty, Some(m.ai.aggressive), holding); + } + Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => { + let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow"); + let right = if bow && m.ai.aggressive { + ArmPose::Bow + } else if m.extra.main_hand.is_some() { + ArmPose::Item + } else { + ArmPose::Empty + }; + humanoid( + p, + s, + right, + ArmPose::Empty, + None, + m.extra.main_hand.is_some(), + ); + if m.ai.aggressive && !bow { + // SkeletonModel melee pose. + let sw = s.swing; + let s2 = (sw * PI).sin(); + let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).sin(); + p.zrot("right_arm", 0.0); + p.zrot("left_arm", 0.0); + p.yrot("right_arm", -(0.1 - s2 * 0.6)); + p.yrot("left_arm", 0.1 - s2 * 0.6); + p.xrot("right_arm", -PI / 2.0 - (s2 * 1.2 - s1 * 0.4)); + p.xrot("left_arm", -PI / 2.0 - (s2 * 1.2 - s1 * 0.4)); + bob(p, "right_arm", s.age, 1.0); + bob(p, "left_arm", s.age, -1.0); + } + } + Anim::Creeper => { + head(p, s); + p.xrot("right_hind_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); + p.xrot("left_hind_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed); + p.xrot( + "right_front_leg", + (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed, + ); + p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); + } + Anim::Spider => { + head(p, s); + let pos = s.pos * 0.6662; + let sp = s.speed; + let swing = |o: f32| -((pos * 2.0 + o).cos() * 0.4) * sp; + let step = |o: f32| ((pos + o).sin() * 0.4).abs() * sp; + let legs = [ + ("hind", 0.0f32, 0.0f32), + ("middle_hind", PI, PI), + ("middle_front", PI / 2.0, PI / 2.0), + ("front", PI * 3.0 / 2.0, PI * 3.0 / 2.0), + ]; + for (n, so, to) in legs { + let (sw, st) = (swing(so), step(to)); + p.get(&format!("right_{n}_leg"))[4] += sw; + p.get(&format!("left_{n}_leg"))[4] -= sw; + p.get(&format!("right_{n}_leg"))[5] += st; + p.get(&format!("left_{n}_leg"))[5] -= st; + } + } + _ => { + if p.has("head") { + head(p, s); + } + if p.has("right_hind_leg") { + quadruped(p, s); + } + } + } +} diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs new file mode 100644 index 000000000..974559e66 --- /dev/null +++ b/crates/horizon-client/src/mobs/control.rs @@ -0,0 +1,400 @@ +//! Mob controls: `MoveControl` (with the flying and smooth-swimming +//! variants), `LookControl`, `JumpControl` and `BodyRotationControl`. +use super::{Mob, MobWorld, living::wrap}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Operation { + #[default] + Wait, + MoveTo, + Strafe, + Jumping, +} +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub enum MoveKind { + #[default] + Ground, + /// FlyingMoveControl(maxTurn, hoversInPlace) + Flying { max_turn: f32, hovers: bool }, + /// SmoothSwimmingMoveControl(maxTurnX, maxTurnY, inWater, outsideWater, applyGravity) + SmoothSwimming { + max_turn_x: f32, + max_turn_y: f32, + in_water: f32, + outside: f32, + gravity: bool, + }, + /// Goals drive the mob directly (slimes, ghasts, squid, fish, bats, phantoms). + Custom, +} +#[derive(Clone, Debug, Default)] +pub struct MoveControl { + pub kind: MoveKind, + pub wanted: [f64; 3], + pub speed_modifier: f64, + pub strafe_forwards: f32, + pub strafe_right: f32, + pub operation: Operation, +} +impl MoveControl { + pub fn has_wanted(&self) -> bool { + self.operation == Operation::MoveTo + } + pub fn set_wanted(&mut self, x: f64, y: f64, z: f64, speed: f64) { + self.wanted = [x, y, z]; + self.speed_modifier = speed; + if self.operation != Operation::Jumping { + self.operation = Operation::MoveTo; + } + } + pub fn strafe(&mut self, forwards: f32, right: f32) { + self.operation = Operation::Strafe; + self.strafe_forwards = forwards; + self.strafe_right = right; + self.speed_modifier = 0.25; + } +} +/// MoveControl.rotlerp: turn at most `max` degrees, result in [0, 360]. +pub fn rotlerp(a: f32, b: f32, max: f32) -> f32 { + let diff = wrap(b - a).clamp(-max, max); + let mut r = a + diff; + if r < 0.0 { + r += 360.0; + } else if r > 360.0 { + r -= 360.0; + } + r +} +/// Control.rotateTowards. +pub fn rotate_towards(from: f32, to: f32, max: f32) -> f32 { + from + wrap(to - from).clamp(-max, max) +} +/// Mth.rotateIfNecessary. +pub fn rotate_if_necessary(base: f32, target: f32, max: f32) -> f32 { + let d = wrap(target - base).clamp(-max, max); + target - d +} +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub enum LookKind { + #[default] + Default, + /// SmoothSwimmingLookControl(maxYRotFromCenter) + SmoothSwimming(f32), + /// Look controls that never reset pitch (e.g. ghasts keep their own). + Fixed, +} +#[derive(Clone, Debug, Default)] +pub struct LookControl { + pub kind: LookKind, + pub wanted: [f64; 3], + pub y_max_rot_speed: f32, + pub x_max_rot_angle: f32, + pub cooldown: i32, +} +impl LookControl { + pub fn set_look_at(&mut self, at: [f64; 3], y_speed: f32, x_max: f32) { + self.wanted = at; + self.y_max_rot_speed = y_speed; + self.x_max_rot_angle = x_max; + self.cooldown = 2; + } +} +#[derive(Clone, Debug, Default)] +pub struct BodyRotation { + head_stable_time: i32, + last_stable_head: f32, +} +impl Mob { + pub fn look_at(&mut self, at: [f64; 3]) { + let (y, x) = (self.kind.head_rot_speed, self.kind.max_head_x_rot); + self.ai.look.set_look_at(at, y, x); + } + pub fn look_at_speed(&mut self, at: [f64; 3], y_speed: f32, x_max: f32) { + self.ai.look.set_look_at(at, y_speed, x_max); + } + /// Mob.lookAt(entity, yMax, xMax): rotate the body yaw/pitch directly. + pub fn turn_to(&mut self, at: [f64; 3], y_max: f32, x_max: f32) { + let (dx, dz) = (at[0] - self.position.x, at[2] - self.position.z); + let dy = at[1] - self.eye_y(); + let sd = (dx * dx + dz * dz).sqrt(); + let y_rot = (dz.atan2(dx).to_degrees() as f32) - 90.0; + let x_rot = -(dy.atan2(sd).to_degrees() as f32); + self.head_pitch = rotate_toward_max(self.head_pitch, x_rot, x_max); + self.yaw = rotate_toward_max(self.yaw, y_rot, y_max); + } + /// MoveControl.tick (and the flying / smooth-swimming variants). + pub fn move_control_tick(&mut self, w: &MobWorld) { + let attr_speed = self.kind.speed * self.speed_bonus(); + match self.ai.mov.kind { + MoveKind::Custom => {} + MoveKind::Ground => self.ground_move_tick(w, attr_speed), + MoveKind::Flying { max_turn, hovers } => { + let m = &mut self.ai.mov; + if m.operation == Operation::MoveTo { + m.operation = Operation::Wait; + self.no_gravity = true; + let [wx, wy, wz] = self.ai.mov.wanted; + let (xd, yd, zd) = ( + wx - self.position.x, + wy - self.position.y, + wz - self.position.z, + ); + if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + self.ai.yya = 0.0; + self.ai.zza = 0.0; + return; + } + let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + self.yaw = rotlerp(self.yaw, y_rot, 90.0); + let speed = (self.ai.mov.speed_modifier + * if self.on_ground { + attr_speed + } else { + self.kind.flying_speed + }) as f32; + self.set_speed(speed); + let sd = (xd * xd + zd * zd).sqrt(); + if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 { + let x_rot = -(yd.atan2(sd).to_degrees() as f32); + self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn); + self.ai.yya = if yd > 0.0 { speed } else { -speed }; + } + } else { + if !hovers { + self.no_gravity = false; + } + self.ai.yya = 0.0; + self.ai.zza = 0.0; + } + } + MoveKind::SmoothSwimming { + max_turn_x, + max_turn_y, + in_water, + outside, + gravity, + } => { + if gravity && self.fluids.in_water { + self.velocity.y += 0.005; + } + if self.ai.mov.operation == Operation::MoveTo && !self.ai.nav.is_done() { + let [wx, wy, wz] = self.ai.mov.wanted; + let (xd, yd, zd) = ( + wx - self.position.x, + wy - self.position.y, + wz - self.position.z, + ); + if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + self.ai.zza = 0.0; + } else { + let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + self.yaw = rotlerp(self.yaw, y_rot, max_turn_y); + self.body_yaw = self.yaw; + self.head_yaw = self.yaw; + let speed = (self.ai.mov.speed_modifier * attr_speed) as f32; + if self.fluids.in_water { + self.ai.speed = speed * in_water; + let sd = (xd * xd + zd * zd).sqrt(); + if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 { + let x_rot = -(yd.atan2(sd).to_degrees() as f32); + let x_rot = wrap(x_rot).clamp(-max_turn_x, max_turn_x); + self.head_pitch = rotate_towards(self.head_pitch, x_rot, 5.0); + } + let (c, s) = ( + self.head_pitch.to_radians().cos(), + self.head_pitch.to_radians().sin(), + ); + self.ai.zza = c * speed; + self.ai.yya = -s * speed; + } else { + let left = wrap(self.yaw - y_rot).abs(); + let factor = 1.0 - ((left - 10.0) / 50.0).clamp(0.0, 1.0); + self.set_speed(speed * outside * factor); + } + } + } else { + self.ai.speed = 0.0; + self.ai.xxa = 0.0; + self.ai.yya = 0.0; + self.ai.zza = 0.0; + } + } + } + } + /// Mob.setSpeed also sets the forward input. + pub fn set_speed(&mut self, speed: f32) { + self.ai.speed = speed; + self.ai.zza = speed; + } + fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) { + match self.ai.mov.operation { + Operation::Strafe => { + let speed = (self.ai.mov.speed_modifier * attr_speed) as f32; + let (mut xa, mut za) = (self.ai.mov.strafe_forwards, self.ai.mov.strafe_right); + let mut dist = (xa * xa + za * za).sqrt(); + if dist < 1.0 { + dist = 1.0; + } + dist = speed / dist; + xa *= dist; + za *= dist; + let (s, c) = (self.yaw.to_radians().sin(), self.yaw.to_radians().cos()); + let dx = xa * c - za * s; + let dz = za * c + xa * s; + if !self.walkable(w, dx, dz) { + self.ai.mov.strafe_forwards = 1.0; + self.ai.mov.strafe_right = 0.0; + } + self.set_speed(speed); + self.ai.zza = self.ai.mov.strafe_forwards; + self.ai.xxa = self.ai.mov.strafe_right; + self.ai.mov.operation = Operation::Wait; + } + Operation::MoveTo => { + self.ai.mov.operation = Operation::Wait; + let [wx, wy, wz] = self.ai.mov.wanted; + let (xd, yd, zd) = ( + wx - self.position.x, + wy - self.position.y, + wz - self.position.z, + ); + if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 { + self.ai.zza = 0.0; + return; + } + let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + self.yaw = rotlerp(self.yaw, y_rot, 90.0); + self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32); + let (bx, by, bz) = ( + self.position.x.floor() as i32, + self.position.y.floor() as i32, + self.position.z.floor() as i32, + ); + let state = w.world.block(bx, by, bz); + let top = w.data.state(state).top; + let name = &w.facts.get(state).name; + let door_or_fence = name.ends_with("_door") || name.ends_with("fence"); + if yd > self.kind.step_height + && xd * xd + zd * zd < f64::from(self.width().max(1.0)) + || top > 0.0 + && self.position.y < f64::from(top) + f64::from(by) + && !door_or_fence + { + self.ai.jump = true; + self.ai.mov.operation = Operation::Jumping; + } + } + Operation::Jumping => { + self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32); + if self.on_ground || self.is_in_liquid() { + self.ai.mov.operation = Operation::Wait; + } + } + Operation::Wait => self.ai.zza = 0.0, + } + } + fn walkable(&self, w: &MobWorld, dx: f32, dz: f32) -> bool { + let x = (self.position.x + f64::from(dx)).floor() as i32; + let z = (self.position.z + f64::from(dz)).floor() as i32; + let y = self.position.y.floor() as i32; + w.path_type_static(x, y, z) == super::path::PathType::Walkable + } + /// LookControl.tick (and SmoothSwimmingLookControl). + pub fn look_control_tick(&mut self) { + let look = self.ai.look.clone(); + let (x_d, y_d) = self.look_angles(look.wanted); + match look.kind { + LookKind::SmoothSwimming(max) => { + if look.cooldown > 0 { + self.ai.look.cooldown -= 1; + if let Some(y) = y_d { + self.head_yaw = + rotate_towards(self.head_yaw, y + 20.0, look.y_max_rot_speed); + } + if let Some(x) = x_d { + self.head_pitch = + rotate_towards(self.head_pitch, x + 10.0, look.x_max_rot_angle); + } + } else { + if self.ai.nav.is_done() { + self.head_pitch = rotate_towards(self.head_pitch, 0.0, 5.0); + } + self.head_yaw = + rotate_towards(self.head_yaw, self.body_yaw, look.y_max_rot_speed); + } + let diff = wrap(self.head_yaw - self.body_yaw); + if diff < -max { + self.body_yaw -= 4.0; + } else if diff > max { + self.body_yaw += 4.0; + } + } + LookKind::Default | LookKind::Fixed => { + if look.kind == LookKind::Default { + self.head_pitch = 0.0; + } + if look.cooldown > 0 { + self.ai.look.cooldown -= 1; + if let Some(y) = y_d { + self.head_yaw = rotate_towards(self.head_yaw, y, look.y_max_rot_speed); + } + if let Some(x) = x_d { + self.head_pitch = rotate_towards(self.head_pitch, x, look.x_max_rot_angle); + } + } else { + self.head_yaw = rotate_towards(self.head_yaw, self.body_yaw, 10.0); + } + if !self.ai.nav.is_done() { + self.head_yaw = + rotate_if_necessary(self.head_yaw, self.body_yaw, self.kind.max_head_y_rot); + } + } + } + } + fn look_angles(&self, at: [f64; 3]) -> (Option, Option) { + let (xd, yd, zd) = ( + at[0] - self.position.x, + at[1] - self.eye_y(), + at[2] - self.position.z, + ); + let sd = (xd * xd + zd * zd).sqrt(); + let x = + (yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5).then(|| -(yd.atan2(sd).to_degrees() as f32)); + let y = (zd.abs() > 1.0e-5 || xd.abs() > 1.0e-5) + .then(|| (zd.atan2(xd).to_degrees() as f32) - 90.0); + (x, y) + } + /// JumpControl.tick. + pub fn jump_control_tick(&mut self) { + self.ai.jumping = self.ai.jump; + self.ai.jump = false; + } + /// BodyRotationControl.clientTick (Mob.tickHeadTurn). + pub fn body_rotation_tick(&mut self) { + let dx = self.position.x - self.previous.x; + let dz = self.position.z - self.previous.z; + let max = self.kind.max_head_y_rot; + if dx * dx + dz * dz > 2.500_000_3e-7 { + self.body_yaw = self.yaw; + self.head_yaw = rotate_if_necessary(self.head_yaw, self.body_yaw, max); + self.ai.body.last_stable_head = self.head_yaw; + self.ai.body.head_stable_time = 0; + } else if (self.head_yaw - self.ai.body.last_stable_head).abs() > 15.0 { + self.ai.body.head_stable_time = 0; + self.ai.body.last_stable_head = self.head_yaw; + self.body_yaw = rotate_if_necessary(self.body_yaw, self.head_yaw, max); + } else { + self.ai.body.head_stable_time += 1; + if self.ai.body.head_stable_time > 10 { + let t = self.ai.body.head_stable_time - 10; + let fraction = (t as f32 / 10.0).clamp(0.0, 1.0); + self.body_yaw = + rotate_if_necessary(self.body_yaw, self.head_yaw, max * (1.0 - fraction)); + } + } + } +} +/// Entity.rotlerp used by Mob.lookAt (clamped turn, no wrap of the result). +fn rotate_toward_max(from: f32, to: f32, max: f32) -> f32 { + from + wrap(to - from).clamp(-max, max) +} diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs new file mode 100644 index 000000000..5dde4f59b --- /dev/null +++ b/crates/horizon-client/src/mobs/data.rs @@ -0,0 +1,177 @@ +//! Facts the mob AI and renderer read from vanilla code, exported by +//! `VanillaMobDataExporter` into `mob-data.json`: per-state pathfinding types +//! (`WalkNodeEvaluator.getPathTypeFromState` with vanilla's tags bound), +//! pathfindability, spawn-surface predicates, collision tops, each entity +//! type's spawn placement and the client's keyframe animation definitions. +use super::keyframes::Animation; +use super::path::PathType; +use crate::blocks::{BlockFacts, Fluid}; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +pub const LAND: u16 = 1; +pub const WATER: u16 = 2; +pub const AIR: u16 = 4; +/// `isValidSpawn` for a typical monster (zombie). +pub const VALID_SPAWN: u16 = 8; +/// `isValidSpawn` for ocelots/parrots (leaves allowed). +pub const VALID_SPAWN_LEAVES: u16 = 16; +/// `isValidSpawn` for polar bears (ice allowed). +pub const VALID_SPAWN_ICE: u16 = 32; +pub const REDSTONE_CONDUCTOR: u16 = 64; +/// `NaturalSpawner.isValidEmptySpawnBlock` for a zombie. +pub const VALID_EMPTY_SPAWN: u16 = 128; +pub const STURDY_TOP: u16 = 256; +/// BlockState.isSolid +pub const SOLID: u16 = 512; +pub const SOLID_RENDER: u16 = 1024; + +#[derive(Clone, Copy, Debug)] +pub struct StateData { + pub path: PathType, + pub flags: u16, + /// Collision shape top (0 when the shape is empty). + pub top: f32, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Placement { + OnGround, + InWater, + InLava, + NoRestrictions, +} +pub struct MobData { + pub states: Vec, + pub placements: HashMap, + pub animations: HashMap, + /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. + pub biome_tags: HashMap>, +} +impl MobData { + pub fn load(root: &Path, facts: &BlockFacts) -> Self { + let parsed: Option = fs::read(root.join("mob-data.json")) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()); + let mut data = match parsed { + Some(v) + if v["states"] + .as_array() + .is_some_and(|a| a.len() == facts.states.len()) => + { + Self::from_json(&v) + } + _ => Self::fallback(facts), + }; + data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(); + data + } + pub fn biome_has(&self, tag: &str, biome: &str) -> bool { + self.biome_tags.get(tag).is_some_and(|s| s.contains(biome)) + } + fn from_json(v: &Value) -> Self { + let states = v["states"] + .as_array() + .into_iter() + .flatten() + .map(|s| StateData { + path: PathType::from_name(s[0].as_str().unwrap_or("BLOCKED")), + flags: s[1].as_u64().unwrap_or(0) as u16, + top: s[2].as_f64().unwrap_or(0.0) as f32, + }) + .collect(); + let placements = v["placements"] + .as_object() + .into_iter() + .flatten() + .map(|(k, p)| { + let placement = match p["placement"].as_str() { + Some("on_ground") => Placement::OnGround, + Some("in_water") => Placement::InWater, + Some("in_lava") => Placement::InLava, + _ => Placement::NoRestrictions, + }; + (k.clone(), placement) + }) + .collect(); + let animations = v["animations"] + .as_object() + .into_iter() + .flatten() + .map(|(k, a)| (k.clone(), Animation::parse(a))) + .collect(); + Self { + states, + placements, + animations, + biome_tags: HashMap::new(), + } + } + /// Without the export, approximate path types from the gameplay facts. + pub fn fallback(facts: &BlockFacts) -> Self { + let states = facts + .states + .iter() + .map(|f| { + let name = &*f.name; + let path = if matches!( + name, + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) { + PathType::Open + } else if f.fluid == Fluid::Lava && !f.waterlogged { + PathType::Lava + } else if name.ends_with("fence") || name.ends_with("_wall") { + PathType::Fence + } else if name.ends_with("leaves") { + PathType::Leaves + } else if name == "minecraft:fire" || name == "minecraft:magma_block" { + PathType::Fire + } else if f.full_collision { + PathType::Blocked + } else if f.fluid == Fluid::Water { + PathType::Water + } else { + PathType::Open + }; + let mut flags = 0; + if !f.full_collision { + flags |= LAND | AIR | VALID_EMPTY_SPAWN; + } + if f.fluid == Fluid::Water { + flags |= WATER; + } + if f.full_collision { + flags |= + VALID_SPAWN | VALID_SPAWN_ICE | REDSTONE_CONDUCTOR | STURDY_TOP | SOLID; + } + StateData { + path, + flags, + top: if f.full_collision { 1.0 } else { 0.0 }, + } + }) + .collect(); + Self { + states, + placements: HashMap::new(), + animations: HashMap::new(), + biome_tags: HashMap::new(), + } + } + pub fn state(&self, id: horizon_world::registry::BlockStateId) -> StateData { + self.states + .get(id.0 as usize) + .copied() + .unwrap_or(StateData { + path: PathType::Blocked, + flags: 0, + top: 1.0, + }) + } + pub fn placement(&self, entity: &str) -> Placement { + self.placements + .get(entity) + .cloned() + .unwrap_or(Placement::OnGround) + } +} diff --git a/crates/horizon-client/src/mobs/farm.rs b/crates/horizon-client/src/mobs/farm.rs new file mode 100644 index 000000000..4cd8416be --- /dev/null +++ b/crates/horizon-client/src/mobs/farm.rs @@ -0,0 +1,127 @@ +//! Farm animals: pigs, cows, mooshrooms, sheep and chickens (`registerGoals`, +//! chicken flapping and egg laying, sheep wool colours). +use super::{ + Mob, MobEvent, MobWorld, Species, + goals::{ + Breed, EatBlock, Float, FollowParent, LookAtPlayer, Panic, RandomLookAround, Stroll, Tempt, + }, +}; +use horizon_core::random::RandomSource; +use std::sync::Arc; + +pub fn register(m: &mut Mob) { + let food = m.kind.food.clone(); + let tempt = m.kind.tempt.clone(); + let g = &mut m.ai.goals; + match m.kind.species { + Species::Pig => { + g.add(0, Float); + g.add(1, Panic::new(1.25)); + g.add(3, Breed::new(1.0)); + g.add( + 4, + Tempt::new( + 1.2, + Arc::from(vec!["minecraft:carrot_on_a_stick".to_owned()]), + false, + ), + ); + g.add(4, Tempt::new(1.2, tempt, false)); + g.add(5, FollowParent::new(1.1)); + g.add(6, Stroll::avoiding_water(1.0)); + g.add(7, LookAtPlayer::new(6.0)); + g.add(8, RandomLookAround::default()); + } + Species::Cow | Species::Mooshroom => { + g.add(0, Float); + g.add(1, Panic::new(2.0)); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.25, food, false)); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + } + Species::Sheep => { + g.add(0, Float); + g.add(1, Panic::new(1.25)); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.1, food, false)); + g.add(4, FollowParent::new(1.1)); + g.add(5, EatBlock::default()); + g.add(6, Stroll::avoiding_water(1.0)); + g.add(7, LookAtPlayer::new(6.0)); + g.add(8, RandomLookAround::default()); + } + Species::Chicken => { + g.add(0, Float); + g.add(1, Panic::new(1.4)); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.0, food, false)); + g.add(4, FollowParent::new(1.1)); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + m.extra.egg_time = m.random.next_int_bound(6000).unwrap_or(0) + 6000; + } + _ => {} + } +} +/// Chicken.aiStep: wing flapping, slowed falling and laying eggs. +pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { + let a = &mut m.anim; + a.flap_o = a.flap; + a.flap_speed_o = a.flap_speed; + a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0); + if !m.on_ground && a.flapping < 1.0 { + a.flapping = 1.0; + } + a.flapping *= 0.9; + if !m.on_ground && m.velocity.y < 0.0 { + m.velocity.y *= 0.6; + } + a.flap += a.flapping * 2.0; + if m.alive() && !m.is_baby() { + m.extra.egg_time -= 1; + if m.extra.egg_time <= 0 { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch)); + events.push(MobEvent::GiftLoot { + table: "minecraft:gameplay/chicken_lay", + at, + }); + m.extra.egg_time = m.random.next_int_bound(6000).unwrap_or(0) + 6000; + } + } +} +/// Farm animal climate from the biome tags (`spawns_warm/cold_variant_farm_animals`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Climate { + #[default] + Temperate, + Warm, + Cold, +} +/// SheepColorSpawnRules.getSheepColor: a weighted list of 100 where the +/// climate's common colour (82) itself rolls pink 1 in 500. +pub fn sheep_color(climate: Climate, random: &mut impl RandomSource) -> u8 { + // DyeColor ids: white 0, pink 6, gray 7, light gray 8, brown 12, black 15. + let (list, common): ([(u8, i32); 4], u8) = match climate { + Climate::Temperate => ([(15, 5), (7, 5), (8, 5), (12, 3)], 0), + Climate::Warm => ([(7, 5), (8, 5), (0, 5), (15, 3)], 12), + Climate::Cold => ([(8, 5), (7, 5), (0, 5), (12, 3)], 15), + }; + let mut r = random.next_int_bound(100).unwrap_or(0); + for (color, weight) in list { + if r < weight { + return color; + } + r -= weight; + } + if random.next_int_bound(500).unwrap_or(1) < 499 { + common + } else { + 6 + } +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs new file mode 100644 index 000000000..fdb4a2387 --- /dev/null +++ b/crates/horizon-client/src/mobs/goals.rs @@ -0,0 +1,1638 @@ +//! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, +//! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. +use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::sync::Arc; + +pub const MOVE: u8 = 1; +pub const LOOK: u8 = 2; +pub const JUMP: u8 = 4; +pub const TARGET: u8 = 8; + +/// What goals may read and emit during a tick. +pub struct Cx<'a, 'w> { + pub w: &'a MobWorld<'w>, + pub events: &'a mut Vec, +} +pub trait Goal: std::fmt::Debug { + fn flags(&self) -> u8; + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool; + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) + } + fn interruptable(&self) -> bool { + true + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) {} + fn stop(&mut self, _m: &mut Mob, _cx: &mut Cx) {} + fn every_tick(&self) -> bool { + false + } + fn tick(&mut self, _m: &mut Mob, _cx: &mut Cx) {} + fn box_clone(&self) -> Box; + /// The goal's name for debugging (`Goal.toString`). + fn name(&self) -> &'static str { + std::any::type_name::() + .rsplit("::") + .next() + .unwrap_or("Goal") + } +} +impl Clone for Box { + fn clone(&self) -> Self { + self.box_clone() + } +} +macro_rules! goal_clone { + () => { + fn box_clone(&self) -> Box { + Box::new(self.clone()) + } + }; +} +pub(crate) use goal_clone; + +/// Goal.reducedTickDelay +pub fn reduced(ticks: i32) -> i32 { + (ticks + 1) / 2 +} +fn adjusted(every_tick: bool, ticks: i32) -> i32 { + if every_tick { ticks } else { reduced(ticks) } +} + +#[derive(Clone, Debug)] +struct Wrapped { + priority: i32, + goal: Box, + running: bool, +} +#[derive(Clone, Debug, Default)] +pub struct GoalSelector { + goals: Vec, + locked: [Option; 4], + pub disabled: u8, +} +fn flag_index(f: u8) -> usize { + f.trailing_zeros() as usize +} +impl GoalSelector { + pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) { + self.goals.push(Wrapped { + priority, + goal: Box::new(goal), + running: false, + }); + } + pub fn clear(&mut self) { + self.goals.clear(); + self.locked = [None; 4]; + } + pub fn running_names(&self) -> Vec<&'static str> { + self.goals + .iter() + .filter(|g| g.running) + .map(|g| g.goal.name()) + .collect() + } + pub fn is_running(&self, name: &str) -> bool { + self.goals + .iter() + .any(|g| g.running && g.goal.name() == name) + } + fn stop(&mut self, i: usize, m: &mut Mob, cx: &mut Cx) { + if self.goals[i].running { + self.goals[i].running = false; + self.goals[i].goal.stop(m, cx); + } + } + /// GoalSelector.tick + pub fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + for i in 0..self.goals.len() { + if self.goals[i].running + && (self.goals[i].goal.flags() & self.disabled != 0 + || !self.goals[i].goal.can_continue(m, cx)) + { + self.stop(i, m, cx); + } + } + for slot in &mut self.locked { + if slot.is_some_and(|i| !self.goals[i].running) { + *slot = None; + } + } + for i in 0..self.goals.len() { + let flags = self.goals[i].goal.flags(); + if self.goals[i].running || flags & self.disabled != 0 { + continue; + } + let replaceable = + (0..4) + .filter(|b| flags & (1 << b) != 0) + .all(|b| match self.locked[b] { + None => true, + Some(j) => { + self.goals[j].goal.interruptable() + && self.goals[i].priority < self.goals[j].priority + } + }); + if !replaceable || !self.goals[i].goal.can_use(m, cx) { + continue; + } + for b in 0..4 { + if flags & (1 << b) != 0 { + if let Some(j) = self.locked[b] { + self.stop(j, m, cx); + } + self.locked[b] = Some(i); + } + } + if !self.goals[i].running { + self.goals[i].running = true; + self.goals[i].goal.start(m, cx); + } + } + self.tick_running(m, cx, true); + } + pub fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx, force: bool) { + for g in &mut self.goals { + if g.running && (force || g.goal.every_tick()) { + g.goal.tick(m, cx); + } + } + } + pub fn stop_all(&mut self, m: &mut Mob, cx: &mut Cx) { + for i in 0..self.goals.len() { + self.stop(i, m, cx); + } + self.locked = [None; 4]; + } + #[allow(dead_code)] + fn locked_by(&self, flag: u8) -> Option { + self.locked[flag_index(flag)] + } +} + +// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- + +impl Mob { + /// PathfinderMob.getWalkTargetValue. + pub fn walk_target_value(&self, w: &MobWorld, p: [i32; 3]) -> f32 { + super::ai::walk_target_value(self, w, p) + } + fn random_direction(&mut self, h: i32, v: i32) -> [i32; 3] { + let x = self.random.next_int_bound(2 * h + 1).unwrap_or(0) - h; + let y = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v; + let z = self.random.next_int_bound(2 * h + 1).unwrap_or(0) - h; + [x, y, z] + } + #[allow(clippy::too_many_arguments)] + fn random_direction_within( + &mut self, + min: f64, + max: f64, + v: i32, + fly_height: i32, + xd: f64, + zd: f64, + max_rad: f64, + ) -> Option<[i32; 3]> { + let center = zd.atan2(xd) - std::f64::consts::FRAC_PI_2; + let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad; + let dist = + (min + self.random.next_double().sqrt() * (max - min)) * std::f64::consts::SQRT_2; + let xt = -dist * yrad.sin(); + let zt = dist * yrad.cos(); + if xt.abs() > max || zt.abs() > max { + return None; + } + let yt = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v + fly_height; + Some([xt.floor() as i32, yt, zt.floor() as i32]) + } + /// RandomPos.generateRandomPosTowardDirection (no home restriction). + fn toward(&mut self, _h: f64, d: [i32; 3]) -> [i32; 3] { + [ + (f64::from(d[0]) + self.position.x).floor() as i32, + (f64::from(d[1]) + self.position.y).floor() as i32, + (f64::from(d[2]) + self.position.z).floor() as i32, + ] + } + fn default_check(&self, w: &MobWorld, p: [i32; 3]) -> bool { + p[1] >= crate::chunk::MIN_Y + && p[1] < 320 + && self.stable_destination(w, p) + && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0 + } + fn pick_best( + &mut self, + w: &MobWorld, + mut supplier: impl FnMut(&mut Self) -> Option<[i32; 3]>, + ) -> Option<[f64; 3]> { + let mut best: Option<[i32; 3]> = None; + let mut best_weight = f64::NEG_INFINITY; + for _ in 0..10 { + if let Some(p) = supplier(self) { + let v = f64::from(self.walk_target_value(w, p)); + if v > best_weight { + best_weight = v; + best = Some(p); + } + } + } + best.map(|p| { + [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ] + }) + } + /// DefaultRandomPos.getPos + pub fn default_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> { + self.pick_best(w, |m| { + let d = m.random_direction(h, v); + let p = m.toward(f64::from(h), d); + m.default_check(w, p).then_some(p) + }) + } + /// DefaultRandomPos.getPosAway + pub fn default_random_pos_away( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + away: [f64; 3], + ) -> Option<[f64; 3]> { + let (xd, zd) = (self.position.x - away[0], self.position.z - away[2]); + self.pick_best(w, |m| { + let d = m.random_direction_within( + 0.0, + f64::from(h), + v, + 0, + xd, + zd, + std::f64::consts::FRAC_PI_2, + )?; + let p = m.toward(f64::from(h), d); + m.default_check(w, p).then_some(p) + }) + } + /// DefaultRandomPos.getPosTowards + pub fn default_random_pos_towards( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + to: [f64; 3], + max_rad: f64, + ) -> Option<[f64; 3]> { + let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); + self.pick_best(w, |m| { + let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?; + let p = m.toward(f64::from(h), d); + m.default_check(w, p).then_some(p) + }) + } + fn land_up_out_of_solid(&self, w: &MobWorld, mut p: [i32; 3]) -> Option<[i32; 3]> { + if w.solid(p[0], p[1], p[2]) { + p[1] += 1; + while p[1] <= 319 && w.solid(p[0], p[1], p[2]) { + p[1] += 1; + } + } + let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water; + (!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) + } + /// LandRandomPos.getPos + pub fn land_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> { + self.pick_best(w, |m| { + let d = m.random_direction(h, v); + let p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + return None; + } + m.land_up_out_of_solid(w, p) + }) + } + /// LandRandomPos.getPosAway + pub fn land_random_pos_away( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + away: [f64; 3], + ) -> Option<[f64; 3]> { + let (mut xd, mut zd) = (self.position.x - away[0], self.position.z - away[2]); + if xd == 0.0 && zd == 0.0 { + xd = self.random.next_double() - 0.5; + zd = self.random.next_double() - 0.5; + } + self.pick_best(w, |m| { + let d = m.random_direction_within( + 0.0, + f64::from(h), + v, + 0, + xd, + zd, + std::f64::consts::FRAC_PI_2, + )?; + let p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + return None; + } + m.land_up_out_of_solid(w, p) + }) + } + /// LandRandomPos.getPosTowards + pub fn land_random_pos_towards( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + to: [f64; 3], + ) -> Option<[f64; 3]> { + let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); + self.pick_best(w, |m| { + let d = m.random_direction_within( + 0.0, + f64::from(h), + v, + 0, + xd, + zd, + std::f64::consts::FRAC_PI_2, + )?; + let p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + return None; + } + m.land_up_out_of_solid(w, p) + }) + } + pub fn target_info(&self, w: &MobWorld) -> Option { + self.ai.target.and_then(|t| w.target_info(t)) + } + /// Sensing.hasLineOfSight (cached per tick in vanilla). + pub fn sees(&mut self, w: &MobWorld, who: Who) -> bool { + if let Some(v) = self.ai.seen_cache.iter().find(|(k, _)| *k == who) { + return v.1; + } + let Some(t) = w.target_info(who) else { + return false; + }; + let eye = Vec3::new(self.position.x, self.eye_y(), self.position.z); + let v = w.line_of_sight(eye, Vec3::new(t.position.x, t.eye_y, t.position.z)); + self.ai.seen_cache.push((who, v)); + v + } + /// Mob.isWithinMeleeAttackRange: the box inflated by sqrt(2.04) - 0.6. + pub fn within_melee_range(&self, t: &TargetInfo) -> bool { + let reach = 2.04f32.sqrt() as f64 - 0.6; + let b = self.bounds().inflate(Vec3::new(reach, 0.0, reach)); + b.intersects(t.bounds) + } + /// TargetingConditions.forCombat().test for the player: alive, not + /// creative, within range scaled by visibility, optionally visible. + pub fn can_target_player(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { + let Some(p) = &w.player else { return false }; + if !p.alive || p.creative { + return false; + } + let mut visibility = 1.0; + if p.sneaking { + visibility *= 0.8; + } + if let Some(head) = &p.head { + let skull = match self.species() { + Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { + "minecraft:zombie_head" + } + Species::Skeleton | Species::Stray | Species::Bogged => "minecraft:skeleton_head", + Species::Creeper => "minecraft:creeper_head", + Species::Piglin | Species::PiglinBrute => "minecraft:piglin_head", + _ => "", + }; + if &**head == skull { + visibility *= 0.5; + } + } + let dist = (range * visibility).max(2.0); + if self.distance_sqr(p.position) > dist * dist { + return false; + } + !check_sight || self.sees(w, Who::Player) + } +} + +// --- goals --------------------------------------------------------------- + +/// FloatGoal: jump (swim up) while deeper than the jump threshold or in lava. +#[derive(Clone, Debug)] +pub struct Float; +impl Goal for Float { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + if m.random.next_float() < 0.8 { + m.ai.jump = true; + } + } +} +/// PanicGoal: flee to a random position after panic-causing damage (or +/// towards water while burning). +#[derive(Clone, Debug)] +pub struct Panic { + pub speed: f64, + pos: [f64; 3], +} +impl Panic { + pub fn new(speed: f64) -> Self { + Self { + speed, + pos: [0.0; 3], + } + } +} +pub fn should_panic(m: &Mob) -> bool { + m.last_damage + .is_some_and(|(d, t)| d.causes_panic() && i64::from(m.age) - t <= 40) + || m.fire_ticks > 0 && !m.kind.flags.fire_immune +} +impl Goal for Panic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !should_panic(m) { + return false; + } + if m.fire_ticks > 0 { + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + if cx.w.data.state(cx.w.world.block(bx, by, bz)).top == 0.0 { + // findBlocksInBoxByManhattanDistance(pos, 5, 1) for water. + let mut best: Option<([i32; 3], i32)> = None; + for dy in -1i32..=1 { + for dx in -5i32..=5 { + for dz in -5i32..=5 { + let d = dx.abs() + dy.abs() + dz.abs(); + if cx.w.fluid(bx + dx, by + dy, bz + dz) == crate::blocks::Fluid::Water + && best.is_none_or(|b| d < b.1) + { + best = Some(([bx + dx, by + dy, bz + dz], d)); + } + } + } + } + if let Some((p, _)) = best { + self.pos = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]; + return true; + } + } + } + match m.default_random_pos(cx.w, 5, 4) { + Some(p) => { + self.pos = p; + true + } + None => false, + } + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_move_to(cx.w, self.pos, self.speed); + m.ai.panicking = true; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.panicking = false; + } +} +/// RandomStrollGoal / WaterAvoidingRandomStrollGoal. +#[derive(Clone, Debug)] +pub struct Stroll { + pub speed: f64, + pub interval: i32, + pub check_no_action: bool, + /// WaterAvoidingRandomStrollGoal probability of a plain stroll. + pub water_avoiding: Option, + pub force: bool, + wanted: [f64; 3], +} +impl Stroll { + pub fn new(speed: f64) -> Self { + Self { + speed, + interval: 120, + check_no_action: true, + water_avoiding: None, + force: false, + wanted: [0.0; 3], + } + } + pub fn avoiding_water(speed: f64) -> Self { + Self { + water_avoiding: Some(0.001), + ..Self::new(speed) + } + } + pub fn interval(mut self, i: i32) -> Self { + self.interval = i; + self + } +} +impl Goal for Stroll { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !self.force { + if self.check_no_action && m.ai.no_action_time >= 100 { + return false; + } + if m.random.next_int_bound(reduced(self.interval)).unwrap_or(1) != 0 { + return false; + } + } + let pos = match self.water_avoiding { + Some(prob) => { + if m.fluids.in_water { + m.land_random_pos(cx.w, 15, 7) + .or_else(|| m.default_random_pos(cx.w, 10, 7)) + } else if m.random.next_float() >= prob { + m.land_random_pos(cx.w, 10, 7) + } else { + m.default_random_pos(cx.w, 10, 7) + } + } + None => m.default_random_pos(cx.w, 10, 7), + }; + let Some(p) = pos else { return false }; + self.wanted = p; + self.force = false; + true + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_move_to(cx.w, self.wanted, self.speed); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + } +} +/// LookAtPlayerGoal (player targets only). +#[derive(Clone, Debug)] +pub struct LookAtPlayer { + pub range: f32, + pub probability: f32, + pub only_horizontal: bool, + look_time: i32, +} +impl LookAtPlayer { + pub fn new(range: f32) -> Self { + Self { + range, + probability: 0.02, + only_horizontal: false, + look_time: 0, + } + } + pub fn probability(mut self, p: f32) -> Self { + self.probability = p; + self + } +} +impl Goal for LookAtPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.random.next_float() >= self.probability { + return false; + } + let Some(p) = &cx.w.player else { return false }; + p.alive && m.distance_sqr(p.position) <= f64::from(self.range * self.range) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = &cx.w.player else { return false }; + p.alive + && m.distance_sqr(p.position) <= f64::from(self.range * self.range) + && self.look_time > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.look_time = reduced(40 + m.random.next_int_bound(40).unwrap_or(0)); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(p) = &cx.w.player + && p.alive + { + let y = if self.only_horizontal { + m.eye_y() + } else { + p.eye[1] + }; + m.look_at([p.position.x, y, p.position.z]); + self.look_time -= 1; + } + } +} +/// RandomLookAroundGoal. +#[derive(Clone, Debug, Default)] +pub struct RandomLookAround { + rel: [f64; 2], + time: i32, +} +impl Goal for RandomLookAround { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.random.next_float() < 0.02 + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + self.time >= 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let r = std::f64::consts::TAU * m.random.next_double(); + self.rel = [r.cos(), r.sin()]; + self.time = 20 + m.random.next_int_bound(20).unwrap_or(0); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + self.time -= 1; + let at = [ + m.position.x + self.rel[0], + m.eye_y(), + m.position.z + self.rel[1], + ]; + m.look_at(at); + } +} +/// MeleeAttackGoal (and ZombieAttackGoal's raised arms when `zombie`). +#[derive(Clone, Debug)] +pub struct MeleeAttack { + pub speed: f64, + pub follow_unseen: bool, + pub zombie: bool, + path_target: [f64; 3], + recalc: i32, + pub until_attack: i32, + last_check: i64, + raise_arm: i32, +} +impl MeleeAttack { + pub fn new(speed: f64, follow_unseen: bool) -> Self { + Self { + speed, + follow_unseen, + zombie: false, + path_target: [0.0; 3], + recalc: 0, + until_attack: 0, + last_check: i64::MIN / 2, + raise_arm: 0, + } + } + pub fn zombie(mut self) -> Self { + self.zombie = true; + self + } +} +impl Goal for MeleeAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if cx.w.game_time - self.last_check < 20 { + return false; + } + self.last_check = cx.w.game_time; + let Some(t) = m.target_info(cx.w) else { + return false; + }; + if !t.alive { + return false; + } + let path = m.create_path_to_entity(cx.w, [t.position.x, t.position.y, t.position.z], 0); + let ok = path.is_some() || m.within_melee_range(&t); + m.ai.pending_path = path; + ok + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(t) = m.target_info(cx.w) else { + return false; + }; + if !t.alive { + return false; + } + if !self.follow_unseen { + return !m.ai.nav.is_done(); + } + !(t.is_player && t.creative) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, self.speed); + m.ai.aggressive = true; + self.recalc = 0; + self.until_attack = 0; + self.raise_arm = 0; + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(t) = m.target_info(cx.w) + && t.is_player + && t.creative + { + m.ai.target = None; + } + m.ai.aggressive = false; + m.nav_stop(); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(who) = m.ai.target else { return }; + let Some(t) = cx.w.target_info(who) else { + return; + }; + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 30.0, 30.0); + self.recalc = (self.recalc - 1).max(0); + let moved = (t.position.x - self.path_target[0]).powi(2) + + (t.position.y - self.path_target[1]).powi(2) + + (t.position.z - self.path_target[2]).powi(2) + >= 1.0; + if (self.follow_unseen || m.sees(cx.w, who)) + && self.recalc <= 0 + && (self.path_target == [0.0; 3] || moved || m.random.next_float() < 0.05) + { + self.path_target = [t.position.x, t.position.y, t.position.z]; + self.recalc = 4 + m.random.next_int_bound(7).unwrap_or(0); + let d = m.distance_sqr(t.position); + if d > 1024.0 { + self.recalc += 10; + } else if d > 256.0 { + self.recalc += 5; + } + if !m.nav_move_to_entity(cx.w, self.path_target, 0, self.speed) { + self.recalc += 15; + } + self.recalc = adjusted(true, self.recalc); + } + 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); + m.swing(); + super::ai::do_hurt_target(m, who, cx); + } + if self.zombie { + self.raise_arm += 1; + m.ai.aggressive = self.raise_arm >= 5 && self.until_attack < adjusted(true, 20) / 2; + } + } +} +/// LeapAtTargetGoal. +#[derive(Clone, Debug)] +pub struct LeapAtTarget { + pub yd: f32, + target: [f64; 3], +} +impl LeapAtTarget { + pub fn new(yd: f32) -> Self { + Self { + yd, + target: [0.0; 3], + } + } +} +impl Goal for LeapAtTarget { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(t) = m.target_info(cx.w) else { + return false; + }; + let d = m.distance_sqr(t.position); + if !(4.0..=16.0).contains(&d) || !m.on_ground { + return false; + } + self.target = [t.position.x, t.position.y, t.position.z]; + m.random.next_int_bound(reduced(5)).unwrap_or(1) == 0 + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.on_ground + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let mut d = [ + self.target[0] - m.position.x, + 0.0, + self.target[2] - m.position.z, + ]; + let len_sq = d[0] * d[0] + d[2] * d[2]; + if len_sq > 1.0e-7 { + let l = len_sq.sqrt(); + d = [ + d[0] / l * 0.4 + m.velocity.x * 0.2, + 0.0, + d[2] / l * 0.4 + m.velocity.z * 0.2, + ]; + } + m.velocity = Vec3::new(d[0], f64::from(self.yd), d[2]); + } +} +/// What a target goal hunts. +#[derive(Clone, Debug)] +pub enum Prey { + Player, + Species(Vec), + /// Any mob matching a predicate on its snapshot. + Filter(fn(&Seen) -> bool), +} +/// NearestAttackableTargetGoal (+ TargetGoal's continue rules). +#[derive(Clone, Debug)] +pub struct NearestTarget { + pub prey: Prey, + pub must_see: bool, + pub must_reach: bool, + pub interval: i32, + /// Extra condition on the attacker (e.g. spiders only at night). + pub when: Option bool>, + found: Option, + target_goal: TargetState, +} +#[derive(Clone, Debug, Default)] +pub struct TargetState { + unseen: i32, + pub unseen_memory: i32, + reach_cache: i32, + reach_time: i32, +} +impl NearestTarget { + pub fn new(prey: Prey, must_see: bool) -> Self { + Self { + prey, + must_see, + must_reach: false, + interval: reduced(10), + when: None, + found: None, + target_goal: TargetState { + unseen_memory: 60, + ..Default::default() + }, + } + } + pub fn player(must_see: bool) -> Self { + Self::new(Prey::Player, must_see) + } + pub fn species(list: &[Species], must_see: bool) -> Self { + Self::new(Prey::Species(list.to_vec()), must_see) + } + pub fn interval(mut self, i: i32) -> Self { + self.interval = reduced(i); + self + } + pub fn reach(mut self) -> Self { + self.must_reach = true; + self + } + pub fn when(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self { + self.when = Some(f); + self + } +} +/// TargetGoal.canContinueToUse +pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(who) = m.ai.target else { return false }; + let Some(t) = cx.w.target_info(who) else { + return false; + }; + if !t.alive || t.is_player && t.creative { + return false; + } + if m.distance_sqr(t.position) > m.kind.follow_range * m.kind.follow_range { + return false; + } + if must_see { + if m.sees(cx.w, who) { + st.unseen = 0; + } else { + st.unseen += 1; + if st.unseen > reduced(st.unseen_memory) { + return false; + } + } + } + true +} +/// TargetGoal.canAttack's reach check. +fn can_reach(st: &mut TargetState, m: &mut Mob, cx: &mut Cx, at: Vec3) -> bool { + st.reach_time -= 1; + if st.reach_time <= 0 { + st.reach_cache = 0; + } + if st.reach_cache == 0 { + st.reach_time = reduced(10 + m.random.next_int_bound(5).unwrap_or(0)); + let path = m.create_path_to_entity(cx.w, [at.x, at.y, at.z], 0); + let ok = path.and_then(|p| p.end()).is_some_and(|e| { + let (xx, zz) = (e.x - at.x.floor() as i32, e.z - at.z.floor() as i32); + f64::from(xx * xx + zz * zz) <= 2.25 + }); + st.reach_cache = if ok { 1 } else { 2 }; + } + st.reach_cache == 1 +} +impl Goal for NearestTarget { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.interval > 0 && m.random.next_int_bound(self.interval).unwrap_or(1) != 0 { + return false; + } + if let Some(f) = self.when + && !f(m, cx.w) + { + return false; + } + let range = m.kind.follow_range; + self.found = None; + match &self.prey { + Prey::Player => { + if m.can_target_player(cx.w, range, self.must_see) { + let at = + cx.w.player + .as_ref() + .map(|p| p.position) + .unwrap_or(Vec3::ZERO); + if !self.must_reach || can_reach(&mut self.target_goal, m, cx, at) { + self.found = Some(Who::Player); + } + } + } + prey => { + let pos = m.position; + let id = m.id; + let candidates: Vec<(u32, Vec3)> = + cx.w.nearby(pos, range, move |s| { + s.id != id + && match prey { + Prey::Species(list) => list.contains(&s.species), + Prey::Filter(f) => f(s), + Prey::Player => false, + } + }) + .map(|s| (s.id, s.position)) + .collect(); + for (cid, cpos) in candidates { + if m.distance_sqr(cpos) > range * range { + continue; + } + if self.must_see && !m.sees(cx.w, Who::Mob(cid)) { + continue; + } + if self.must_reach && !can_reach(&mut self.target_goal, m, cx, cpos) { + continue; + } + self.found = Some(Who::Mob(cid)); + break; + } + } + } + self.found.is_some() + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + target_continue(&mut self.target_goal, self.must_see, m, cx) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = self.found; + self.target_goal.reach_cache = 0; + self.target_goal.reach_time = 0; + self.target_goal.unseen = 0; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = None; + } +} +/// HurtByTargetGoal (optionally alerting others of the same species). +#[derive(Clone, Debug)] +pub struct HurtByTarget { + pub alert: bool, + /// Species that should not be alerted. + pub alert_except: Vec, + /// Attackers ignored (e.g. zombified piglins ignore other zombified piglins). + pub ignore: Vec, + timestamp: i32, + st: TargetState, +} +impl HurtByTarget { + pub fn new() -> Self { + Self { + alert: false, + alert_except: vec![], + ignore: vec![], + timestamp: 0, + st: TargetState { + unseen_memory: 300, + ..Default::default() + }, + } + } + pub fn alert(mut self) -> Self { + self.alert = true; + self + } + pub fn ignoring(mut self, s: &[Species]) -> Self { + self.ignore = s.to_vec(); + self + } +} +impl Default for HurtByTarget { + fn default() -> Self { + Self::new() + } +} +impl Goal for HurtByTarget { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(by) = m.ai.last_hurt_by else { + return false; + }; + if m.ai.last_hurt_by_time == self.timestamp { + return false; + } + if let Who::Mob(id) = by + && cx + .w + .seen(id) + .is_some_and(|s| self.ignore.contains(&s.species)) + { + return false; + } + let Some(t) = cx.w.target_info(by) else { + return false; + }; + t.alive && !(t.is_player && t.creative) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + target_continue(&mut self.st, true, m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.target = m.ai.last_hurt_by; + self.timestamp = m.ai.last_hurt_by_time; + self.st.unseen_memory = 300; + self.st.unseen = 0; + if self.alert + && let Some(by) = m.ai.target + { + let range = m.kind.follow_range; + let species = m.species(); + let id = m.id; + let pos = m.position; + let ids: Vec = + cx.w.others + .iter() + .filter(|s| { + s.id != id + && s.alive + && s.species == species + && s.target.is_none() + && (s.position.x - pos.x).abs() <= range + 1.0 + && (s.position.y - pos.y).abs() <= 11.0 + && (s.position.z - pos.z).abs() <= range + 1.0 + }) + .filter(|s| !self.alert_except.contains(&s.species)) + .filter(|s| Who::Mob(s.id) != by) + .map(|s| s.id) + .collect(); + for other in ids { + cx.events.push(MobEvent::SetTarget { + mob: other, + target: by, + }); + } + } + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = None; + } +} +/// What an AvoidEntityGoal flees from. +#[derive(Clone, Debug)] +pub enum Avoid { + Player, + Species(Vec), +} +/// AvoidEntityGoal. +#[derive(Clone, Debug)] +pub struct AvoidEntity { + pub what: Avoid, + pub max_dist: f32, + pub walk: f64, + pub sprint: f64, + /// Extra condition on the avoider (e.g. untamed cats only). + pub when: Option bool>, + from: Vec3, +} +impl AvoidEntity { + pub fn new(what: Avoid, max_dist: f32, walk: f64, sprint: f64) -> Self { + Self { + what, + max_dist, + walk, + sprint, + when: None, + from: Vec3::ZERO, + } + } + pub fn when(mut self, f: fn(&Mob) -> bool) -> Self { + self.when = Some(f); + self + } +} +impl Goal for AvoidEntity { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if let Some(f) = self.when + && !f(m) + { + return false; + } + let max = f64::from(self.max_dist); + let found = match &self.what { + Avoid::Player => { + cx.w.player + .as_ref() + .filter(|p| { + p.alive + && !p.creative + && m.distance_sqr(p.position) <= max * max + && (p.position.y - m.position.y).abs() <= max + 3.0 + }) + .map(|p| p.position) + } + Avoid::Species(list) => { + let id = m.id; + let y = m.position.y; + cx.w.nearby(m.position, max, move |s| { + s.id != id && list.contains(&s.species) && (s.position.y - y).abs() <= 3.0 + max + }) + .map(|s| s.position) + .next() + } + }; + let Some(from) = found else { return false }; + if m.distance_sqr(from) > max * max { + return false; + } + let Some(pos) = m.default_random_pos_away(cx.w, 16, 7, [from.x, from.y, from.z]) else { + return false; + }; + let to_pos = + (from.x - pos[0]).powi(2) + (from.y - pos[1]).powi(2) + (from.z - pos[2]).powi(2); + if to_pos < m.distance_sqr(from) { + return false; + } + self.from = from; + let path = m.create_path_to( + cx.w, + [ + pos[0].floor() as i32, + pos[1].floor() as i32, + pos[2].floor() as i32, + ], + 0, + ); + m.ai.pending_path = path; + m.ai.pending_path.is_some() + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let path = m.ai.pending_path.take(); + m.nav_move_to_path(path, self.walk); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let from = match &self.what { + Avoid::Player => { + cx.w.player + .as_ref() + .map(|p| p.position) + .unwrap_or(self.from) + } + Avoid::Species(_) => self.from, + }; + m.ai.nav.speed_modifier = if m.distance_sqr(from) < 49.0 { + self.sprint + } else { + self.walk + }; + } +} +/// TemptGoal: follow a player holding one of the items. +#[derive(Clone, Debug)] +pub struct Tempt { + pub speed: f64, + pub items: Arc<[String]>, + pub can_scare: bool, + pub stop_distance: f64, + p: [f64; 3], + rot: [f64; 2], + calm_down: i32, +} +impl Tempt { + pub fn new(speed: f64, items: Arc<[String]>, can_scare: bool) -> Self { + Self { + speed, + items, + can_scare, + stop_distance: 2.5, + p: [0.0; 3], + rot: [0.0; 2], + calm_down: 0, + } + } + fn wants(&self, item: &Option>) -> bool { + item.as_ref() + .is_some_and(|i| self.items.iter().any(|t| t.as_str() == &**i)) + } +} +impl Goal for Tempt { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.calm_down > 0 { + self.calm_down -= 1; + return false; + } + let Some(p) = &cx.w.player else { return false }; + // Attributes.TEMPT_RANGE default 10. + p.alive + && (self.wants(&p.main_hand) || self.wants(&p.off_hand)) + && m.distance_sqr(p.position) <= 100.0 + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.can_scare + && let Some(p) = &cx.w.player + { + if m.distance_sqr(p.position) < 36.0 { + let moved = (p.position.x - self.p[0]).powi(2) + + (p.position.y - self.p[1]).powi(2) + + (p.position.z - self.p[2]).powi(2); + if moved > 0.010_000_000_000_000_002 { + return false; + } + let (yaw, pitch) = look_angles(p.look); + if (pitch - self.rot[0]).abs() > 5.0 || (yaw - self.rot[1]).abs() > 5.0 { + return false; + } + } else { + self.p = [p.position.x, p.position.y, p.position.z]; + } + let (yaw, pitch) = look_angles(p.look); + self.rot = [pitch, yaw]; + } + self.can_use(m, cx) + } + fn start(&mut self, _: &mut Mob, cx: &mut Cx) { + if let Some(p) = &cx.w.player { + self.p = [p.position.x, p.position.y, p.position.z]; + } + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + self.calm_down = reduced(100); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + m.look_at_speed(p.eye, y, x); + if m.distance_sqr(p.position) < self.stop_distance * self.stop_distance { + m.nav_stop(); + } else { + m.nav_move_to_entity( + cx.w, + [p.position.x, p.position.y, p.position.z], + 1, + self.speed, + ); + } + } +} +fn look_angles(look: [f64; 3]) -> (f64, f64) { + let yaw = (-look[0]).atan2(look[2]).to_degrees(); + let pitch = (-look[1]).asin().to_degrees(); + (yaw, pitch) +} +/// BreedGoal: walk to a partner in love and breed after 60 ticks. +#[derive(Clone, Debug)] +pub struct Breed { + pub speed: f64, + partner: Option, + love_time: i32, +} +impl Breed { + pub fn new(speed: f64) -> Self { + Self { + speed, + partner: None, + love_time: 0, + } + } +} +impl Goal for Breed { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.in_love <= 0 { + return false; + } + let species = m.species(); + let id = m.id; + self.partner = + cx.w.nearby(m.position, 8.0, move |s| { + s.id != id && s.species == species && s.in_love && !s.baby + }) + .map(|s| s.id) + .next(); + self.partner.is_some() + } + fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool { + self.partner + .and_then(|p| cx.w.seen(p)) + .is_some_and(|s| s.alive && s.in_love) + && self.love_time < 60 + } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.partner = None; + self.love_time = 0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = self.partner.and_then(|p| cx.w.seen(p)).cloned() else { + return; + }; + let x = m.kind.max_head_x_rot; + m.look_at_speed([p.position.x, p.eye_y, p.position.z], 10.0, x); + m.nav_move_to_entity( + cx.w, + [p.position.x, p.position.y, p.position.z], + 1, + self.speed, + ); + self.love_time += 1; + if self.love_time >= reduced(60) && m.distance_sqr(p.position) < 9.0 { + m.extra.in_love = 0; + m.extra.age = 6000; + cx.events.push(MobEvent::Breed { + parent: m.id, + partner: p.id, + }); + } + } +} +/// FollowParentGoal. +#[derive(Clone, Debug)] +pub struct FollowParent { + pub speed: f64, + parent: Option, + recalc: i32, +} +impl FollowParent { + pub fn new(speed: f64) -> Self { + Self { + speed, + parent: None, + recalc: 0, + } + } +} +impl Goal for FollowParent { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.age >= 0 { + return false; + } + let species = m.species(); + let pos = m.position; + let mut best: Option<(u32, f64)> = None; + for s in cx.w.others.iter().filter(|s| { + s.alive + && s.species == species + && !s.baby + && (s.position.x - pos.x).abs() <= 8.0 + && (s.position.y - pos.y).abs() <= 4.0 + && (s.position.z - pos.z).abs() <= 8.0 + }) { + let d = m.distance_sqr(s.position); + if best.is_none_or(|b| d <= b.1) { + best = Some((s.id, d)); + } + } + match best { + Some((id, d)) if d >= 9.0 => { + self.parent = Some(id); + true + } + _ => false, + } + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.extra.age >= 0 { + return false; + } + let Some(p) = self.parent.and_then(|p| cx.w.seen(p)) else { + return false; + }; + let d = m.distance_sqr(p.position); + p.alive && (9.0..=256.0).contains(&d) + } + fn start(&mut self, _: &mut Mob, _: &mut Cx) { + self.recalc = 0; + } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.parent = None; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.recalc -= 1; + if self.recalc <= 0 { + self.recalc = reduced(10); + if let Some(p) = self.parent.and_then(|p| cx.w.seen(p)) { + let at = [p.position.x, p.position.y, p.position.z]; + m.nav_move_to_entity(cx.w, at, 1, self.speed); + } + } + } +} +/// RestrictSunGoal: avoid sunlit nodes while it is bright outside. +#[derive(Clone, Debug)] +pub struct RestrictSun; +impl Goal for RestrictSun { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + cx.w.daylight && m.extra.head.is_none() + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.nav.avoid_sun = true; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.nav.avoid_sun = false; + } +} +/// FleeSunGoal: find shade while burning. +#[derive(Clone, Debug)] +pub struct FleeSun { + pub speed: f64, + wanted: [f64; 3], +} +impl FleeSun { + pub fn new(speed: f64) -> Self { + Self { + speed, + wanted: [0.0; 3], + } + } +} +impl Goal for FleeSun { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.ai.target.is_some() || !cx.w.daylight || m.fire_ticks <= 0 || m.extra.head.is_some() { + return false; + } + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + if !cx.w.can_see_sky(bx, by, bz) { + return false; + } + for _ in 0..10 { + let p = [ + bx + m.random.next_int_bound(20).unwrap_or(0) - 10, + by + m.random.next_int_bound(6).unwrap_or(0) - 3, + bz + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; + if !cx.w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(cx.w, p) < 0.0 { + self.wanted = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + return true; + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_move_to(cx.w, self.wanted, self.speed); + } +} +/// EatBlockGoal (sheep): eat short grass or turn grass blocks to dirt. +#[derive(Clone, Debug, Default)] +pub struct EatBlock { + tick: i32, +} +impl Goal for EatBlock { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let chance = reduced(if m.is_baby() { 50 } else { 1000 }); + if m.random.next_int_bound(chance).unwrap_or(1) != 0 { + return false; + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let here = cx.w.block_name(x, y, z).to_owned(); + cx.w.has_tag("minecraft:edible_for_sheep", &here) + || cx.w.block_name(x, y - 1, z) == "minecraft:grass_block" + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.tick = reduced(40); + m.extra.anim_ticks = 40; + m.nav_stop(); + } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.tick = 0; + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + self.tick > 0 + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.tick = (self.tick - 1).max(0); + if self.tick == reduced(4) { + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let here = cx.w.block_name(x, y, z).to_owned(); + if cx.w.has_tag("minecraft:edible_for_sheep", &here) { + cx.events.push(MobEvent::BreakBlock { + pos: [x, y, z], + drop: false, + }); + super::ai::ate(m); + } else if cx.w.block_name(x, y - 1, z) == "minecraft:grass_block" { + cx.events.push(MobEvent::SetBlockName { + pos: [x, y - 1, z], + name: "minecraft:dirt", + effect: true, + }); + super::ai::ate(m); + } + } + } +} diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs new file mode 100644 index 000000000..18f5d7333 --- /dev/null +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -0,0 +1,173 @@ +//! Creepers (swelling, explosions) and spiders (wall climbing, daylight +//! neutrality, leaping). +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::{ + Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LeapAtTarget, LookAtPlayer, MOVE, + MeleeAttack, NearestTarget, RandomLookAround, Stroll, goal_clone, + }, +}; +use horizon_core::random::RandomSource; + +pub fn register(m: &mut Mob) { + use Species as S; + match m.species() { + S::Creeper => { + let g = &mut m.ai.goals; + g.add(1, Float); + g.add(2, Swell::default()); + g.add( + 3, + AvoidEntity::new(Avoid::Species(vec![S::Ocelot]), 6.0, 1.0, 1.2), + ); + g.add( + 3, + AvoidEntity::new(Avoid::Species(vec![S::Cat]), 6.0, 1.0, 1.2), + ); + g.add(4, MeleeAttack::new(1.0, false)); + g.add(5, Stroll::avoiding_water(0.8)); + g.add(6, LookAtPlayer::new(8.0)); + g.add(6, RandomLookAround::default()); + m.ai.targets.add(1, NearestTarget::player(true)); + m.ai.targets.add(2, HurtByTarget::new()); + // Creeper DATA_SWELL_DIR starts at -1. + m.extra.counter = -1; + } + S::Spider | S::CaveSpider => { + let g = &mut m.ai.goals; + g.add(1, Float); + g.add( + 2, + AvoidEntity::new(Avoid::Species(vec![S::Armadillo]), 6.0, 1.0, 1.2), + ); + g.add(3, LeapAtTarget::new(0.4)); + g.add(4, SpiderAttack(MeleeAttack::new(1.0, true))); + g.add(5, Stroll::avoiding_water(0.8)); + g.add(6, LookAtPlayer::new(8.0)); + g.add(6, RandomLookAround::default()); + m.ai.targets.add(1, HurtByTarget::new()); + m.ai.targets + .add(2, NearestTarget::player(true).when(dark_enough)); + m.ai.targets.add( + 3, + NearestTarget::species(&[S::IronGolem], true).when(dark_enough), + ); + m.ai.nav.kind = super::nav::NavKind::WallClimber; + } + _ => {} + } +} +/// Entity.getLightLevelDependentMagicValue at the eye. +pub fn mob_brightness(m: &Mob, w: &MobWorld) -> f32 { + w.brightness( + m.position.x.floor() as i32, + m.eye_y().floor() as i32, + m.position.z.floor() as i32, + ) +} +fn dark_enough(m: &Mob, w: &MobWorld) -> bool { + mob_brightness(m, w) < 0.5 +} +/// Spider.SpiderAttackGoal: gives up in bright light 1 in 100 ticks. +#[derive(Clone, Debug)] +pub struct SpiderAttack(MeleeAttack); +impl Goal for SpiderAttack { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if mob_brightness(m, cx.w) >= 0.5 && m.random.next_int_bound(100).unwrap_or(1) == 0 { + m.ai.target = None; + return false; + } + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx) + } +} +/// SwellGoal: fuse within 3 blocks, defuse beyond 7 or out of sight. +#[derive(Clone, Debug, Default)] +pub struct Swell { + target: Option, +} +impl Goal for Swell { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let close = m + .target_info(cx.w) + .is_some_and(|t| t.alive && m.distance_sqr(t.position) < 9.0); + m.extra.counter > 0 || close + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + self.target = m.ai.target; + } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.target = None; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let dir = match self + .target + .and_then(|t| cx.w.target_info(t).map(|i| (t, i))) + { + Some((who, t)) if t.alive => { + if m.distance_sqr(t.position) > 49.0 || !m.sees(cx.w, who) { + -1 + } else { + 1 + } + } + _ => -1, + }; + m.extra.counter = dir; + } +} +/// Creeper.tick: advance the fuse and explode at 30. +pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { + if !m.alive() { + return; + } + if m.extra.flag { + // Ignited by flint and steel. + m.extra.counter = 1; + } + let dir = m.extra.counter; + if dir > 0 && m.swell == 0 { + events.push(MobEvent::Sound( + "entity.creeper.primed", + m.center(), + 1.0, + 0.5, + )); + } + m.swell = (m.swell + dir).max(0); + if m.swell >= 30 { + m.swell = 30; + let radius = if m.extra.charged { 6.0 } else { 3.0 }; + events.push(MobEvent::Explode( + [m.position.x, m.position.y, m.position.z], + radius, + )); + m.removed = true; + } +} diff --git a/crates/horizon-client/src/mobs/keyframes.rs b/crates/horizon-client/src/mobs/keyframes.rs new file mode 100644 index 000000000..e070210ec --- /dev/null +++ b/crates/horizon-client/src/mobs/keyframes.rs @@ -0,0 +1,228 @@ +//! Vanilla keyframe animations (`AnimationDefinition`, `AnimationChannel`, +//! `KeyframeAnimation`) exported from the client's animation definitions, +//! applied to a pose map exactly like `KeyframeAnimation.Entry.apply`. +use serde_json::Value; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Target { + Position, + Rotation, + Scale, +} +#[derive(Clone, Copy, Debug)] +pub struct Keyframe { + pub time: f32, + pub pre: [f32; 3], + pub post: [f32; 3], + pub catmull: bool, +} +#[derive(Clone, Debug)] +pub struct Channel { + pub target: Target, + pub keyframes: Vec, +} +#[derive(Clone, Debug)] +pub struct Animation { + pub length: f32, + pub looping: bool, + pub bones: Vec<(String, Vec)>, +} +fn v3(v: &Value) -> [f32; 3] { + let a = |i: usize| v[i].as_f64().unwrap_or(0.0) as f32; + [a(0), a(1), a(2)] +} +impl Animation { + pub fn parse(v: &Value) -> Self { + let bones = v["bones"] + .as_object() + .into_iter() + .flatten() + .map(|(name, channels)| { + let channels = channels + .as_array() + .into_iter() + .flatten() + .map(|c| Channel { + target: match c["target"].as_str() { + Some("position") => Target::Position, + Some("scale") => Target::Scale, + _ => Target::Rotation, + }, + keyframes: c["keyframes"] + .as_array() + .into_iter() + .flatten() + .map(|k| Keyframe { + time: k[0].as_f64().unwrap_or(0.0) as f32, + pre: v3(&k[1]), + post: v3(&k[2]), + catmull: k[3].as_str() == Some("catmullrom"), + }) + .collect(), + }) + .collect(); + (name.clone(), channels) + }) + .collect(); + Self { + length: v["length"].as_f64().unwrap_or(1.0) as f32, + looping: v["looping"].as_bool().unwrap_or(false), + bones, + } + } + /// KeyframeAnimation.apply(millis, scale): offsets added to each bone's pose. + pub fn apply(&self, millis: i64, scale: f32, poses: &mut super::anim::Poses) { + let mut seconds = millis as f32 / 1000.0; + if self.looping { + seconds %= self.length; + } + for (bone, channels) in &self.bones { + for c in channels { + let v = sample(&c.keyframes, seconds, scale); + let p = poses.get(bone); + match c.target { + // ModelPart.offsetPos / offsetRotation / offsetScale. + Target::Position => { + p[0] += v[0]; + p[1] += v[1]; + p[2] += v[2]; + } + Target::Rotation => { + p[3] += v[0]; + p[4] += v[1]; + p[5] += v[2]; + } + Target::Scale => { + p[6] += v[0]; + p[7] += v[1]; + p[8] += v[2]; + } + } + } + } + } + /// KeyframeAnimation.applyWalk(pos, speed, speedFactor, scaleFactor). + pub fn apply_walk( + &self, + pos: f32, + speed: f32, + speed_factor: f32, + scale_factor: f32, + poses: &mut super::anim::Poses, + ) { + let time = (pos * 50.0 * speed_factor) as i64; + let scale = (speed * scale_factor).min(1.0); + self.apply(time, scale, poses); + } +} +fn catmullrom(t: f32, p0: f32, p1: f32, p2: f32, p3: f32) -> f32 { + 0.5 * (2.0 * p1 + + (p2 - p0) * t + + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t * t + + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t * t * t) +} +/// KeyframeAnimation.Entry.apply interpolation. +fn sample(k: &[Keyframe], seconds: f32, scale: f32) -> [f32; 3] { + if k.is_empty() { + return [0.0; 3]; + } + // Mth.binarySearch(0, len, i -> seconds <= k[i].time) - 1 + let first = k.iter().position(|f| seconds <= f.time).unwrap_or(k.len()); + let prev = first.saturating_sub(1); + let next = (prev + 1).min(k.len() - 1); + let delta = seconds - k[prev].time; + let alpha = if next != prev { + (delta / (k[next].time - k[prev].time)).clamp(0.0, 1.0) + } else { + 0.0 + }; + if k[next].catmull { + let p0 = k[prev.saturating_sub(1)].post; + let p1 = k[prev].post; + let p2 = k[next].post; + let p3 = k[(next + 1).min(k.len() - 1)].post; + std::array::from_fn(|i| catmullrom(alpha, p0[i], p1[i], p2[i], p3[i]) * scale) + } else { + let a = k[prev].post; + let b = k[next].pre; + std::array::from_fn(|i| (a[i] + (b[i] - a[i]) * alpha) * scale) + } +} +/// AnimationState: a start time in ticks while started. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct AnimationState { + pub started: Option, +} +impl AnimationState { + pub fn start(&mut self, age: f32) { + self.started = Some(age); + } + pub fn start_if_stopped(&mut self, age: f32) { + if self.started.is_none() { + self.started = Some(age); + } + } + pub fn stop(&mut self) { + self.started = None; + } + pub fn animate_when(&mut self, condition: bool, age: f32) { + if condition { + self.start_if_stopped(age) + } else { + self.stop() + } + } + /// Milliseconds since the start at render time `age` (ticks + partial). + pub fn millis(&self, age: f32) -> Option { + self.started.map(|s| ((age - s) * 50.0) as i64) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn linear_keyframes_interpolate_post_to_pre() { + let k = vec![ + Keyframe { + time: 0.0, + pre: [0.0; 3], + post: [0.0; 3], + catmull: false, + }, + Keyframe { + time: 1.0, + pre: [2.0, 4.0, 6.0], + post: [2.0, 4.0, 6.0], + catmull: false, + }, + ]; + let v = sample(&k, 0.5, 1.0); + assert_eq!(v, [1.0, 2.0, 3.0]); + // Past the end it holds the last value. + assert_eq!(sample(&k, 3.0, 0.5), [1.0, 2.0, 3.0]); + } + #[test] + fn catmullrom_passes_through_keyframes() { + let k = vec![ + Keyframe { + time: 0.0, + pre: [0.0; 3], + post: [0.0; 3], + catmull: true, + }, + Keyframe { + time: 1.0, + pre: [1.0; 3], + post: [1.0; 3], + catmull: true, + }, + Keyframe { + time: 2.0, + pre: [0.0; 3], + post: [0.0; 3], + catmull: true, + }, + ]; + assert!((sample(&k, 1.0, 1.0)[0] - 1.0).abs() < 1e-6); + } +} diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs new file mode 100644 index 000000000..20af8ba26 --- /dev/null +++ b/crates/horizon-client/src/mobs/living.rs @@ -0,0 +1,450 @@ +//! `LivingEntity` movement for mobs: `aiStep` input decay and jumping, +//! `travel` in air, water and lava (friction-scaled acceleration, gravity, +//! fluid slowdown and falling adjustment), fluid immersion heights, fall +//! damage, fire and the walk animation. +use super::{Mob, MobEvent, MobWorld}; +use crate::{blocks::Fluid, collisions::SceneCollisions}; +use horizon_core::geometry::{Aabb, Vec3}; + +#[derive(Clone, Copy, Debug, Default)] +pub struct Fluids { + pub water: f64, + pub lava: f64, + pub in_water: bool, + pub in_lava: bool, + pub eye_in_water: bool, +} +pub fn wrap(a: f32) -> f32 { + let mut a = a % 360.0; + if a >= 180.0 { + a -= 360.0; + } + if a < -180.0 { + a += 360.0; + } + a +} +impl MobWorld<'_> { + /// FluidState.getHeight: a full block under the same fluid, else amount / 9. + pub fn fluid_height(&self, x: i32, y: i32, z: i32) -> (Fluid, f64) { + let f = self.facts.get(self.world.block(x, y, z)); + if f.fluid == Fluid::None { + return (Fluid::None, 0.0); + } + let above = self.facts.get(self.world.block(x, y + 1, z)); + if above.fluid == f.fluid { + return (f.fluid, 1.0); + } + (f.fluid, f64::from(f.fluid_level) / 9.0) + } + /// Entity.updateFluidHeightAndDoFluidPushing heights over the deflated box. + pub fn fluids(&self, bounds: Aabb, eye_y: f64) -> Fluids { + let b = bounds.deflate(Vec3::new(0.001, 0.001, 0.001)); + let (lo, hi) = (b.min_position(), b.max_position()); + let mut out = Fluids::default(); + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + let (fluid, h) = self.fluid_height(x, y, z); + if fluid == Fluid::None { + continue; + } + let top = f64::from(y) + h; + if top >= lo.y { + let depth = top - lo.y; + match fluid { + Fluid::Water => { + out.water = out.water.max(depth); + out.in_water = true; + } + Fluid::Lava => { + out.lava = out.lava.max(depth); + out.in_lava = true; + } + Fluid::None => {} + } + } + } + } + } + let (fx, fz) = ((lo.x + hi.x) / 2.0, (lo.z + hi.z) / 2.0); + let ey = eye_y.floor() as i32; + let (fluid, h) = self.fluid_height(fx.floor() as i32, ey, fz.floor() as i32); + out.eye_in_water = fluid == Fluid::Water && eye_y < f64::from(ey) + h + 0.111_111_11; + out + } + pub fn no_collision(&self, b: Aabb) -> bool { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + scene.unobstructed(b).unwrap_or(false) + } +} +impl Mob { + pub fn eye_y(&self) -> f64 { + self.position.y + self.eye_height() + } + /// Entity dimensions: the type's, a class's BABY_DIMENSIONS, or the + /// slime size scaling. + pub fn dims(&self) -> (f64, f64, f64) { + let k = &self.kind; + let (mut w, mut h, mut e) = (k.width, k.height, k.eye_height); + if self.is_baby() { + match super::species::def(k.species).baby { + super::species::Baby::Abs(bw, bh, be) => (w, h, e) = (bw, bh, be), + super::species::Baby::Scale(s, eye) => { + (w, h, e) = (w * s, h * s, eye.unwrap_or(e * s)) + } + super::species::Baby::None => {} + } + } + if self.extra.size > 0 { + let s = f64::from(self.extra.size); + (w, h, e) = (w * s, h * s, e * s); + } + (w, h, e) + } + pub fn eye_height(&self) -> f64 { + self.dims().2 + } + pub fn width(&self) -> f32 { + self.dims().0 as f32 + } + pub fn height(&self) -> f32 { + self.dims().1 as f32 + } + pub fn is_baby(&self) -> bool { + self.extra.age < 0 + } + pub fn fluid_jump_threshold(&self) -> f64 { + if self.eye_height() < 0.4 { 0.0 } else { 0.4 } + } + pub fn is_in_liquid(&self) -> bool { + self.fluids.in_water || self.fluids.in_lava + } + fn affected_by_fluids(&self) -> bool { + true + } + /// Entity.moveRelative: input rotated by yaw and scaled to `speed`. + pub fn move_relative(&mut self, speed: f32, input: Vec3) { + let len_sq = input.x * input.x + input.y * input.y + input.z * input.z; + if len_sq < 1.0e-7 { + return; + } + let v = if len_sq > 1.0 { + let l = len_sq.sqrt(); + Vec3::new(input.x / l, input.y / l, input.z / l) + } else { + input + }; + let v = Vec3::new( + v.x * f64::from(speed), + v.y * f64::from(speed), + v.z * f64::from(speed), + ); + let (s, c) = ( + f64::from(self.yaw.to_radians().sin() as f32), + f64::from(self.yaw.to_radians().cos() as f32), + ); + self.velocity = Vec3::new( + self.velocity.x + (v.x * c - v.z * s), + self.velocity.y + v.y, + self.velocity.z + (v.z * c + v.x * s), + ); + } + /// Entity.move with block collisions and step-up; updates collision flags + /// and fall distance (Entity.checkFallDamage). + pub fn do_move(&mut self, w: &MobWorld, events: &mut Vec) { + let wanted = self.velocity; + let step = self.kind.step_height as f32; + let mut scene = SceneCollisions { + world: w.world, + binding: w.collision, + }; + let moved = scene + .resolve(self.bounds(), wanted, step, self.on_ground) + .unwrap_or(Vec3::ZERO); + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + let x_hit = (moved.x - wanted.x).abs() > 1.0e-5; + let z_hit = (moved.z - wanted.z).abs() > 1.0e-5; + self.horizontal_collision = x_hit || z_hit; + let vertical = (moved.y - wanted.y).abs() > 1.0e-5; + self.vertical_collision_below = vertical && wanted.y < 0.0; + self.on_ground = self.vertical_collision_below; + if x_hit { + self.velocity.x = 0.0; + } + if z_hit { + self.velocity.z = 0.0; + } + if vertical { + self.velocity.y = 0.0; + } + // Entity.checkFallDamage + if self.on_ground { + if self.fall_distance > 0.0 { + self.cause_fall_damage(events); + } + self.fall_distance = 0.0; + } else if moved.y < 0.0 { + self.fall_distance -= moved.y; + } + if self.fluids.in_water { + self.fall_distance = 0.0; + } + } + fn cause_fall_damage(&mut self, events: &mut Vec) { + if self.kind.flags.fall_immune { + return; + } + let power = self.fall_distance + 1.0e-6 - self.kind.safe_fall_distance; + let damage = (power * self.kind.fall_damage_multiplier).floor(); + if damage > 0.0 { + let at = [self.position.x, self.position.y, self.position.z]; + let sound = if damage > 4.0 { + "entity.generic.big_fall" + } else { + "entity.generic.small_fall" + }; + events.push(MobEvent::Sound(sound, at, 1.0, 1.0)); + self.damage(damage as f32, super::Damage::fall()); + } + } + /// LivingEntity.getFrictionInfluencedSpeed. + fn friction_speed(&self, friction: f32) -> f32 { + if self.on_ground { + if friction > 0.6 { + self.ai.speed * (0.216_000_02 / (friction * friction * friction)) + } else { + self.ai.speed + } + } else { + self.flying_speed() + } + } + fn flying_speed(&self) -> f32 { + 0.02 + } + fn gravity(&self) -> f64 { + self.kind.gravity + } + /// LivingEntity.travel. + pub fn travel(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { + if super::ai::custom_travel(self, w, input, events) { + return; + } + if self.kind.flags.flying { + return self.travel_flying(w, input, events); + } + let stands_on_fluid = self.kind.flags.lava_walker && self.fluids.in_lava; + if self.is_in_liquid() && self.affected_by_fluids() && !stands_on_fluid { + self.travel_in_fluid(w, input, events); + } else { + self.travel_in_air(w, input, events); + } + } + /// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag. + fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { + let (speed, drag) = if self.fluids.in_water { + (0.02, 0.8) + } else if self.fluids.in_lava { + (0.02, 0.5) + } else { + (self.kind.air_speed, 0.91) + }; + self.move_relative(speed, input); + self.do_move(w, events); + self.velocity = Vec3::new( + self.velocity.x * drag, + self.velocity.y * drag, + self.velocity.z * drag, + ); + } + fn block_friction(&self, w: &MobWorld) -> f32 { + // Entity.getBlockPosBelowThatAffectsMyMovement: 0.500001 below. + let x = self.position.x.floor() as i32; + let z = self.position.z.floor() as i32; + let y = (self.position.y - 0.500_001).floor() as i32; + w.facts.get(w.world.block(x, y, z)).friction + } + fn travel_in_air(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { + let friction = if self.on_ground { + self.block_friction(w) + } else { + 1.0 + }; + let speed = self.friction_speed(friction); + self.move_relative(speed, input); + if self.kind.flags.climber && self.horizontal_collision { + // Spider.onClimbable: handleOnClimbable clamps and resets the fall. + self.fall_distance = 0.0; + self.velocity = Vec3::new( + self.velocity.x.clamp(-0.15, 0.15), + self.velocity.y.max(-0.15), + self.velocity.z.clamp(-0.15, 0.15), + ); + } + self.do_move(w, events); + let mut movement = self.velocity; + if self.kind.flags.climber + && (self.horizontal_collision || self.ai.jumping) + && self.climbing + { + movement.y = 0.2; + } + let mut y = movement.y; + if self.extra.levitation > 0 { + y += (0.05 * 1.0 - movement.y) * 0.2; + } else { + y -= self.gravity(); + } + let drag = 0.91f32; + let f = friction * drag; + let vertical = if self.kind.flags.omnidirectional { + drag + } else { + 0.98 + }; + self.velocity = Vec3::new( + movement.x * f64::from(f), + y * f64::from(vertical), + movement.z * f64::from(f), + ); + } + fn travel_in_fluid(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { + let falling = self.velocity.y <= 0.0; + let old_y = self.position.y; + let gravity = self.gravity(); + if self.fluids.in_water { + let mut slow = self.kind.water_slowdown; + let mut speed = 0.02f32; + let mut efficiency = self.kind.water_efficiency as f32; + if !self.on_ground { + efficiency *= 0.5; + } + if efficiency > 0.0 { + slow += (0.546_000_06 - slow) * efficiency; + speed += (self.ai.speed - speed) * efficiency; + } + self.move_relative(speed, input); + self.do_move(w, events); + let mut m = self.velocity; + if self.horizontal_collision && self.kind.flags.climber { + m.y = 0.2; + } + m = Vec3::new(m.x * f64::from(slow), m.y * 0.8, m.z * f64::from(slow)); + self.velocity = fluid_falling(gravity, falling, m); + } else { + self.move_relative(0.02, input); + self.do_move(w, events); + if self.fluids.lava <= self.fluid_jump_threshold() { + self.velocity = Vec3::new( + self.velocity.x * 0.5, + self.velocity.y * 0.8, + self.velocity.z * 0.5, + ); + self.velocity = fluid_falling(gravity, falling, self.velocity); + } else { + self.velocity = Vec3::new( + self.velocity.x * 0.5, + self.velocity.y * 0.5, + self.velocity.z * 0.5, + ); + } + if gravity != 0.0 { + self.velocity.y -= gravity / 4.0; + } + } + // jumpOutOfFluid + let m = self.velocity; + if self.horizontal_collision + && w.no_collision(self.bounds().move_by(Vec3::new( + m.x, + m.y + 0.6 - self.position.y + old_y, + m.z, + ))) + { + self.velocity.y = 0.3; + } + } + /// The jump part of LivingEntity.aiStep. + pub fn handle_jumping(&mut self) { + if self.ai.jumping && self.affected_by_fluids() { + let (fluid_height, in_water_with_height) = if self.fluids.in_lava { + (self.fluids.lava, false) + } else { + ( + self.fluids.water, + self.fluids.in_water && self.fluids.water > 0.0, + ) + }; + let threshold = self.fluid_jump_threshold(); + if !in_water_with_height || self.on_ground && fluid_height <= threshold { + if !self.fluids.in_lava || self.on_ground && self.fluids.lava <= threshold { + if (self.on_ground || in_water_with_height && fluid_height <= threshold) + && self.ai.no_jump_delay == 0 + { + self.jump_from_ground(); + self.ai.no_jump_delay = 10; + } + } else { + self.jump_in_liquid(); + } + } else { + self.jump_in_liquid(); + } + } else { + self.ai.no_jump_delay = 0; + } + } + /// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3. + fn jump_in_liquid(&mut self) { + self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 }; + } + pub fn jump_from_ground(&mut self) { + let power = self.jump_power(); + if power > 1.0e-5 { + self.velocity.y = f64::from(power).max(self.velocity.y); + } + } + pub fn jump_power(&self) -> f32 { + self.kind.jump_strength as f32 + } + /// LivingEntity.updateWalkAnimation (client calculateEntityAnimation). + pub fn update_walk_animation(&mut self) { + let dy = if self.kind.flags.omnidirectional { + self.position.y - self.previous.y + } else { + 0.0 + }; + let dx = self.position.x - self.previous.x; + let dz = self.position.z - self.previous.z; + 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); + 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 { + self.limb_speed = 0.0; + } + } +} +/// LivingEntity.getFluidFallingAdjustedMovement. +fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 { + if gravity != 0.0 { + let y = if falling && (m.y - 0.005).abs() >= 0.003 && (m.y - gravity / 16.0).abs() < 0.003 { + -0.003 + } else { + m.y - gravity / 16.0 + }; + Vec3::new(m.x, y, m.z) + } else { + m + } +} diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs new file mode 100644 index 000000000..d2b318ff4 --- /dev/null +++ b/crates/horizon-client/src/mobs/nav.rs @@ -0,0 +1,587 @@ +//! `PathNavigation` and its ground, wall-climbing, water-bound, flying and +//! amphibious variants: path creation, waypoint following, corner cutting, +//! stuck detection and path timeouts. +use super::{ + Mob, MobWorld, + path::{Evaluator, Finder, Path, PathMob, PathType}, +}; +use horizon_core::geometry::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum NavKind { + #[default] + Ground, + WallClimber, + Water { + breach: bool, + }, + Flying, + Amphibious, +} +#[derive(Clone, Debug)] +pub struct Navigation { + pub kind: NavKind, + pub path: Option, + pub speed_modifier: f64, + tick: i64, + last_stuck_check: i64, + last_stuck_pos: Vec3, + timeout_node: [i32; 3], + timeout_timer: i64, + last_timeout_check: i64, + timeout_limit: f64, + pub max_distance_to_waypoint: f32, + delayed_recompute: bool, + time_last_recompute: i64, + pub target_pos: Option<[i32; 3]>, + reach_range: i32, + pub max_visited_multiplier: f32, + pub stuck: bool, + pub required_path_length: f32, + pub can_float: bool, + pub can_open_doors: bool, + pub can_pass_doors: bool, + pub can_walk_over_fences: bool, + pub avoid_sun: bool, + pub below_surface: bool, + /// WallClimberNavigation.pathToPosition + climb_to: Option<[i32; 3]>, +} +impl Default for Navigation { + fn default() -> Self { + Self { + kind: NavKind::Ground, + path: None, + speed_modifier: 0.0, + tick: 0, + last_stuck_check: 0, + last_stuck_pos: Vec3::ZERO, + timeout_node: [0; 3], + timeout_timer: 0, + last_timeout_check: 0, + timeout_limit: 0.0, + max_distance_to_waypoint: 0.5, + delayed_recompute: false, + time_last_recompute: 0, + target_pos: None, + reach_range: 0, + max_visited_multiplier: 1.0, + stuck: false, + required_path_length: 16.0, + can_float: false, + can_open_doors: false, + can_pass_doors: true, + can_walk_over_fences: false, + avoid_sun: false, + below_surface: false, + climb_to: None, + } + } +} +impl Navigation { + pub fn is_done(&self) -> bool { + self.path.as_ref().is_none_or(Path::is_done) + } + pub fn is_in_progress(&self) -> bool { + !self.is_done() + } + pub fn stop(&mut self) { + self.path = None; + } + fn reset_stuck_timeout(&mut self) { + self.timeout_node = [0; 3]; + self.timeout_timer = 0; + self.timeout_limit = 0.0; + self.stuck = false; + } + fn evaluator(&self) -> Evaluator { + match self.kind { + NavKind::Ground | NavKind::WallClimber => Evaluator::Walk, + NavKind::Water { breach } => Evaluator::Swim { breach }, + NavKind::Flying => Evaluator::Fly, + NavKind::Amphibious => Evaluator::Amphibious { + prefers_shallow: false, + }, + } + } + pub fn can_cut_corner(t: PathType) -> bool { + !matches!( + t, + PathType::FireInNeighbor | PathType::DamagingInNeighbor | PathType::WalkableDoor + ) + } +} +impl Mob { + pub fn path_mob(&self) -> PathMob { + PathMob { + position: self.position, + width: self.width(), + height: self.height(), + on_ground: self.on_ground, + in_water: self.fluids.in_water, + max_up_step: self.kind.step_height as f32, + max_fall_distance: self.max_fall_distance(), + malus: self.ai.malus, + can_float: self.ai.nav.can_float, + can_open_doors: self.ai.nav.can_open_doors, + can_pass_doors: self.ai.nav.can_pass_doors, + can_walk_over_fences: self.ai.nav.can_walk_over_fences, + stands_on_lava: self.kind.flags.lava_walker, + } + } + /// Mob.getMaxFallDistance (normal difficulty). + pub fn max_fall_distance(&self) -> i32 { + if self.ai.target.is_none() { + return 3; + } + let mut sacrifice = (self.health - self.kind.max_health * 0.33) as i32; + sacrifice -= (3 - 2) * 4; + sacrifice.max(0) + 3 + } + pub fn malus(&self, t: PathType) -> f32 { + self.ai.malus[t as usize].unwrap_or_else(|| t.malus()) + } + pub fn set_malus(&mut self, t: PathType, v: f32) { + self.ai.malus[t as usize] = Some(v); + } + fn max_path_length(&self) -> f32 { + (self.kind.follow_range as f32).max(self.ai.nav.required_path_length) + } + fn can_update_path(&self) -> bool { + match self.ai.nav.kind { + NavKind::Ground | NavKind::WallClimber => self.on_ground || self.is_in_liquid(), + NavKind::Water { breach } => breach || self.is_in_liquid(), + NavKind::Flying | NavKind::Amphibious => true, + } + } + fn temp_mob_pos(&self, w: &MobWorld) -> Vec3 { + match self.ai.nav.kind { + NavKind::Ground | NavKind::WallClimber => Vec3::new( + self.position.x, + f64::from(self.surface_y(w)), + self.position.z, + ), + NavKind::Water { .. } | NavKind::Amphibious => Vec3::new( + self.position.x, + self.position.y + f64::from(self.height()) * 0.5, + self.position.z, + ), + NavKind::Flying => self.position, + } + } + fn surface_y(&self, w: &MobWorld) -> i32 { + let (x, z) = ( + self.position.x.floor() as i32, + self.position.z.floor() as i32, + ); + if self.fluids.in_water && self.ai.nav.can_float { + let mut y = self.position.y.floor() as i32; + let start = y; + let mut steps = 0; + while w.facts.get(w.world.block(x, y, z)).fluid == crate::blocks::Fluid::Water { + y += 1; + steps += 1; + if steps > 16 { + return start; + } + } + y + } else { + (self.position.y + 0.5).floor() as i32 + } + } + /// GroundPathNavigation.findSurfacePosition. + fn surface_position(&self, w: &MobWorld, mut p: [i32; 3]) -> [i32; 3] { + let air = |p: [i32; 3]| w.facts.is_air(w.world.block(p[0], p[1], p[2])); + let solid = |p: [i32; 3]| w.solid(p[0], p[1], p[2]); + if air(p) { + let mut q = [p[0], p[1] - 1, p[2]]; + while q[1] >= crate::chunk::MIN_Y && air(q) { + q[1] -= 1; + } + if q[1] >= crate::chunk::MIN_Y { + return [q[0], q[1] + 1, q[2]]; + } + q[1] = p[1] + 1; + while q[1] <= 319 && air(q) { + q[1] += 1; + } + p = q; + } + if !solid(p) { + return p; + } + let mut q = [p[0], p[1] + 1, p[2]]; + while q[1] <= 319 && solid(q) { + q[1] += 1; + } + q + } + fn create_path_raw( + &mut self, + w: &MobWorld, + targets: &[[i32; 3]], + reach: i32, + max_len: f32, + ) -> Option { + if targets.is_empty() + || self.position.y < f64::from(crate::chunk::MIN_Y) + || !self.can_update_path() + { + return None; + } + if let (Some(path), Some(tp)) = (&self.ai.nav.path, self.ai.nav.target_pos) + && !path.is_done() + && targets.contains(&tp) + { + return Some(path.clone()); + } + let pm = self.path_mob(); + let max_visited = ((self.kind.follow_range * 16.0).floor() as f32 + * self.ai.nav.max_visited_multiplier) as i32; + let finder = Finder::new(w, &pm, self.ai.nav.evaluator()); + let path = finder.find(targets, max_len, reach, max_visited); + if let Some(p) = &path { + self.ai.nav.target_pos = Some(p.target); + self.ai.nav.reach_range = reach; + self.ai.nav.reset_stuck_timeout(); + } + path + } + /// PathNavigation.createPath(BlockPos, reach) with the ground surface search. + pub fn create_path_to(&mut self, w: &MobWorld, mut p: [i32; 3], reach: i32) -> Option { + match self.ai.nav.kind { + NavKind::Ground | NavKind::WallClimber => { + if !w.world.loaded(p[0], p[2]) { + return None; + } + if self.ai.nav.kind == NavKind::WallClimber { + self.ai.nav.climb_to = Some(p); + } + if !self.ai.nav.below_surface { + p = self.surface_position(w, p); + } + } + _ => {} + } + let max = self.max_path_length(); + self.create_path_raw(w, &[p], reach, max) + } + /// PathNavigation.createPath(Entity, reach). + pub fn create_path_to_entity( + &mut self, + w: &MobWorld, + at: [f64; 3], + reach: i32, + ) -> Option { + let p = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + self.create_path_to(w, p, reach) + } + pub fn nav_move_to_path(&mut self, path: Option, speed: f64) -> bool { + let Some(path) = path else { + self.ai.nav.path = None; + return false; + }; + if !path.same_as(self.ai.nav.path.as_ref()) { + self.ai.nav.path = Some(path); + } + if self.ai.nav.is_done() { + return false; + } + if self.ai.nav.path.as_ref().is_none_or(|p| p.nodes.is_empty()) { + return false; + } + self.ai.nav.speed_modifier = speed; + self.ai.nav.last_stuck_check = self.ai.nav.tick; + // getTempMobPos needs the world for ground navigation; position is close enough + // for the first stuck sample and is refreshed 100 ticks later. + self.ai.nav.last_stuck_pos = self.position; + true + } + /// PathNavigation.moveTo(x, y, z, speed): a path to the containing block. + pub fn nav_move_to(&mut self, w: &MobWorld, at: [f64; 3], speed: f64) -> bool { + let p = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + let path = self.create_path_to(w, p, 1); + self.nav_move_to_path(path, speed) + } + pub fn nav_move_to_entity( + &mut self, + w: &MobWorld, + at: [f64; 3], + reach: i32, + speed: f64, + ) -> bool { + let path = self.create_path_to_entity(w, at, reach); + if self.ai.nav.kind == NavKind::WallClimber && path.is_none() { + // WallClimberNavigation.moveTo(Entity): climb straight towards it. + self.ai.nav.climb_to = Some([ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]); + self.ai.nav.speed_modifier = speed; + return true; + } + path.is_some() && self.nav_move_to_path(path, speed) + } + pub fn nav_stop(&mut self) { + self.ai.nav.path = None; + } + fn recompute_path(&mut self, w: &MobWorld) { + if w.game_time - self.ai.nav.time_last_recompute <= 20 || !self.can_update_path() { + self.ai.nav.delayed_recompute = true; + } else if let Some(t) = self.ai.nav.target_pos { + self.ai.nav.path = None; + let reach = self.ai.nav.reach_range; + self.ai.nav.path = self.create_path_to(w, t, reach); + self.ai.nav.time_last_recompute = w.game_time; + self.ai.nav.delayed_recompute = false; + } + } + /// PathNavigation.tick. + pub fn nav_tick(&mut self, w: &MobWorld) { + self.ai.nav.tick += 1; + if self.ai.nav.delayed_recompute { + self.recompute_path(w); + } + if self.ai.nav.kind == NavKind::WallClimber && self.ai.nav.is_done() { + if let Some(t) = self.ai.nav.climb_to { + let width = f64::from(self.width()); + let center = |p: [i32; 3]| { + let (dx, dy, dz) = ( + f64::from(p[0]) + 0.5 - self.position.x, + f64::from(p[1]) + 0.5 - self.position.y, + f64::from(p[2]) + 0.5 - self.position.z, + ); + dx * dx + dy * dy + dz * dz < width * width + }; + let same_level = [t[0], self.position.y.floor() as i32, t[2]]; + if !center(t) && (self.position.y <= f64::from(t[1]) || !center(same_level)) { + let speed = self.ai.nav.speed_modifier; + self.ai.mov.set_wanted( + f64::from(t[0]), + f64::from(t[1]), + f64::from(t[2]), + speed, + ); + } else { + self.ai.nav.climb_to = None; + } + } + return; + } + if self.ai.nav.is_done() { + return; + } + if self.can_update_path() { + self.follow_the_path(w); + } else if let Some(path) = &self.ai.nav.path + && !path.is_done() + { + let mob = self.temp_mob_pos(w); + let pos = path.entity_pos_at(path.next, self.width()); + let advance = match self.ai.nav.kind { + NavKind::Flying => { + self.position.x.floor() == pos.x.floor() + && self.position.y.floor() == pos.y.floor() + && self.position.z.floor() == pos.z.floor() + } + _ => { + mob.y > pos.y + && !self.on_ground + && mob.x.floor() == pos.x.floor() + && mob.z.floor() == pos.z.floor() + } + }; + if advance && let Some(p) = &mut self.ai.nav.path { + p.advance(); + } + } + if let Some(path) = &self.ai.nav.path + && !path.is_done() + { + let target = path.entity_pos_at(path.next, self.width()); + let y = match self.ai.nav.kind { + NavKind::Ground | NavKind::WallClimber => { + let (bx, by, bz) = ( + target.x.floor() as i32, + target.y.floor() as i32, + target.z.floor() as i32, + ); + if w.facts.is_air(w.world.block(bx, by - 1, bz)) { + target.y + } else { + w.floor_level(bx, by, bz) + } + } + _ => target.y, + }; + let speed = self.ai.nav.speed_modifier; + self.ai.mov.set_wanted(target.x, y, target.z, speed); + } + } + fn follow_the_path(&mut self, w: &MobWorld) { + let mob_pos = self.temp_mob_pos(w); + let width = self.width(); + self.ai.nav.max_distance_to_waypoint = if width > 0.75 { + width / 2.0 + } else { + 0.75 - width / 2.0 + }; + let vertical = match self.ai.nav.kind { + NavKind::Water { .. } => 0.5, + _ => 1.0, + }; + let Some(path) = &self.ai.nav.path else { + return; + }; + let n = path.next_node(); + let xd = (self.position.x - (f64::from(n.x) + 0.5)).abs(); + let yd = (self.position.y - f64::from(n.y)).abs(); + let zd = (self.position.z - (f64::from(n.z) + 0.5)).abs(); + let max = f64::from(self.ai.nav.max_distance_to_waypoint); + let close = xd < max && zd < max && yd < vertical; + if close || Navigation::can_cut_corner(n.kind) && self.should_target_next_node(w, mob_pos) { + if let Some(p) = &mut self.ai.nav.path { + p.advance(); + } + } + self.do_stuck_detection(w, mob_pos); + } + fn should_target_next_node(&self, w: &MobWorld, mob: Vec3) -> bool { + let Some(path) = &self.ai.nav.path else { + return false; + }; + if path.next + 1 >= path.nodes.len() { + return false; + } + let n = path.nodes[path.next]; + let current = Vec3::new(f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5); + let d = |a: Vec3, b: Vec3| (a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2); + if d(mob, current) >= 4.0 { + return false; + } + if self.can_move_directly(w, mob, path.entity_pos_at(path.next, self.width())) { + return true; + } + let m = path.nodes[path.next + 1]; + let next = Vec3::new(f64::from(m.x) + 0.5, f64::from(m.y), f64::from(m.z) + 0.5); + let to_current = Vec3::new(current.x - mob.x, current.y - mob.y, current.z - mob.z); + let to_next = Vec3::new(next.x - mob.x, next.y - mob.y, next.z - mob.z); + let (cs, ns) = (to_current.length_squared(), to_next.length_squared()); + if !(ns < cs) && !(cs < 0.5) { + return false; + } + let a = to_current.normalize(); + let b = to_next.normalize(); + a.x * b.x + a.y * b.y + a.z * b.z < 0.0 + } + fn can_move_directly(&self, w: &MobWorld, from: Vec3, to: Vec3) -> bool { + match self.ai.nav.kind { + NavKind::Flying => w.clear_between( + from, + Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z), + true, + ), + NavKind::Water { .. } => w.clear_between( + from, + Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z), + false, + ), + NavKind::Amphibious if self.is_in_liquid() => w.clear_between( + from, + Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z), + false, + ), + _ => false, + } + } + fn do_stuck_detection(&mut self, w: &MobWorld, mob: Vec3) { + let speed = self.ai.speed; + let nav = &mut self.ai.nav; + if nav.tick - nav.last_stuck_check > 100 { + let effective = if speed >= 1.0 { speed } else { speed * speed }; + let threshold = f64::from(effective * 100.0 * 0.25); + let d = (mob.x - nav.last_stuck_pos.x).powi(2) + + (mob.y - nav.last_stuck_pos.y).powi(2) + + (mob.z - nav.last_stuck_pos.z).powi(2); + if d < threshold * threshold { + nav.stuck = true; + nav.path = None; + } else { + nav.stuck = false; + } + nav.last_stuck_check = nav.tick; + nav.last_stuck_pos = mob; + } + if let Some(path) = &nav.path + && !path.is_done() + { + let n = path.next_node(); + let pos = [n.x, n.y, n.z]; + if pos == nav.timeout_node { + nav.timeout_timer += w.game_time - nav.last_timeout_check; + } else { + nav.timeout_node = pos; + let c = Vec3::new(f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5); + let dist = + ((mob.x - c.x).powi(2) + (mob.y - c.y).powi(2) + (mob.z - c.z).powi(2)).sqrt(); + nav.timeout_limit = if speed > 0.0 { + dist / f64::from(speed) * 20.0 + } else { + 0.0 + }; + } + if nav.timeout_limit > 0.0 && nav.timeout_timer as f64 > nav.timeout_limit * 3.0 { + nav.reset_stuck_timeout(); + nav.path = None; + } + nav.last_timeout_check = w.game_time; + } + } + /// PathNavigation.isStableDestination for the mob's navigation. + pub fn stable_destination(&self, w: &MobWorld, p: [i32; 3]) -> bool { + match self.ai.nav.kind { + NavKind::Ground | NavKind::WallClimber => { + w.facts + .get(w.world.block(p[0], p[1] - 1, p[2])) + .solid_render + } + NavKind::Water { .. } => !w.facts.get(w.world.block(p[0], p[1], p[2])).solid_render, + NavKind::Flying => { + w.data.state(w.world.block(p[0], p[1], p[2])).flags & super::data::STURDY_TOP != 0 + } + NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])), + } + } + pub fn should_recompute_path(&self, p: [i32; 3]) -> bool { + if self.ai.nav.delayed_recompute { + return false; + } + let Some(path) = &self.ai.nav.path else { + return false; + }; + if path.is_done() || path.nodes.is_empty() { + return false; + } + let Some(end) = path.end() else { return false }; + let mid = [ + (f64::from(end.x) + self.position.x) / 2.0, + (f64::from(end.y) + self.position.y) / 2.0, + (f64::from(end.z) + self.position.z) / 2.0, + ]; + let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2) + + (f64::from(p[1]) + 0.5 - mid[1]).powi(2) + + (f64::from(p[2]) + 0.5 - mid[2]).powi(2); + let r = (path.nodes.len() - path.next) as f64; + d < r * r + } +} diff --git a/crates/horizon-client/src/mobs/path.rs b/crates/horizon-client/src/mobs/path.rs new file mode 100644 index 000000000..18119bb31 --- /dev/null +++ b/crates/horizon-client/src/mobs/path.rs @@ -0,0 +1,1385 @@ +//! Vanilla's A* pathfinder (`PathFinder`, `BinaryHeap`, `Node`, `Path`) with +//! the walking, swimming, flying and amphibious node evaluators +//! (`WalkNodeEvaluator`, `SwimNodeEvaluator`, `FlyNodeEvaluator`, +//! `AmphibiousNodeEvaluator`), ported rule for rule. +use super::{MobWorld, data}; +use crate::blocks::Fluid; +use horizon_core::geometry::{Aabb, Vec3}; +use std::collections::HashMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PathType { + Blocked, + Open, + Walkable, + WalkableDoor, + Trapdoor, + PowderSnow, + OnTopOfPowderSnow, + Fence, + Lava, + Water, + WaterBorder, + Rail, + UnpassableRail, + FireInNeighbor, + Fire, + DamagingInNeighbor, + Damaging, + DoorOpen, + DoorWoodClosed, + DoorIronClosed, + Breach, + Leaves, + StickyHoney, + Cocoa, + DamageCautious, + OnTopOfTrapdoor, + BigMobsCloseToDanger, +} +pub const PATH_TYPES: usize = 27; +impl PathType { + pub fn from_name(name: &str) -> Self { + match name { + "OPEN" => Self::Open, + "WALKABLE" => Self::Walkable, + "WALKABLE_DOOR" => Self::WalkableDoor, + "TRAPDOOR" => Self::Trapdoor, + "POWDER_SNOW" => Self::PowderSnow, + "ON_TOP_OF_POWDER_SNOW" => Self::OnTopOfPowderSnow, + "FENCE" => Self::Fence, + "LAVA" => Self::Lava, + "WATER" => Self::Water, + "WATER_BORDER" => Self::WaterBorder, + "RAIL" => Self::Rail, + "UNPASSABLE_RAIL" => Self::UnpassableRail, + "FIRE_IN_NEIGHBOR" => Self::FireInNeighbor, + "FIRE" => Self::Fire, + "DAMAGING_IN_NEIGHBOR" => Self::DamagingInNeighbor, + "DAMAGING" => Self::Damaging, + "DOOR_OPEN" => Self::DoorOpen, + "DOOR_WOOD_CLOSED" => Self::DoorWoodClosed, + "DOOR_IRON_CLOSED" => Self::DoorIronClosed, + "BREACH" => Self::Breach, + "LEAVES" => Self::Leaves, + "STICKY_HONEY" => Self::StickyHoney, + "COCOA" => Self::Cocoa, + "DAMAGE_CAUTIOUS" => Self::DamageCautious, + "ON_TOP_OF_TRAPDOOR" => Self::OnTopOfTrapdoor, + "BIG_MOBS_CLOSE_TO_DANGER" => Self::BigMobsCloseToDanger, + _ => Self::Blocked, + } + } + /// PathType's default malus. + pub fn malus(self) -> f32 { + match self { + Self::Blocked | Self::PowderSnow | Self::Fence | Self::Lava | Self::UnpassableRail => { + -1.0 + } + Self::Damaging | Self::DoorWoodClosed | Self::DoorIronClosed | Self::Leaves => -1.0, + Self::Water + | Self::WaterBorder + | Self::FireInNeighbor + | Self::DamagingInNeighbor + | Self::StickyHoney => 8.0, + Self::Fire => 16.0, + Self::Breach | Self::BigMobsCloseToDanger => 4.0, + _ => 0.0, + } + } +} + +impl MobWorld<'_> { + pub fn path_type_from_state(&self, x: i32, y: i32, z: i32) -> PathType { + self.data.state(self.world.block(x, y, z)).path + } + /// WalkNodeEvaluator.getPathTypeStatic. + pub fn path_type_static(&self, x: i32, y: i32, z: i32) -> PathType { + let t = self.path_type_from_state(x, y, z); + if t == PathType::Open && y >= MIN_Y + 1 { + match self.path_type_from_state(x, y - 1, z) { + PathType::Open | PathType::Water | PathType::Lava | PathType::Walkable => { + PathType::Open + } + PathType::Fire => PathType::Fire, + PathType::Damaging => PathType::Damaging, + PathType::StickyHoney => PathType::StickyHoney, + PathType::PowderSnow => PathType::OnTopOfPowderSnow, + PathType::DamageCautious => PathType::DamageCautious, + PathType::Trapdoor => PathType::OnTopOfTrapdoor, + _ => self.check_neighbours(x, y, z, PathType::Walkable), + } + } else { + t + } + } + /// WalkNodeEvaluator.checkNeighbourBlocks. + pub fn check_neighbours(&self, x: i32, y: i32, z: i32, t: PathType) -> PathType { + for dx in -1..=1 { + for dy in -1..=1 { + for dz in -1..=1 { + if dx != 0 || dz != 0 { + match self.path_type_from_state(x + dx, y + dy, z + dz) { + PathType::Damaging => return PathType::DamagingInNeighbor, + PathType::Fire | PathType::Lava => return PathType::FireInNeighbor, + PathType::Water => return PathType::WaterBorder, + PathType::DamageCautious => return PathType::DamageCautious, + _ => {} + } + } + } + } + } + t + } + /// WalkNodeEvaluator.getFloorLevel(level, pos). + pub fn floor_level(&self, x: i32, y: i32, z: i32) -> f64 { + f64::from(y - 1) + f64::from(self.data.state(self.world.block(x, y - 1, z)).top) + } +} + +/// The parts of a mob the node evaluators read (`Mob` accessors at prepare time). +#[derive(Clone, Debug)] +pub struct PathMob { + pub position: Vec3, + pub width: f32, + pub height: f32, + pub on_ground: bool, + pub in_water: bool, + pub max_up_step: f32, + pub max_fall_distance: i32, + pub malus: [Option; PATH_TYPES], + pub can_float: bool, + pub can_open_doors: bool, + pub can_pass_doors: bool, + pub can_walk_over_fences: bool, + /// Striders stand on lava (`canStandOnFluid`). + pub stands_on_lava: bool, +} +impl PathMob { + pub fn malus(&self, t: PathType) -> f32 { + self.malus[t as usize].unwrap_or_else(|| t.malus()) + } + pub fn bounds(&self) -> Aabb { + let w = f64::from(self.width) / 2.0; + Aabb::new( + Vec3::new(self.position.x - w, self.position.y, self.position.z - w), + Vec3::new( + self.position.x + w, + self.position.y + f64::from(self.height), + self.position.z + w, + ), + ) + } + fn block_position(&self) -> [i32; 3] { + [ + self.position.x.floor() as i32, + self.position.y.floor() as i32, + self.position.z.floor() as i32, + ] + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Evaluator { + Walk, + Swim { breach: bool }, + Fly, + Amphibious { prefers_shallow: bool }, +} + +#[derive(Clone, Debug)] +pub struct Node { + pub x: i32, + pub y: i32, + pub z: i32, + heap: i32, + g: f32, + h: f32, + f: f32, + came_from: Option, + pub closed: bool, + walked: f32, + pub cost_malus: f32, + pub kind: PathType, +} +impl Node { + fn new(x: i32, y: i32, z: i32) -> Self { + Self { + x, + y, + z, + heap: -1, + g: 0.0, + h: 0.0, + f: 0.0, + came_from: None, + closed: false, + walked: 0.0, + cost_malus: 0.0, + kind: PathType::Blocked, + } + } + fn distance(&self, x: i32, y: i32, z: i32) -> f32 { + let (dx, dy, dz) = ( + (x - self.x) as f32, + (y - self.y) as f32, + (z - self.z) as f32, + ); + (dx * dx + dy * dy + dz * dz).sqrt() + } + fn manhattan(&self, x: i32, y: i32, z: i32) -> f32 { + ((x - self.x).abs() + (y - self.y).abs() + (z - self.z).abs()) as f32 + } +} + +/// A computed path: node positions, the requested target and whether it was reached. +#[derive(Clone, Debug, PartialEq)] +pub struct Path { + pub nodes: Vec, + pub next: usize, + pub target: [i32; 3], + pub dist_to_target: f32, + pub reached: bool, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PathNode { + pub x: i32, + pub y: i32, + pub z: i32, + pub kind: PathType, +} +impl Path { + fn new(nodes: Vec, target: [i32; 3], reached: bool) -> Self { + let dist_to_target = nodes.last().map_or(f32::MAX, |n| { + ((n.x - target[0]).abs() + (n.y - target[1]).abs() + (n.z - target[2]).abs()) as f32 + }); + Self { + nodes, + next: 0, + target, + dist_to_target, + reached, + } + } + pub fn is_done(&self) -> bool { + self.next >= self.nodes.len() + } + pub fn advance(&mut self) { + self.next += 1; + } + pub fn end(&self) -> Option { + self.nodes.last().copied() + } + pub fn next_node(&self) -> PathNode { + self.nodes[self.next] + } + /// Path.getEntityPosAtNode: node corner plus half the mob's block width. + pub fn entity_pos_at(&self, index: usize, width: f32) -> Vec3 { + let n = self.nodes[index]; + let half = f64::from((width + 1.0) as i32) * 0.5; + Vec3::new(f64::from(n.x) + half, f64::from(n.y), f64::from(n.z) + half) + } + pub fn same_as(&self, other: Option<&Path>) -> bool { + other.is_some_and(|o| o.nodes == self.nodes) + } +} + +struct Target { + x: i32, + y: i32, + z: i32, + best_h: f32, + best: Option, + reached: bool, + pos: [i32; 3], +} + +/// One pathfinding query: the node arena, open set and per-query caches. +pub struct Finder<'a, 'w> { + w: &'a MobWorld<'w>, + mob: &'a PathMob, + eval: Evaluator, + nodes: Vec, + index: HashMap<(i32, i32, i32), u32>, + heap: Vec, + types: HashMap<(i32, i32, i32), PathType>, + collisions: HashMap<[u64; 6], bool>, + entity_width: i32, + entity_height: i32, + entity_depth: i32, +} + +const MIN_Y: i32 = crate::chunk::MIN_Y; + +impl<'a, 'w> Finder<'a, 'w> { + pub fn new(w: &'a MobWorld<'w>, mob: &'a PathMob, eval: Evaluator) -> Self { + Self { + w, + mob, + eval, + nodes: Vec::new(), + index: HashMap::new(), + heap: Vec::new(), + types: HashMap::new(), + collisions: HashMap::new(), + entity_width: (mob.width + 1.0).floor() as i32, + entity_height: (mob.height + 1.0).floor() as i32, + entity_depth: (mob.width + 1.0).floor() as i32, + } + } + /// Mob.getPathfindingMalus; AmphibiousNodeEvaluator.prepare overrides three + /// maluses for the duration of the query. + fn malus(&self, t: PathType) -> f32 { + if let Evaluator::Amphibious { .. } = self.eval { + match t { + PathType::Water => return 0.0, + PathType::Walkable => return 6.0, + PathType::WaterBorder => return 4.0, + _ => {} + } + } + self.mob.malus(t) + } + // --- world access ------------------------------------------------- + fn state(&self, x: i32, y: i32, z: i32) -> data::StateData { + self.w.data.state(self.w.world.block(x, y, z)) + } + fn from_state(&self, x: i32, y: i32, z: i32) -> PathType { + self.w.path_type_from_state(x, y, z) + } + fn fluid(&self, x: i32, y: i32, z: i32) -> Fluid { + self.w.facts.get(self.w.world.block(x, y, z)).fluid + } + fn is_air(&self, x: i32, y: i32, z: i32) -> bool { + self.w.facts.is_air(self.w.world.block(x, y, z)) + } + /// WalkNodeEvaluator.getFloorLevel(level, pos). + pub fn static_floor(&self, x: i32, y: i32, z: i32) -> f64 { + f64::from(y - 1) + f64::from(self.state(x, y - 1, z).top) + } + fn floor_level(&self, x: i32, y: i32, z: i32) -> f64 { + let amphibious = matches!(self.eval, Evaluator::Amphibious { .. }); + if (self.mob.can_float || amphibious) && self.fluid(x, y, z) == Fluid::Water { + f64::from(y) + 0.5 + } else { + self.static_floor(x, y, z) + } + } + fn has_collisions(&mut self, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + let key = [ + lo.x.to_bits(), + lo.y.to_bits(), + lo.z.to_bits(), + hi.x.to_bits(), + hi.y.to_bits(), + hi.z.to_bits(), + ]; + if let Some(v) = self.collisions.get(&key) { + return *v; + } + let v = !self.w.no_collision(b); + self.collisions.insert(key, v); + v + } + // --- path types ----------------------------------------------------- + /// WalkNodeEvaluator.getPathTypeStatic (+ the fly/amphibious overrides). + fn path_type(&self, x: i32, y: i32, z: i32) -> PathType { + match self.eval { + Evaluator::Fly => self.fly_path_type(x, y, z), + Evaluator::Amphibious { .. } => { + let t = self.from_state(x, y, z); + if t == PathType::Water { + for (dx, dy, dz) in [ + (0, -1, 0), + (0, 1, 0), + (0, 0, -1), + (0, 0, 1), + (-1, 0, 0), + (1, 0, 0), + ] { + if self.from_state(x + dx, y + dy, z + dz) == PathType::Blocked { + return PathType::WaterBorder; + } + } + PathType::Water + } else { + self.walk_path_type(x, y, z) + } + } + _ => self.walk_path_type(x, y, z), + } + } + pub fn walk_path_type(&self, x: i32, y: i32, z: i32) -> PathType { + self.w.path_type_static(x, y, z) + } + fn check_neighbours(&self, x: i32, y: i32, z: i32, t: PathType) -> PathType { + self.w.check_neighbours(x, y, z, t) + } + fn fly_path_type(&self, x: i32, y: i32, z: i32) -> PathType { + let mut t = self.from_state(x, y, z); + if t == PathType::Open && y >= MIN_Y + 1 { + let below = self.from_state(x, y - 1, z); + t = match below { + PathType::Fire | PathType::Lava => PathType::Fire, + PathType::Damaging => PathType::Damaging, + PathType::Cocoa => PathType::Cocoa, + PathType::Fence => { + if [x, y - 1, z] != self.mob.block_position() { + PathType::Fence + } else { + t + } + } + PathType::Walkable | PathType::Open | PathType::Water => PathType::Open, + _ => PathType::Walkable, + }; + } + if t == PathType::Walkable || t == PathType::Open { + t = self.check_neighbours(x, y, z, t); + } + t + } + fn within_bb(&self, x: i32, y: i32, z: i32) -> Vec { + let mut out = Vec::with_capacity(4); + let mp = self.mob.block_position(); + for dx in 0..self.entity_width { + for dy in 0..self.entity_height { + for dz in 0..self.entity_depth { + let mut t = self.path_type(x + dx, y + dy, z + dz); + if t == PathType::DoorWoodClosed + && self.mob.can_open_doors + && self.mob.can_pass_doors + { + t = PathType::WalkableDoor; + } + if t == PathType::DoorOpen && !self.mob.can_pass_doors { + t = PathType::Blocked; + } + if t == PathType::Rail + && self.path_type(mp[0], mp[1], mp[2]) != PathType::Rail + && self.path_type(mp[0], mp[1] - 1, mp[2]) != PathType::Rail + { + t = PathType::UnpassableRail; + } + if !out.contains(&t) { + out.push(t); + } + } + } + } + out + } + /// WalkNodeEvaluator.getPathTypeOfMob. + fn path_type_of_mob(&self, x: i32, y: i32, z: i32) -> PathType { + if let Evaluator::Swim { .. } = self.eval { + return self.swim_path_type(x, y, z); + } + let mut types = self.within_bb(x, y, z); + // EnumSet iteration follows declaration order. + types.sort_by_key(|t| *t as u8); + if types.len() == 1 { + return types[0]; + } + if types.contains(&PathType::Fence) { + return PathType::Fence; + } + if types.contains(&PathType::UnpassableRail) { + return PathType::UnpassableRail; + } + let mut highest = PathType::Blocked; + let mut highest_malus = self.malus(highest); + for t in &types { + let m = self.malus(*t); + if m < 0.0 { + return *t; + } + if m >= highest_malus { + highest_malus = m; + highest = *t; + } + } + let current = self.path_type(x, y, z); + if self.entity_width > 1 { + let cheaper = self.malus(current) < highest_malus; + if cheaper && self.malus(PathType::BigMobsCloseToDanger) < highest_malus { + PathType::BigMobsCloseToDanger + } else { + highest + } + } else if current == PathType::Open && highest != PathType::Open && highest_malus == 0.0 { + PathType::Open + } else { + highest + } + } + fn swim_path_type(&self, x: i32, y: i32, z: i32) -> PathType { + let mut last = (x, y, z); + for xx in x..x + self.entity_width { + for yy in y..y + self.entity_height { + for zz in z..z + self.entity_depth { + let fluid = self.fluid(xx, yy, zz); + let below = self.state(xx, yy - 1, zz); + if fluid == Fluid::None + && below.flags & data::WATER != 0 + && self.is_air(xx, yy, zz) + { + return PathType::Breach; + } + if fluid != Fluid::Water { + return PathType::Blocked; + } + last = (xx, yy, zz); + } + } + } + if self.state(last.0, last.1, last.2).flags & data::WATER != 0 { + PathType::Water + } else { + PathType::Blocked + } + } + fn cached(&mut self, x: i32, y: i32, z: i32) -> PathType { + if let Some(t) = self.types.get(&(x, y, z)) { + return *t; + } + let t = self.path_type_of_mob(x, y, z); + self.types.insert((x, y, z), t); + t + } + // --- node arena ------------------------------------------------------- + fn node(&mut self, x: i32, y: i32, z: i32) -> u32 { + if let Some(i) = self.index.get(&(x, y, z)) { + return *i; + } + let i = self.nodes.len() as u32; + self.nodes.push(Node::new(x, y, z)); + self.index.insert((x, y, z), i); + i + } + fn start_node(&mut self, x: i32, y: i32, z: i32) -> u32 { + let n = self.node(x, y, z); + let t = self.cached(x, y, z); + let m = self.malus(t); + let node = &mut self.nodes[n as usize]; + node.kind = t; + node.cost_malus = m; + n + } + fn can_start_at(&mut self, x: i32, y: i32, z: i32) -> bool { + let t = self.cached(x, y, z); + if self.eval == Evaluator::Fly { + return self.malus(t) >= 0.0; + } + t != PathType::Open && self.malus(t) >= 0.0 + } + fn start(&mut self) -> Option { + let m = self.mob.clone(); + let p = m.position; + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + match self.eval { + Evaluator::Swim { .. } => { + return Some(self.node( + lo.x.floor() as i32, + (lo.y + 0.5).floor() as i32, + lo.z.floor() as i32, + )); + } + Evaluator::Amphibious { .. } if m.in_water => { + return Some(self.start_node( + lo.x.floor() as i32, + (lo.y + 0.5).floor() as i32, + lo.z.floor() as i32, + )); + } + Evaluator::Fly => { + let (bx, bz) = (p.x.floor() as i32, p.z.floor() as i32); + let mut start_y; + if m.can_float && m.in_water { + start_y = p.y.floor() as i32; + while &*self.w.facts.get(self.w.world.block(bx, start_y, bz)).name + == "minecraft:water" + { + start_y += 1; + } + } else { + start_y = (p.y + 0.5).floor() as i32; + } + if !self.can_start_at(bx, start_y, bz) { + let by = p.y.floor() as i32; + for (cx, cz) in [(lo.x, lo.z), (lo.x, hi.z), (hi.x, lo.z), (hi.x, hi.z)] { + let (cx, cz) = (cx.floor() as i32, cz.floor() as i32); + if self.can_start_at(cx, by, cz) { + return Some(self.start_node(cx, by, cz)); + } + } + } + return Some(self.start_node(bx, start_y, bz)); + } + _ => {} + } + // WalkNodeEvaluator.getStart + let (bx, bz) = (p.x.floor() as i32, p.z.floor() as i32); + let mut start_y = p.y.floor() as i32; + let fluid_at = |s: &Self, y: i32| s.fluid(bx, y, bz); + if !(m.stands_on_lava && fluid_at(self, start_y) == Fluid::Lava) { + if m.can_float && fluid_at(self, start_y) == Fluid::Water { + while fluid_at(self, start_y) == Fluid::Water { + start_y += 1; + } + start_y -= 1; + } else if m.on_ground { + start_y = (p.y + 0.5).floor() as i32; + } else { + let mut y = (p.y + 1.0).floor() as i32; + while y > MIN_Y { + start_y = y; + y -= 1; + let s = self.w.world.block(bx, y, bz); + if !self.w.facts.is_air(s) && self.w.data.state(s).flags & data::LAND == 0 { + break; + } + } + } + } else { + while m.stands_on_lava && fluid_at(self, start_y) == Fluid::Lava { + start_y += 1; + } + start_y -= 1; + } + if !self.can_start_at(bx, start_y, bz) { + for (cx, cz) in [(lo.x, lo.z), (lo.x, hi.z), (hi.x, lo.z), (hi.x, hi.z)] { + let (cx, cz) = (cx.floor() as i32, cz.floor() as i32); + if self.can_start_at(cx, start_y, cz) { + return Some(self.start_node(cx, start_y, cz)); + } + } + } + Some(self.start_node(bx, start_y, bz)) + } + // --- walking neighbours ---------------------------------------------- + fn node_update_max(&mut self, x: i32, y: i32, z: i32, t: PathType, cost: f32) -> u32 { + let n = self.node(x, y, z); + let node = &mut self.nodes[n as usize]; + node.kind = t; + node.cost_malus = node.cost_malus.max(cost); + n + } + fn blocked_node(&mut self, x: i32, y: i32, z: i32) -> u32 { + let n = self.node(x, y, z); + let node = &mut self.nodes[n as usize]; + node.kind = PathType::Blocked; + node.cost_malus = -1.0; + n + } + fn closed_node(&mut self, x: i32, y: i32, z: i32, t: PathType) -> u32 { + let n = self.node(x, y, z); + let node = &mut self.nodes[n as usize]; + node.closed = true; + node.kind = t; + node.cost_malus = t.malus(); + n + } + fn jump_height(&self) -> f64 { + f64::from(self.mob.max_up_step).max(1.125) + } + fn partial_collision(t: PathType) -> bool { + matches!( + t, + PathType::Fence | PathType::DoorWoodClosed | PathType::DoorIronClosed + ) + } + fn can_reach_without_collision(&mut self, n: u32) -> bool { + let (nx, ny, nz) = { + let node = &self.nodes[n as usize]; + (node.x, node.y, node.z) + }; + let mut bb = self.mob.bounds(); + let size = { + let (lo, hi) = (bb.min_position(), bb.max_position()); + ((hi.x - lo.x) + (hi.y - lo.y) + (hi.z - lo.z)) / 3.0 + }; + let (lo, hi) = (bb.min_position(), bb.max_position()); + let p = self.mob.position; + let mut delta = Vec3::new( + f64::from(nx) - p.x + (hi.x - lo.x) / 2.0, + f64::from(ny) - p.y + (hi.y - lo.y) / 2.0, + f64::from(nz) - p.z + (hi.z - lo.z) / 2.0, + ); + let len = (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z).sqrt(); + let steps = (len / size).ceil().max(1.0) as i32; + delta = Vec3::new( + delta.x / f64::from(steps), + delta.y / f64::from(steps), + delta.z / f64::from(steps), + ); + for _ in 1..=steps { + bb = bb.move_by(delta); + if self.has_collisions(bb) { + return false; + } + } + true + } + #[allow(clippy::too_many_arguments)] + fn find_accepted( + &mut self, + x: i32, + y: i32, + z: i32, + jump: i32, + node_height: f64, + dir: (i32, i32), + current: PathType, + ) -> Option { + let amphibious = matches!(self.eval, Evaluator::Amphibious { .. }); + let max_y_target = self.floor_level(x, y, z); + if max_y_target - node_height > self.jump_height() { + return None; + } + let t = self.cached(x, y, z); + let cost = self.malus(t); + let mut best = None; + if cost >= 0.0 { + best = Some(self.node_update_max(x, y, z, t, cost)); + } + if Self::partial_collision(current) + && let Some(b) = best + && self.nodes[b as usize].cost_malus >= 0.0 + && !self.can_reach_without_collision(b) + { + best = None; + } + if t == PathType::Walkable || (amphibious && t == PathType::Water) { + return best; + } + let best_cost_negative = best.is_none_or(|b| self.nodes[b as usize].cost_malus < 0.0); + if best_cost_negative + && jump > 0 + && (t != PathType::Fence || self.mob.can_walk_over_fences) + && t != PathType::UnpassableRail + && t != PathType::Trapdoor + && t != PathType::PowderSnow + { + best = self.try_jump_on(x, y, z, jump, node_height, dir, current); + } else if !amphibious && t == PathType::Water && !self.mob.can_float { + best = self.first_non_water_below(x, y, z, best); + } else if t == PathType::Open { + best = Some(self.first_ground_below(x, y, z)); + } else if Self::partial_collision(t) && best.is_none() { + best = Some(self.closed_node(x, y, z, t)); + } + best + } + #[allow(clippy::too_many_arguments)] + fn try_jump_on( + &mut self, + x: i32, + y: i32, + z: i32, + jump: i32, + node_height: f64, + dir: (i32, i32), + current: PathType, + ) -> Option { + let above = self.find_accepted(x, y + 1, z, jump - 1, node_height, dir, current)?; + if self.mob.width >= 1.0 { + return Some(above); + } + let (ak, ax, ay, az) = { + let n = &self.nodes[above as usize]; + (n.kind, n.x, n.y, n.z) + }; + if ak != PathType::Open && ak != PathType::Walkable { + return Some(above); + } + let cx = f64::from(x - dir.0) + 0.5; + let cz = f64::from(z - dir.1) + 0.5; + let half = f64::from(self.mob.width) / 2.0; + let grow = Aabb::new( + Vec3::new( + cx - half, + self.floor_level(cx.floor() as i32, y + 1, cz.floor() as i32) + 0.001, + cz - half, + ), + Vec3::new( + cx + half, + f64::from(self.mob.height) + self.floor_level(ax, ay, az) - 0.002, + cz + half, + ), + ); + if self.has_collisions(grow) { + None + } else { + Some(above) + } + } + fn first_non_water_below( + &mut self, + x: i32, + mut y: i32, + z: i32, + mut best: Option, + ) -> Option { + y -= 1; + while y > MIN_Y { + let t = self.cached(x, y, z); + if t != PathType::Water { + return best; + } + let m = self.malus(t); + best = Some(self.node_update_max(x, y, z, t, m)); + y -= 1; + } + best + } + fn first_ground_below(&mut self, x: i32, y: i32, z: i32) -> u32 { + let mut cy = y - 1; + while cy >= MIN_Y { + if y - cy > self.mob.max_fall_distance { + return self.blocked_node(x, cy, z); + } + let t = self.cached(x, cy, z); + let cost = self.malus(t); + if t != PathType::Open { + if cost >= 0.0 { + return self.node_update_max(x, cy, z, t, cost); + } + return self.blocked_node(x, cy, z); + } + cy -= 1; + } + self.blocked_node(x, y, z) + } + fn neighbor_valid(&self, n: Option, current: u32) -> bool { + n.is_some_and(|n| { + let node = &self.nodes[n as usize]; + !node.closed + && (node.cost_malus >= 0.0 || self.nodes[current as usize].cost_malus < 0.0) + }) + } + fn diagonal_pair_valid(&self, pos: u32, ew: Option, ns: Option) -> bool { + let (Some(ew), Some(ns)) = (ew, ns) else { + return false; + }; + let (p, e, n) = ( + &self.nodes[pos as usize], + &self.nodes[ew as usize], + &self.nodes[ns as usize], + ); + if n.y > p.y || e.y > p.y { + return false; + } + if e.kind == PathType::WalkableDoor || n.kind == PathType::WalkableDoor { + return false; + } + if self.mob.width > 1.0 && (e.cost_malus > 0.0 || n.cost_malus > 0.0) { + return false; + } + let between_posts = n.kind == PathType::Fence + && e.kind == PathType::Fence + && f64::from(self.mob.width) < 0.5; + (n.y < p.y || n.cost_malus >= 0.0 || between_posts) + && (e.y < p.y || e.cost_malus >= 0.0 || between_posts) + } + fn diagonal_valid(&self, d: Option) -> bool { + d.is_some_and(|d| { + let n = &self.nodes[d as usize]; + !n.closed && n.kind != PathType::WalkableDoor && n.cost_malus >= 0.0 + }) + } + fn walk_neighbors(&mut self, pos: u32, out: &mut Vec) { + let (px, py, pz) = { + let n = &self.nodes[pos as usize]; + (n.x, n.y, n.z) + }; + let above = self.cached(px, py + 1, pz); + let current = self.cached(px, py, pz); + let mut jump = 0; + if self.malus(above) >= 0.0 && current != PathType::StickyHoney { + jump = self.mob.max_up_step.max(1.0).floor() as i32; + } + let height = self.floor_level(px, py, pz); + // Direction.Plane.HORIZONTAL: north, east, south, west; 2D index S=0 W=1 N=2 E=3. + const DIRS: [(i32, i32, usize); 4] = [(0, -1, 2), (1, 0, 3), (0, 1, 0), (-1, 0, 1)]; + let mut by2d: [Option; 4] = [None; 4]; + for (dx, dz, i2) in DIRS { + let n = self.find_accepted(px + dx, py, pz + dz, jump, height, (dx, dz), current); + by2d[i2] = n; + if self.neighbor_valid(n, pos) { + out.push(n.unwrap_or_default()); + } + } + // Clockwise of north is east, of east south, of south west, of west north. + let clockwise = |i2: usize| match i2 { + 2 => 3, + 3 => 0, + 0 => 1, + _ => 2, + }; + for (dx, dz, i2) in DIRS { + let c = clockwise(i2); + let (cdx, cdz) = match c { + 0 => (0, 1), + 1 => (-1, 0), + 2 => (0, -1), + _ => (1, 0), + }; + if self.diagonal_pair_valid(pos, by2d[i2], by2d[c]) { + let d = self.find_accepted( + px + dx + cdx, + py, + pz + dz + cdz, + jump, + height, + (dx, dz), + current, + ); + if self.diagonal_valid(d) { + out.push(d.unwrap_or_default()); + } + } + } + if let Evaluator::Amphibious { prefers_shallow } = self.eval { + let up = self.find_accepted(px, py + 1, pz, (jump - 1).max(0), height, (0, 0), current); + let down = self.find_accepted(px, py - 1, pz, jump, height, (0, 0), current); + if self.neighbor_valid(up, pos) + && up.is_some_and(|u| self.nodes[u as usize].kind == PathType::Water) + { + out.push(up.unwrap_or_default()); + } + if self.neighbor_valid(down, pos) + && down.is_some_and(|d| self.nodes[d as usize].kind == PathType::Water) + && current != PathType::Trapdoor + { + out.push(down.unwrap_or_default()); + } + if prefers_shallow { + for &n in out.iter() { + let node = &mut self.nodes[n as usize]; + if node.kind == PathType::Water && node.y < 63 - 10 { + node.cost_malus += 1.0; + } + } + } + } + } + // --- swimming / flying neighbours ------------------------------------ + fn swim_accepted(&mut self, x: i32, y: i32, z: i32) -> Option { + let breach = matches!(self.eval, Evaluator::Swim { breach: true }); + let t = self.cached(x, y, z); + if (breach && t == PathType::Breach) || t == PathType::Water { + let cost = self.malus(t); + if cost >= 0.0 { + let n = self.node_update_max(x, y, z, t, cost); + if self.fluid(x, y, z) == Fluid::None { + self.nodes[n as usize].cost_malus += 8.0; + } + return Some(n); + } + } + None + } + fn swim_neighbors(&mut self, pos: u32, out: &mut Vec) { + let (px, py, pz) = { + let n = &self.nodes[pos as usize]; + (n.x, n.y, n.z) + }; + let open = |s: &Self, n: Option| n.is_some_and(|n| !s.nodes[n as usize].closed); + let malus = + |s: &Self, n: Option| n.is_some_and(|n| s.nodes[n as usize].cost_malus >= 0.0); + // Direction.values(): down, up, north, south, west, east. + let mut by_dir: HashMap<(i32, i32, i32), Option> = HashMap::new(); + for (dx, dy, dz) in [ + (0, -1, 0), + (0, 1, 0), + (0, 0, -1), + (0, 0, 1), + (-1, 0, 0), + (1, 0, 0), + ] { + let n = self.swim_accepted(px + dx, py + dy, pz + dz); + by_dir.insert((dx, dy, dz), n); + if open(self, n) { + out.push(n.unwrap_or_default()); + } + } + for ((dx, dz), (cx, cz)) in [ + ((0, -1), (1, 0)), + ((1, 0), (0, 1)), + ((0, 1), (-1, 0)), + ((-1, 0), (0, -1)), + ] { + if malus(self, by_dir[&(dx, 0, dz)]) && malus(self, by_dir[&(cx, 0, cz)]) { + let d = self.swim_accepted(px + dx + cx, py, pz + dz + cz); + if open(self, d) { + out.push(d.unwrap_or_default()); + } + } + } + } + fn fly_accepted(&mut self, x: i32, y: i32, z: i32) -> Option { + let t = self.cached(x, y, z); + let cost = self.malus(t); + if cost >= 0.0 { + let n = self.node_update_max(x, y, z, t, cost); + if t == PathType::Walkable { + self.nodes[n as usize].cost_malus += 1.0; + } + return Some(n); + } + None + } + fn fly_neighbors(&mut self, pos: u32, out: &mut Vec) { + let (px, py, pz) = { + let n = &self.nodes[pos as usize]; + (n.x, n.y, n.z) + }; + let f = |s: &mut Self, dx: i32, dy: i32, dz: i32| s.fly_accepted(px + dx, py + dy, pz + dz); + let open = |s: &Self, n: Option| n.is_some_and(|n| !s.nodes[n as usize].closed); + let m = |s: &Self, n: Option| n.is_some_and(|n| s.nodes[n as usize].cost_malus >= 0.0); + let south = f(self, 0, 0, 1); + let west = f(self, -1, 0, 0); + let east = f(self, 1, 0, 0); + let north = f(self, 0, 0, -1); + let up = f(self, 0, 1, 0); + let down = f(self, 0, -1, 0); + for n in [south, west, east, north, up, down] { + if open(self, n) { + out.push(n.unwrap_or_default()); + } + } + let push = |s: &mut Self, n: Option, ok: bool, out: &mut Vec| { + if open(s, n) && ok { + out.push(n.unwrap_or_default()); + } + }; + let south_up = f(self, 0, 1, 1); + let ok = m(self, south) && m(self, up); + push(self, south_up, ok, out); + let west_up = f(self, -1, 1, 0); + let ok = m(self, west) && m(self, up); + push(self, west_up, ok, out); + let east_up = f(self, 1, 1, 0); + let ok = m(self, east) && m(self, up); + push(self, east_up, ok, out); + let north_up = f(self, 0, 1, -1); + let ok = m(self, north) && m(self, up); + push(self, north_up, ok, out); + let south_down = f(self, 0, -1, 1); + let ok = m(self, south) && m(self, down); + push(self, south_down, ok, out); + let west_down = f(self, -1, -1, 0); + let ok = m(self, west) && m(self, down); + push(self, west_down, ok, out); + let east_down = f(self, 1, -1, 0); + let ok = m(self, east) && m(self, down); + push(self, east_down, ok, out); + let north_down = f(self, 0, -1, -1); + let ok = m(self, north) && m(self, down); + push(self, north_down, ok, out); + let north_east = f(self, 1, 0, -1); + let ok = m(self, north) && m(self, east); + push(self, north_east, ok, out); + let south_east = f(self, 1, 0, 1); + let ok = m(self, south) && m(self, east); + push(self, south_east, ok, out); + let north_west = f(self, -1, 0, -1); + let ok = m(self, north) && m(self, west); + push(self, north_west, ok, out); + let south_west = f(self, -1, 0, 1); + let ok = m(self, south) && m(self, west); + push(self, south_west, ok, out); + let neu = f(self, 1, 1, -1); + let ok = m(self, north_east) + && m(self, north) + && m(self, east) + && m(self, up) + && m(self, north_up) + && m(self, east_up); + push(self, neu, ok, out); + let seu = f(self, 1, 1, 1); + let ok = m(self, south_east) + && m(self, south) + && m(self, east) + && m(self, up) + && m(self, south_up) + && m(self, east_up); + push(self, seu, ok, out); + let nwu = f(self, -1, 1, -1); + let ok = m(self, north_west) + && m(self, north) + && m(self, west) + && m(self, up) + && m(self, north_up) + && m(self, west_up); + push(self, nwu, ok, out); + let swu = f(self, -1, 1, 1); + let ok = m(self, south_west) + && m(self, south) + && m(self, west) + && m(self, up) + && m(self, south_up) + && m(self, west_up); + push(self, swu, ok, out); + let ned = f(self, 1, -1, -1); + let ok = m(self, north_east) + && m(self, north) + && m(self, east) + && m(self, down) + && m(self, north_down) + && m(self, east_down); + push(self, ned, ok, out); + let sed = f(self, 1, -1, 1); + let ok = m(self, south_east) + && m(self, south) + && m(self, east) + && m(self, down) + && m(self, south_down) + && m(self, east_down); + push(self, sed, ok, out); + let nwd = f(self, -1, -1, -1); + let ok = m(self, north_west) + && m(self, north) + && m(self, west) + && m(self, down) + && m(self, north_down) + && m(self, west_down); + push(self, nwd, ok, out); + let swd = f(self, -1, -1, 1); + let ok = m(self, south_west) + && m(self, south) + && m(self, west) + && m(self, down) + && m(self, south_down) + && m(self, west_down); + push(self, swd, ok, out); + } + // --- binary heap (vanilla BinaryHeap) -------------------------------- + fn heap_insert(&mut self, n: u32) { + let i = self.heap.len(); + self.heap.push(n); + self.nodes[n as usize].heap = i as i32; + self.up_heap(i); + } + fn heap_pop(&mut self) -> u32 { + let popped = self.heap[0]; + let last = self.heap.pop().unwrap_or(popped); + if !self.heap.is_empty() { + self.heap[0] = last; + self.nodes[last as usize].heap = 0; + self.down_heap(0); + } + self.nodes[popped as usize].heap = -1; + popped + } + fn change_cost(&mut self, n: u32, cost: f32) { + let old = self.nodes[n as usize].f; + self.nodes[n as usize].f = cost; + let i = self.nodes[n as usize].heap as usize; + if cost < old { + self.up_heap(i); + } else { + self.down_heap(i); + } + } + fn up_heap(&mut self, mut i: usize) { + let node = self.heap[i]; + let cost = self.nodes[node as usize].f; + while i > 0 { + let parent_i = (i - 1) >> 1; + let parent = self.heap[parent_i]; + if cost >= self.nodes[parent as usize].f { + break; + } + self.heap[i] = parent; + self.nodes[parent as usize].heap = i as i32; + i = parent_i; + } + self.heap[i] = node; + self.nodes[node as usize].heap = i as i32; + } + fn down_heap(&mut self, mut i: usize) { + let node = self.heap[i]; + let cost = self.nodes[node as usize].f; + let size = self.heap.len(); + loop { + let left_i = 1 + (i << 1); + let right_i = left_i + 1; + if left_i >= size { + break; + } + let left = self.heap[left_i]; + let left_cost = self.nodes[left as usize].f; + let (right, right_cost) = if right_i >= size { + (u32::MAX, f32::INFINITY) + } else { + ( + self.heap[right_i], + self.nodes[self.heap[right_i] as usize].f, + ) + }; + if left_cost < right_cost { + if left_cost >= cost { + break; + } + self.heap[i] = left; + self.nodes[left as usize].heap = i as i32; + i = left_i; + } else { + if right_cost >= cost { + break; + } + self.heap[i] = right; + self.nodes[right as usize].heap = i as i32; + i = right_i; + } + } + self.heap[i] = node; + self.nodes[node as usize].heap = i as i32; + } + // --- PathFinder.findPath ------------------------------------------------ + fn best_h(&self, n: u32, targets: &mut [Target]) -> f32 { + let mut best = f32::MAX; + let node = &self.nodes[n as usize]; + for t in targets.iter_mut() { + let h = node.distance(t.x, t.y, t.z); + if h < t.best_h { + t.best_h = h; + t.best = Some(n); + } + best = best.min(h); + } + best + } + /// PathFinder.findPath over several target positions. + pub fn find( + mut self, + positions: &[[i32; 3]], + max_path_length: f32, + reach_range: i32, + max_visited: i32, + ) -> Option { + let from = self.start()?; + let mut targets: Vec = positions + .iter() + .map(|p| { + // AmphibiousNodeEvaluator.getTarget floors y + 0.5 (the same block). + let n = self.node(p[0], p[1], p[2]); + let node = &self.nodes[n as usize]; + Target { + x: node.x, + y: node.y, + z: node.z, + best_h: f32::MAX, + best: None, + reached: false, + pos: *p, + } + }) + .collect(); + self.nodes[from as usize].g = 0.0; + let h = self.best_h(from, &mut targets); + self.nodes[from as usize].h = h; + self.nodes[from as usize].f = h; + self.heap.clear(); + self.heap_insert(from); + let mut count = 0; + let mut neighbors = Vec::with_capacity(32); + let (fx, fy, fz) = { + let n = &self.nodes[from as usize]; + (n.x, n.y, n.z) + }; + while !self.heap.is_empty() { + count += 1; + if count >= max_visited { + break; + } + let current = self.heap_pop(); + self.nodes[current as usize].closed = true; + let mut any = false; + for t in targets.iter_mut() { + if self.nodes[current as usize].manhattan(t.x, t.y, t.z) <= reach_range as f32 { + t.reached = true; + any = true; + } + } + if any { + break; + } + if self.nodes[current as usize].distance(fx, fy, fz) >= max_path_length { + continue; + } + neighbors.clear(); + match self.eval { + Evaluator::Walk | Evaluator::Amphibious { .. } => { + self.walk_neighbors(current, &mut neighbors) + } + Evaluator::Swim { .. } => self.swim_neighbors(current, &mut neighbors), + Evaluator::Fly => self.fly_neighbors(current, &mut neighbors), + } + for &neighbor in &neighbors { + let (cx, cy, cz, cg, cw) = { + let c = &self.nodes[current as usize]; + (c.x, c.y, c.z, c.g, c.walked) + }; + let distance = self.nodes[neighbor as usize].distance(cx, cy, cz); + let walked = cw + distance; + self.nodes[neighbor as usize].walked = walked; + let tentative = cg + distance + self.nodes[neighbor as usize].cost_malus; + let in_open = self.nodes[neighbor as usize].heap >= 0; + if walked < max_path_length + && (!in_open || tentative < self.nodes[neighbor as usize].g) + { + self.nodes[neighbor as usize].came_from = Some(current); + self.nodes[neighbor as usize].g = tentative; + let h = self.best_h(neighbor, &mut targets) * 1.5; + self.nodes[neighbor as usize].h = h; + if in_open { + self.change_cost(neighbor, tentative + h); + } else { + self.nodes[neighbor as usize].f = tentative + h; + self.heap_insert(neighbor); + } + } + } + } + let reached: Vec<&Target> = targets.iter().filter(|t| t.reached).collect(); + let build = |s: &Self, t: &Target, reached: bool| -> Option { + let mut n = t.best?; + let mut nodes = vec![]; + loop { + let node = &s.nodes[n as usize]; + nodes.push(PathNode { + x: node.x, + y: node.y, + z: node.z, + kind: node.kind, + }); + match node.came_from { + Some(c) => n = c, + None => break, + } + } + nodes.reverse(); + Some(Path::new(nodes, t.pos, reached)) + }; + if !reached.is_empty() { + reached + .iter() + .filter_map(|t| build(&self, t, true)) + .min_by_key(|p| p.nodes.len()) + } else { + targets + .iter() + .filter_map(|t| build(&self, t, false)) + .min_by(|a, b| { + a.dist_to_target + .total_cmp(&b.dist_to_target) + .then(a.nodes.len().cmp(&b.nodes.len())) + }) + } + } +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs new file mode 100644 index 000000000..ae3859835 --- /dev/null +++ b/crates/horizon-client/src/mobs/render.rs @@ -0,0 +1,507 @@ +//! Mob rendering (`LivingEntityRenderer.submit` and the render layers): +//! variant/baby model and texture selection, setupRotations, per-species +//! scale, and extra layers (sheep wool, spider eyes, drowned/stray outer +//! layers, villager overlays, collars...). +use super::{ + Mob, MobData, Part, Species, + anim::{self, Poses}, + living::wrap, +}; +use crate::mesher::Vertex; +use std::f32::consts::PI; + +/// A texture lookup into the shared atlas (name without namespace -> uv rect). +pub type Atlas<'a> = &'a dyn Fn(&str) -> Option<[f32; 4]>; + +/// One draw of a model with a texture. +pub struct Layer { + pub model: String, + pub texture: String, + pub color: u32, + pub full_bright: bool, +} +/// DyeColor.getTextureDiffuseColor (RGB). +pub const DYE: [u32; 16] = [ + 0xF9FFFE, 0xF9801D, 0xC74EBD, 0x3AB3DA, 0xFED83D, 0x80C71F, 0xF38BAA, 0x474F52, 0x9D9D97, + 0x169C9C, 0x8932B8, 0x3C44AA, 0x835432, 0x5E7C16, 0xB02E26, 0x1D1D21, +]; +pub const DYE_NAMES: [&str; 16] = [ + "white", + "orange", + "magenta", + "light_blue", + "yellow", + "lime", + "pink", + "gray", + "light_gray", + "cyan", + "purple", + "blue", + "brown", + "green", + "red", + "black", +]; +/// ABGR vertex colour from an RGB value. +pub fn abgr(rgb: u32) -> u32 { + let (r, g, b) = ((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255); + 0xFF00_0000 | b << 16 | g << 8 | r +} +/// ColorLerper.Type.SHEEP colour: white is 0xE6E6E6, others 75% of the dye. +pub fn sheep_wool_rgb(color: u8) -> u32 { + if color == 0 { + return 0xE6E6E6; + } + let src = DYE[color as usize & 15]; + let f = |c: u32| ((c as f32 * 0.75).floor() as u32).min(255); + f(src >> 16 & 255) << 16 | f(src >> 8 & 255) << 8 | f(src & 255) +} +const VILLAGER_TYPES: [&str; 7] = [ + "plains", "desert", "jungle", "savanna", "snow", "swamp", "taiga", +]; +pub const PROFESSIONS: [&str; 15] = [ + "none", + "armorer", + "butcher", + "cartographer", + "cleric", + "farmer", + "fisherman", + "fletcher", + "leatherworker", + "librarian", + "mason", + "nitwit", + "shepherd", + "toolsmith", + "weaponsmith", +]; +fn baby_or(m: &Mob, adult: &str, baby: &str) -> String { + if m.is_baby() && m.kind.layer(baby).is_some() { + baby.to_owned() + } else { + adult.to_owned() + } +} +fn climate(m: &Mob) -> &'static str { + match m.extra.variant { + 1 => "warm", + 2 => "cold", + _ => "temperate", + } +} +/// The model layer key and texture for the mob's body. +pub fn body(m: &Mob) -> (String, String) { + use Species as S; + let baby = m.is_baby(); + let b = |s: &str| { + if baby { + format!("{s}_baby") + } else { + s.to_owned() + } + }; + match m.species() { + S::Pig => { + let model = if baby { + "pig_baby#main".into() + } else if m.extra.variant == 2 { + "cold_pig#main".into() + } else { + "pig#main".into() + }; + (model, b(&format!("entity/pig/pig_{}", climate(m)))) + } + S::Cow => { + let model = match (m.extra.variant, baby) { + (1, false) => "warm_cow#main", + (1, true) => "warm_cow_baby#main", + (2, false) => "cold_cow#main", + (2, true) => "cold_cow_baby#main", + (_, true) => "cow_baby#main", + _ => "cow#main", + }; + (model.into(), b(&format!("entity/cow/cow_{}", climate(m)))) + } + S::Mooshroom => ( + baby_or(m, "mooshroom#main", "mooshroom_baby#main"), + b(if m.extra.variant == 1 { + "entity/cow/mooshroom_brown" + } else { + "entity/cow/mooshroom_red" + }), + ), + S::Chicken => { + let model = if baby { + "chicken_baby#main" + } else if m.extra.variant == 2 { + "cold_chicken#main" + } else { + "chicken#main" + }; + ( + model.into(), + b(&format!("entity/chicken/chicken_{}", climate(m))), + ) + } + S::Sheep => ( + baby_or(m, "sheep#main", "sheep_baby#main"), + b("entity/sheep/sheep"), + ), + S::Zombie => ( + baby_or(m, "zombie#main", "zombie_baby#main"), + b("entity/zombie/zombie"), + ), + S::Husk => ( + baby_or(m, "husk#main", "husk_baby#main"), + b("entity/zombie/husk"), + ), + S::Drowned => ( + baby_or(m, "drowned#main", "drowned_baby#main"), + b("entity/zombie/drowned"), + ), + S::ZombieVillager => ( + baby_or(m, "zombie_villager#main", "zombie_villager_baby#main"), + "entity/zombie_villager/zombie_villager".into(), + ), + S::Villager => ( + baby_or(m, "villager#main", "villager_baby#main"), + b("entity/villager/villager"), + ), + S::Piglin => ( + baby_or(m, "piglin#main", "piglin_baby#main"), + b("entity/piglin/piglin"), + ), + S::ZombifiedPiglin => ( + baby_or(m, "zombified_piglin#main", "zombified_piglin_baby#main"), + b("entity/piglin/zombified_piglin"), + ), + S::Hoglin => ( + baby_or(m, "hoglin#main", "hoglin_baby#main"), + b("entity/hoglin/hoglin"), + ), + S::Zoglin => ( + baby_or(m, "zoglin#main", "zoglin_baby#main"), + b("entity/hoglin/zoglin"), + ), + S::Strider => ( + baby_or(m, "strider#main", "strider_baby#main"), + b(if m.extra.flag { + "entity/strider/strider_cold" + } else { + "entity/strider/strider" + }), + ), + _ => (m.kind.model_key(), m.kind.texture.clone()), + } +} +/// Extra render layers drawn over the body with the same pose. +pub fn layers(m: &Mob) -> Vec { + use Species as S; + let mut v = Vec::new(); + let white = 0xFFFF_FFFF; + let push = |v: &mut Vec, model: &str, texture: &str, color: u32, full_bright: bool| { + v.push(Layer { + model: model.into(), + texture: texture.into(), + color, + full_bright, + }) + }; + match m.species() { + S::Sheep if !m.extra.sheared => { + let color = abgr(sheep_wool_rgb(m.extra.color)); + if !m.is_baby() && m.extra.color != 0 { + push( + &mut v, + "sheep#wool_undercoat", + "entity/sheep/sheep_wool_undercoat", + color, + false, + ); + } + if m.is_baby() { + push( + &mut v, + "sheep_baby#wool", + "entity/sheep/sheep_wool_baby", + color, + false, + ); + } else { + push( + &mut v, + "sheep#wool", + "entity/sheep/sheep_wool", + color, + false, + ); + } + } + S::Spider | S::CaveSpider => push( + &mut v, + &m.kind.model_key(), + "entity/spider/spider_eyes", + white, + true, + ), + S::Enderman => push( + &mut v, + "enderman#main", + "entity/enderman/enderman_eyes", + white, + true, + ), + S::Phantom => push( + &mut v, + "phantom#main", + "entity/phantom/phantom_eyes", + white, + true, + ), + S::Drowned => { + if m.is_baby() { + push( + &mut v, + "drowned_baby#outer", + "entity/zombie/drowned_outer_layer_baby", + white, + false, + ); + } else { + push( + &mut v, + "drowned#outer", + "entity/zombie/drowned_outer_layer", + white, + false, + ); + } + } + S::Stray => push( + &mut v, + "stray#outer", + "entity/skeleton/stray_overlay", + white, + false, + ), + S::Bogged if !m.extra.sheared => push( + &mut v, + "bogged#outer", + "entity/skeleton/bogged_overlay", + white, + false, + ), + S::Creeper if m.extra.charged => {} + S::Villager | S::ZombieVillager => { + let base = if m.species() == S::Villager { + "villager" + } else { + "zombie_villager" + }; + let model = if m.is_baby() { + format!("{base}_baby#main") + } else { + format!("{base}#main") + }; + let t = VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()]; + let folder = if m.species() == S::Villager { + "entity/villager" + } else { + "entity/zombie_villager" + }; + let baby = if m.is_baby() && m.species() == S::Villager { + "baby/" + } else { + "" + }; + push( + &mut v, + &model, + &format!("{folder}/type/{baby}{t}"), + white, + false, + ); + let prof = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; + if !m.is_baby() && prof != "none" { + push( + &mut v, + &model, + &format!("{folder}/profession/{prof}"), + white, + false, + ); + if m.species() == S::Villager && prof != "nitwit" { + let level = ["stone", "iron", "gold", "emerald", "diamond"] + [(m.extra.variant3 as usize).min(4)]; + push( + &mut v, + &model, + &format!("{folder}/profession_level/{level}"), + white, + false, + ); + } + } + } + _ => {} + } + v +} +impl super::MobType { + /// The main model layer key without the namespace. + pub fn model_key(&self) -> String { + super::species::def(self.species).model.to_owned() + } +} +/// The mob's root transform (LivingEntityRenderer.submit + setupRotations). +pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { + let a = f64::from(alpha); + let p = glam::DVec3::new( + m.previous.x + (m.position.x - m.previous.x) * a, + m.previous.y + (m.position.y - m.previous.y) * a, + m.previous.z + (m.position.z - m.previous.z) * a, + ) - camera; + let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha; + let mut base = glam::Mat4::from_translation(p.as_vec3()) + * glam::Mat4::from_rotation_y((180.0 - body).to_radians()); + if m.death_time > 0 { + let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) + .sqrt() + .min(1.0); + base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } + base *= species_rotations(m, alpha); + base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + base *= species_scale(m, alpha); + base * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)) +} +fn flip_degrees(m: &Mob) -> f32 { + match m.species() { + Species::Spider | Species::CaveSpider | Species::Silverfish | Species::Endermite => 180.0, + _ => 90.0, + } +} +fn species_rotations(_m: &Mob, _alpha: f32) -> glam::Mat4 { + let _ = PI; + glam::Mat4::IDENTITY +} +fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { + match m.species() { + Species::Creeper => { + // CreeperRenderer.scale: swelling with a wobble. + let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha) + / 28.0) + .clamp(0.0, 1.0); + let wobble = 1.0 + (s * 100.0).sin() * s * 0.01; + let s4 = s * s * s * s; + let xz = (1.0 + s4 * 0.4) * wobble; + let y = (1.0 + s4 * 0.1) / wobble; + glam::Mat4::from_scale(glam::Vec3::new(xz, y, xz)) + } + _ => glam::Mat4::IDENTITY, + } +} +/// Draw a part tree with a pose map, texture rect, colour and light. +#[allow(clippy::too_many_arguments)] +pub fn draw( + part: &Part, + base: glam::Mat4, + poses: &Poses, + uv: [f32; 4], + color: u32, + light: u32, + overlay: u32, + out: &mut Vec, +) { + let p = poses.pose(part); + let m = base + * glam::Mat4::from_translation(glam::Vec3::new(p[0], p[1], p[2]) / 16.0) + * glam::Mat4::from_quat(glam::Quat::from_euler( + glam::EulerRot::ZYX, + p[5], + p[4], + p[3], + )) + * glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8])); + if p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 { + return; + } + for poly in &part.polygons { + for v in poly.vertices { + let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); + out.push(Vertex { + pos: pos.to_array(), + uv: [ + uv[0] + (uv[2] - uv[0]) * v[3], + uv[1] + (uv[3] - uv[1]) * v[4], + ], + layer: overlay, + color, + light, + }); + } + } + for c in &part.children { + draw(c, m, poses, uv, color, light, overlay, out); + } +} +/// Render a mob with its variant model, texture and layers. +pub fn render( + m: &Mob, + alpha: f32, + camera: glam::DVec3, + atlas: Atlas, + light: u32, + data: &MobData, + out: &mut Vec, +) { + let base = base_transform(m, alpha, camera); + let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let s = anim::state(m, alpha); + let (model_key, texture) = body(m); + let model = m + .kind + .layer(&model_key) + .cloned() + .unwrap_or_else(|| m.kind.model.clone()); + if let Some(uv) = atlas(&texture) { + let mut poses = Poses::new(&model); + anim::setup(m, &s, &mut poses, &data.animations); + draw(&model, base, &poses, uv, 0xFFFF_FFFF, light, overlay, out); + } + for layer in layers(m) { + let Some(part) = m.kind.layer(&layer.model).cloned() else { + continue; + }; + let Some(uv) = atlas(&layer.texture) else { + continue; + }; + let mut poses = Poses::new(&part); + anim::setup(m, &s, &mut poses, &data.animations); + let light = if layer.full_bright { + 240 | 240 << 8 + } else { + light + }; + draw(&part, base, &poses, uv, layer.color, light, overlay, out); + } +} +/// Render with a fixed texture rect (the earlier API). +pub fn render_single( + m: &Mob, + alpha: f32, + camera: glam::DVec3, + uv: [f32; 4], + light: u32, + out: &mut Vec, +) { + let base = base_transform(m, alpha, camera); + let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let s = anim::state(m, alpha); + let model = m.kind.model.clone(); + let mut poses = Poses::new(&model); + anim::setup(m, &s, &mut poses, &std::collections::HashMap::new()); + draw(&model, base, &poses, uv, 0xFFFF_FFFF, light, overlay, out); +} diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs new file mode 100644 index 000000000..f6f3be965 --- /dev/null +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -0,0 +1,227 @@ +//! Natural spawning rules: `SpawnPlacements` placement types and each +//! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`, +//! water animals, bats...), and `finalizeSpawn` (variants, colours, babies, +//! equipment). +use super::{Mob, MobWorld, Species, data, farm::Climate}; +use crate::blocks::Fluid; +use horizon_core::random::RandomSource; + +/// Biome facts finalizeSpawn and the spawn rules read. +#[derive(Clone, Copy, Debug, Default)] +pub struct BiomeFacts { + pub climate: Climate, + /// Biome temperature at the position (strays in cold biomes, snow foxes). + pub temperature: f32, + pub snowy: bool, + pub swamp: bool, + pub ocean: bool, + pub mushroom: bool, + pub desert: bool, + pub jungle: bool, +} +/// SpawnPlacementTypes for the species. +pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { + let id = format!("minecraft:{}", super::species::def(species).name); + match w.data.placement(&id) { + data::Placement::OnGround => { + let below = w.data.state(w.world.block(x, y - 1, z)); + let valid = match species { + Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0, + Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0, + _ => below.flags & data::VALID_SPAWN != 0, + }; + valid && empty(w, x, y, z) && empty(w, x, y + 1, z) + } + data::Placement::InWater => { + w.fluid(x, y, z) == Fluid::Water + && w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0 + } + data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava, + data::Placement::NoRestrictions => true, + } +} +fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { + w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0 +} +/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0). +pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool { + let light = w.world.light(x, y, z); + let (sky, block) = (i32::from(light >> 4), i32::from(light & 15)); + if sky > random.next_int_bound(32).unwrap_or(0) { + return false; + } + if block > 0 { + return false; + } + let darken = if w.thundering { 10 } else { w.sky_darken() }; + (sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0) +} +/// The species' checkSpawnRules for natural spawns. +pub fn spawn_rules_ok( + species: Species, + w: &MobWorld, + random: &mut impl RandomSource, + x: i32, + y: i32, + z: i32, +) -> bool { + use Species as S; + let below = w.block_name(x, y - 1, z).to_owned(); + let light = w.world.light(x, y, z); + let raw = i32::from(light >> 4).max(i32::from(light & 15)); + match species { + // Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright. + S::Pig + | S::Cow + | S::Sheep + | S::Chicken + | S::Horse + | S::Donkey + | S::Llama + | S::Wolf + | S::Cat + | S::Fox + | S::Rabbit + | S::Goat + | S::Panda + | S::Armadillo + | S::Mooshroom + | S::Turtle + | S::Frog + | S::Bee => { + let tag = match species { + S::Mooshroom => "minecraft:mooshrooms_spawnable_on", + S::Wolf => "minecraft:wolves_spawnable_on", + S::Fox => "minecraft:foxes_spawnable_on", + S::Rabbit => "minecraft:rabbits_spawnable_on", + S::Goat => "minecraft:goats_spawnable_on", + S::Armadillo => "minecraft:armadillo_spawnable_on", + S::Turtle => "minecraft:turtles_spawnable_on", + S::Frog => "minecraft:frogs_spawnable_on", + _ => "minecraft:animals_spawnable_on", + }; + w.has_tag(tag, &below) && raw > 8 + } + S::PolarBear => { + w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below) + || w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8 + } + S::Ocelot | S::Parrot => { + (w.has_tag("minecraft:parrots_spawnable_on", &below) + || below.contains("leaves") + || below == "minecraft:grass_block") + && raw > 8 + } + S::Bat => { + // Bat.checkBatSpawnRules: below sea level, dark. + if y >= 63 { + return false; + } + let block = i32::from(light & 15).max(i32::from(light >> 4)); + block <= random.next_int_bound(4).unwrap_or(0) + } + S::Slime => { + // Swamp at night by moon brightness, or slime chunks below y 40. + y < 40 && random.next_int_bound(10).unwrap_or(1) == 0 + } + S::Squid + | S::GlowSquid + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Dolphin => { + // WaterAnimal.checkSurfaceWaterAnimalSpawnRules: between sea level - 13 and sea level. + let in_band = (50..=62).contains(&y); + in_band && w.fluid(x, y - 1, z) == Fluid::Water && w.fluid(x, y + 1, z) == Fluid::Water + || matches!(species, S::GlowSquid) && y < 30 + } + S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay", + S::Strider => w.fluid(x, y, z) == Fluid::Lava, + S::Ghast + | S::MagmaCube + | S::ZombifiedPiglin + | S::Piglin + | S::Hoglin + | S::Blaze + | S::WitherSkeleton + | S::Enderman + if w.nether => + { + !w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast + } + S::Husk | S::Stray => dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z), + S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z), + _ => { + // Monster.checkMonsterSpawnRules + !w.nether && dark_enough(w, random, x, y, z) || w.nether + } + } +} +/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. +pub fn finalize(m: &mut Mob, biome: &BiomeFacts) { + use Species as S; + let climate_index = match biome.climate { + Climate::Temperate => 0, + Climate::Warm => 1, + Climate::Cold => 2, + }; + match m.species() { + S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, + S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), + S::Mooshroom => m.extra.variant = 0, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => { + // Zombie.finalizeSpawn: 5% babies (normal difficulty). + if m.random.next_float() < 0.05 { + m.extra.age = i32::MIN / 2; + } + if m.species() != S::Drowned && m.random.next_float() < 0.01 { + let r = m.random.next_int_bound(3).unwrap_or(0); + m.extra.main_hand = Some( + if r == 0 { + "minecraft:iron_sword" + } else { + "minecraft:iron_shovel" + } + .into(), + ); + } + if m.species() == S::Drowned && m.random.next_float() < 0.0625 { + m.extra.main_hand = Some( + if m.random.next_int_bound(16).unwrap_or(1) < 10 { + "minecraft:trident" + } else { + "minecraft:fishing_rod" + } + .into(), + ); + } + if m.species() == S::ZombieVillager { + m.extra.variant = villager_type(biome); + m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8; + } + } + S::Villager => { + m.extra.variant = villager_type(biome); + } + _ => {} + } +} +/// VillagerType.byBiome +pub fn villager_type(b: &BiomeFacts) -> u8 { + if b.desert { + 1 + } else if b.jungle { + 2 + } else if b.snowy { + 4 + } else if b.swamp { + 5 + } else if b.climate == Climate::Warm { + 3 + } else if b.climate == Climate::Cold && b.temperature < 0.4 { + 6 + } else { + 0 + } +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs new file mode 100644 index 000000000..a8b568e3b --- /dev/null +++ b/crates/horizon-client/src/mobs/species.rs @@ -0,0 +1,1253 @@ +//! Supported vanilla mob types: model layers, default textures, animation +//! family, sounds, baby dimensions and the per-class constants +//! (`getMaxHeadXRot`, `getAmbientSoundInterval`, `getWaterSlowDown`...). +use super::{Brain, Flags, anim::Anim}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Species { + Pig, + Cow, + Mooshroom, + Sheep, + Chicken, + Rabbit, + Horse, + Donkey, + Mule, + Llama, + TraderLlama, + Goat, + Panda, + PolarBear, + Fox, + Wolf, + Cat, + Ocelot, + Parrot, + Bee, + Turtle, + Armadillo, + Frog, + Axolotl, + Squid, + GlowSquid, + Cod, + Salmon, + TropicalFish, + Pufferfish, + Dolphin, + Bat, + Villager, + WanderingTrader, + IronGolem, + SnowGolem, + Zombie, + Husk, + Drowned, + ZombieVillager, + Skeleton, + Stray, + Bogged, + WitherSkeleton, + Creeper, + Spider, + CaveSpider, + Enderman, + Endermite, + Silverfish, + Slime, + MagmaCube, + Witch, + Phantom, + Pillager, + Vindicator, + Piglin, + PiglinBrute, + ZombifiedPiglin, + Hoglin, + Zoglin, + Ghast, + Blaze, + Strider, +} +/// Baby bounding boxes (each class's BABY_DIMENSIONS). +#[derive(Clone, Copy, Debug)] +pub enum Baby { + /// Not an ageable mob. + None, + /// EntityDimensions.scalable(w, h).withEyeHeight(e) + Abs(f64, f64, f64), + /// The adult dimensions scaled, with an optional explicit eye height. + Scale(f64, Option), +} +pub struct Def { + pub species: Species, + pub name: &'static str, + pub model: &'static str, + pub texture: &'static str, + pub anim: Anim, + pub sounds: [&'static str; 3], + pub step_sound: Option<&'static str>, + pub baby: Baby, +} +macro_rules! def { + ($s:ident, $name:literal, $model:literal, $tex:literal, $anim:expr, [$a:literal, $h:literal, $d:literal], $step:expr, $baby:expr) => { + Def { + species: Species::$s, + name: $name, + model: $model, + texture: $tex, + anim: $anim, + sounds: [$a, $h, $d], + step_sound: $step, + baby: $baby, + } + }; +} +use Anim as A; +pub const ALL: &[Def] = &[ + def!( + Pig, + "pig", + "pig#main", + "entity/pig/pig_temperate", + A::Quadruped, + ["entity.pig.ambient", "entity.pig.hurt", "entity.pig.death"], + Some("entity.pig.step"), + Baby::Abs(0.45, 0.45, 0.40625) + ), + def!( + Cow, + "cow", + "cow#main", + "entity/cow/cow_temperate", + A::Quadruped, + ["entity.cow.ambient", "entity.cow.hurt", "entity.cow.death"], + Some("entity.cow.step"), + Baby::Abs(0.45, 0.7, 0.69) + ), + def!( + Mooshroom, + "mooshroom", + "mooshroom#main", + "entity/cow/mooshroom_red", + A::Quadruped, + ["entity.cow.ambient", "entity.cow.hurt", "entity.cow.death"], + Some("entity.cow.step"), + Baby::Abs(0.45, 0.7, 0.69) + ), + def!( + Sheep, + "sheep", + "sheep#main", + "entity/sheep/sheep", + A::Sheep, + [ + "entity.sheep.ambient", + "entity.sheep.hurt", + "entity.sheep.death" + ], + Some("entity.sheep.step"), + Baby::Abs(0.45, 0.65, 0.65625) + ), + def!( + Chicken, + "chicken", + "chicken#main", + "entity/chicken/chicken_temperate", + A::Chicken, + [ + "entity.chicken.ambient", + "entity.chicken.hurt", + "entity.chicken.death" + ], + Some("entity.chicken.step"), + Baby::Abs(0.3, 0.4, 0.28125) + ), + def!( + Rabbit, + "rabbit", + "rabbit#main", + "entity/rabbit/rabbit_brown", + A::Rabbit, + [ + "entity.rabbit.ambient", + "entity.rabbit.hurt", + "entity.rabbit.death" + ], + None, + Baby::Abs(0.24, 0.4, 0.39) + ), + def!( + Horse, + "horse", + "horse#main", + "entity/horse/horse_brown", + A::Horse, + [ + "entity.horse.ambient", + "entity.horse.hurt", + "entity.horse.death" + ], + Some("entity.horse.step"), + Baby::Scale(0.7, None) + ), + def!( + Donkey, + "donkey", + "donkey#main", + "entity/horse/donkey", + A::Horse, + [ + "entity.donkey.ambient", + "entity.donkey.hurt", + "entity.donkey.death" + ], + Some("entity.horse.step"), + Baby::Scale(0.7, None) + ), + def!( + Mule, + "mule", + "mule#main", + "entity/horse/mule", + A::Horse, + [ + "entity.mule.ambient", + "entity.mule.hurt", + "entity.mule.death" + ], + Some("entity.horse.step"), + Baby::Scale(0.7, None) + ), + def!( + Llama, + "llama", + "llama#main", + "entity/llama/llama_creamy", + A::Llama, + [ + "entity.llama.ambient", + "entity.llama.hurt", + "entity.llama.death" + ], + Some("entity.llama.step"), + Baby::Scale(0.5, None) + ), + def!( + TraderLlama, + "trader_llama", + "trader_llama#main", + "entity/llama/llama_creamy", + A::Llama, + [ + "entity.llama.ambient", + "entity.llama.hurt", + "entity.llama.death" + ], + Some("entity.llama.step"), + Baby::Scale(0.5, None) + ), + def!( + Goat, + "goat", + "goat#main", + "entity/goat/goat", + A::Goat, + [ + "entity.goat.ambient", + "entity.goat.hurt", + "entity.goat.death" + ], + Some("entity.goat.step"), + Baby::Abs(0.45, 0.65, 0.59375) + ), + def!( + Panda, + "panda", + "panda#main", + "entity/panda/panda", + A::Panda, + [ + "entity.panda.ambient", + "entity.panda.hurt", + "entity.panda.death" + ], + Some("entity.panda.step"), + Baby::Scale(0.5, Some(0.28125)) + ), + def!( + PolarBear, + "polar_bear", + "polar_bear#main", + "entity/bear/polarbear", + A::PolarBear, + [ + "entity.polar_bear.ambient", + "entity.polar_bear.hurt", + "entity.polar_bear.death" + ], + Some("entity.polar_bear.step"), + Baby::Abs(0.7, 0.7, 0.34375) + ), + def!( + Fox, + "fox", + "fox#main", + "entity/fox/fox", + A::Fox, + ["entity.fox.ambient", "entity.fox.hurt", "entity.fox.death"], + None, + Baby::Scale(0.6, Some(0.34375)) + ), + def!( + Wolf, + "wolf", + "wolf#main", + "entity/wolf/wolf", + A::Wolf, + [ + "entity.wolf.ambient", + "entity.wolf.hurt", + "entity.wolf.death" + ], + Some("entity.wolf.step"), + Baby::Abs(0.3, 0.425, 0.34375) + ), + def!( + Cat, + "cat", + "cat#main", + "entity/cat/cat_tabby", + A::Feline, + ["entity.cat.ambient", "entity.cat.hurt", "entity.cat.death"], + None, + Baby::Abs(0.3, 0.35, 0.34375) + ), + def!( + Ocelot, + "ocelot", + "ocelot#main", + "entity/cat/ocelot", + A::Feline, + [ + "entity.ocelot.ambient", + "entity.ocelot.hurt", + "entity.ocelot.death" + ], + None, + Baby::Abs(0.3, 0.35, 0.34375) + ), + def!( + Parrot, + "parrot", + "parrot#main", + "entity/parrot/parrot_red_blue", + A::Parrot, + [ + "entity.parrot.ambient", + "entity.parrot.hurt", + "entity.parrot.death" + ], + Some("entity.parrot.step"), + Baby::None + ), + def!( + Bee, + "bee", + "bee#main", + "entity/bee/bee", + A::Bee, + ["", "entity.bee.hurt", "entity.bee.death"], + None, + Baby::Scale(0.5, None) + ), + def!( + Turtle, + "turtle", + "turtle#main", + "entity/turtle/turtle", + A::Turtle, + [ + "entity.turtle.ambient_land", + "entity.turtle.hurt", + "entity.turtle.death" + ], + Some("entity.turtle.shamble"), + Baby::Scale(0.3, None) + ), + def!( + Armadillo, + "armadillo", + "armadillo#main", + "entity/armadillo/armadillo", + A::Armadillo, + [ + "entity.armadillo.ambient", + "entity.armadillo.hurt", + "entity.armadillo.death" + ], + Some("entity.armadillo.step"), + Baby::Scale(0.6, Some(0.21875)) + ), + def!( + Frog, + "frog", + "frog#main", + "entity/frog/frog_temperate", + A::Frog, + [ + "entity.frog.ambient", + "entity.frog.hurt", + "entity.frog.death" + ], + Some("entity.frog.step"), + Baby::None + ), + def!( + Axolotl, + "axolotl", + "axolotl#main", + "entity/axolotl/axolotl_lucy", + A::Axolotl, + [ + "entity.axolotl.idle_water", + "entity.axolotl.hurt", + "entity.axolotl.death" + ], + None, + Baby::Abs(0.375, 0.21, 0.09375) + ), + def!( + Squid, + "squid", + "squid#main", + "entity/squid/squid", + A::Squid, + [ + "entity.squid.ambient", + "entity.squid.hurt", + "entity.squid.death" + ], + None, + Baby::Abs(0.5, 0.5, 0.37) + ), + def!( + GlowSquid, + "glow_squid", + "glow_squid#main", + "entity/squid/glow_squid", + A::Squid, + [ + "entity.glow_squid.ambient", + "entity.glow_squid.hurt", + "entity.glow_squid.death" + ], + None, + Baby::Abs(0.5, 0.5, 0.37) + ), + def!( + Cod, + "cod", + "cod#main", + "entity/fish/cod", + A::Fish, + ["entity.cod.ambient", "entity.cod.hurt", "entity.cod.death"], + None, + Baby::None + ), + def!( + Salmon, + "salmon", + "salmon#main", + "entity/fish/salmon", + A::Fish, + [ + "entity.salmon.ambient", + "entity.salmon.hurt", + "entity.salmon.death" + ], + None, + Baby::None + ), + def!( + TropicalFish, + "tropical_fish", + "tropical_fish_small#main", + "entity/fish/tropical_a", + A::Fish, + [ + "entity.tropical_fish.ambient", + "entity.tropical_fish.hurt", + "entity.tropical_fish.death" + ], + None, + Baby::None + ), + def!( + Pufferfish, + "pufferfish", + "pufferfish_big#main", + "entity/fish/pufferfish", + A::Pufferfish, + ["", "entity.puffer_fish.hurt", "entity.puffer_fish.death"], + None, + Baby::None + ), + def!( + Dolphin, + "dolphin", + "dolphin#main", + "entity/dolphin/dolphin", + A::Dolphin, + [ + "entity.dolphin.ambient_water", + "entity.dolphin.hurt", + "entity.dolphin.death" + ], + None, + Baby::Scale(0.65, Some(0.093_75)) + ), + def!( + Bat, + "bat", + "bat#main", + "entity/bat/bat", + A::Bat, + ["entity.bat.ambient", "entity.bat.hurt", "entity.bat.death"], + None, + Baby::None + ), + def!( + Villager, + "villager", + "villager#main", + "entity/villager/villager", + A::Villager, + [ + "entity.villager.ambient", + "entity.villager.hurt", + "entity.villager.death" + ], + None, + Baby::Abs(0.49, 0.98, 0.63) + ), + def!( + WanderingTrader, + "wandering_trader", + "wandering_trader#main", + "entity/wandering_trader/wandering_trader", + A::Villager, + [ + "entity.wandering_trader.ambient", + "entity.wandering_trader.hurt", + "entity.wandering_trader.death" + ], + None, + Baby::None + ), + def!( + IronGolem, + "iron_golem", + "iron_golem#main", + "entity/iron_golem/iron_golem", + A::IronGolem, + ["", "entity.iron_golem.hurt", "entity.iron_golem.death"], + Some("entity.iron_golem.step"), + Baby::None + ), + def!( + SnowGolem, + "snow_golem", + "snow_golem#main", + "entity/snow_golem/snow_golem", + A::SnowGolem, + [ + "entity.snow_golem.ambient", + "entity.snow_golem.hurt", + "entity.snow_golem.death" + ], + None, + Baby::None + ), + def!( + Zombie, + "zombie", + "zombie#main", + "entity/zombie/zombie", + A::Zombie, + [ + "entity.zombie.ambient", + "entity.zombie.hurt", + "entity.zombie.death" + ], + Some("entity.zombie.step"), + Baby::Abs(0.49, 0.98, 0.775) + ), + def!( + Husk, + "husk", + "husk#main", + "entity/zombie/husk", + A::Zombie, + [ + "entity.husk.ambient", + "entity.husk.hurt", + "entity.husk.death" + ], + Some("entity.husk.step"), + Baby::Abs(0.49, 0.98, 0.825) + ), + def!( + Drowned, + "drowned", + "drowned#main", + "entity/zombie/drowned", + A::Drowned, + [ + "entity.drowned.ambient", + "entity.drowned.hurt", + "entity.drowned.death" + ], + Some("entity.drowned.step"), + Baby::Abs(0.49, 0.98, 0.775) + ), + def!( + ZombieVillager, + "zombie_villager", + "zombie_villager#main", + "entity/zombie_villager/zombie_villager", + A::ZombieVillager, + [ + "entity.zombie_villager.ambient", + "entity.zombie_villager.hurt", + "entity.zombie_villager.death" + ], + Some("entity.zombie_villager.step"), + Baby::Abs(0.49, 0.98, 0.67) + ), + def!( + Skeleton, + "skeleton", + "skeleton#main", + "entity/skeleton/skeleton", + A::Skeleton, + [ + "entity.skeleton.ambient", + "entity.skeleton.hurt", + "entity.skeleton.death" + ], + Some("entity.skeleton.step"), + Baby::None + ), + def!( + Stray, + "stray", + "stray#main", + "entity/skeleton/stray", + A::Skeleton, + [ + "entity.stray.ambient", + "entity.stray.hurt", + "entity.stray.death" + ], + Some("entity.stray.step"), + Baby::None + ), + def!( + Bogged, + "bogged", + "bogged#main", + "entity/skeleton/bogged", + A::Skeleton, + [ + "entity.bogged.ambient", + "entity.bogged.hurt", + "entity.bogged.death" + ], + Some("entity.bogged.step"), + Baby::None + ), + def!( + WitherSkeleton, + "wither_skeleton", + "wither_skeleton#main", + "entity/skeleton/wither_skeleton", + A::Skeleton, + [ + "entity.wither_skeleton.ambient", + "entity.wither_skeleton.hurt", + "entity.wither_skeleton.death" + ], + Some("entity.wither_skeleton.step"), + Baby::None + ), + def!( + Creeper, + "creeper", + "creeper#main", + "entity/creeper/creeper", + A::Creeper, + ["", "entity.creeper.hurt", "entity.creeper.death"], + None, + Baby::None + ), + def!( + Spider, + "spider", + "spider#main", + "entity/spider/spider", + A::Spider, + [ + "entity.spider.ambient", + "entity.spider.hurt", + "entity.spider.death" + ], + Some("entity.spider.step"), + Baby::None + ), + def!( + CaveSpider, + "cave_spider", + "cave_spider#main", + "entity/spider/cave_spider", + A::Spider, + [ + "entity.spider.ambient", + "entity.spider.hurt", + "entity.spider.death" + ], + Some("entity.spider.step"), + Baby::None + ), + def!( + Enderman, + "enderman", + "enderman#main", + "entity/enderman/enderman", + A::Enderman, + [ + "entity.enderman.ambient", + "entity.enderman.hurt", + "entity.enderman.death" + ], + None, + Baby::None + ), + def!( + Endermite, + "endermite", + "endermite#main", + "entity/endermite", + A::Silverfish, + [ + "entity.endermite.ambient", + "entity.endermite.hurt", + "entity.endermite.death" + ], + Some("entity.endermite.step"), + Baby::None + ), + def!( + Silverfish, + "silverfish", + "silverfish#main", + "entity/silverfish", + A::Silverfish, + [ + "entity.silverfish.ambient", + "entity.silverfish.hurt", + "entity.silverfish.death" + ], + Some("entity.silverfish.step"), + Baby::None + ), + def!( + Slime, + "slime", + "slime#main", + "entity/slime/slime", + A::Slime, + ["", "entity.slime.hurt", "entity.slime.death"], + None, + Baby::None + ), + def!( + MagmaCube, + "magma_cube", + "magma_cube#main", + "entity/slime/magmacube", + A::MagmaCube, + ["", "entity.magma_cube.hurt", "entity.magma_cube.death"], + None, + Baby::None + ), + def!( + Witch, + "witch", + "witch#main", + "entity/witch/witch", + A::Witch, + [ + "entity.witch.ambient", + "entity.witch.hurt", + "entity.witch.death" + ], + None, + Baby::None + ), + def!( + Phantom, + "phantom", + "phantom#main", + "entity/phantom/phantom", + A::Phantom, + [ + "entity.phantom.ambient", + "entity.phantom.hurt", + "entity.phantom.death" + ], + None, + Baby::None + ), + def!( + Pillager, + "pillager", + "pillager#main", + "entity/illager/pillager", + A::Illager, + [ + "entity.pillager.ambient", + "entity.pillager.hurt", + "entity.pillager.death" + ], + None, + Baby::None + ), + def!( + Vindicator, + "vindicator", + "vindicator#main", + "entity/illager/vindicator", + A::Illager, + [ + "entity.vindicator.ambient", + "entity.vindicator.hurt", + "entity.vindicator.death" + ], + None, + Baby::None + ), + def!( + Piglin, + "piglin", + "piglin#main", + "entity/piglin/piglin", + A::Piglin, + [ + "entity.piglin.ambient", + "entity.piglin.hurt", + "entity.piglin.death" + ], + Some("entity.piglin.step"), + Baby::Abs(0.49, 0.98, 0.78) + ), + def!( + PiglinBrute, + "piglin_brute", + "piglin_brute#main", + "entity/piglin/piglin_brute", + A::Piglin, + [ + "entity.piglin_brute.ambient", + "entity.piglin_brute.hurt", + "entity.piglin_brute.death" + ], + Some("entity.piglin_brute.step"), + Baby::None + ), + def!( + ZombifiedPiglin, + "zombified_piglin", + "zombified_piglin#main", + "entity/piglin/zombified_piglin", + A::ZombifiedPiglin, + [ + "entity.zombified_piglin.ambient", + "entity.zombified_piglin.hurt", + "entity.zombified_piglin.death" + ], + None, + Baby::Abs(0.49, 0.98, 0.78) + ), + def!( + Hoglin, + "hoglin", + "hoglin#main", + "entity/hoglin/hoglin", + A::Hoglin, + [ + "entity.hoglin.ambient", + "entity.hoglin.hurt", + "entity.hoglin.death" + ], + Some("entity.hoglin.step"), + Baby::Abs(0.75, 0.85, 0.625) + ), + def!( + Zoglin, + "zoglin", + "zoglin#main", + "entity/hoglin/zoglin", + A::Hoglin, + [ + "entity.zoglin.ambient", + "entity.zoglin.hurt", + "entity.zoglin.death" + ], + Some("entity.zoglin.step"), + Baby::Abs(0.75, 0.85, 0.625) + ), + def!( + Ghast, + "ghast", + "ghast#main", + "entity/ghast/ghast", + A::Ghast, + [ + "entity.ghast.ambient", + "entity.ghast.hurt", + "entity.ghast.death" + ], + None, + Baby::None + ), + def!( + Blaze, + "blaze", + "blaze#main", + "entity/blaze", + A::Blaze, + [ + "entity.blaze.ambient", + "entity.blaze.hurt", + "entity.blaze.death" + ], + None, + Baby::None + ), + def!( + Strider, + "strider", + "strider#main", + "entity/strider/strider", + A::Strider, + [ + "entity.strider.ambient", + "entity.strider.hurt", + "entity.strider.death" + ], + Some("entity.strider.step"), + Baby::Abs(0.45, 0.85, 0.4375) + ), +]; +pub fn def(s: Species) -> &'static Def { + ALL.iter().find(|d| d.species == s).unwrap_or(&ALL[0]) +} +impl Def { + /// Model layer families to load for this entity (adult, baby, variants). + pub fn layer_prefixes(&self) -> Vec<&'static str> { + let base = self.model.split('#').next().unwrap_or(self.name); + let mut v = vec![base]; + let extra: &[&str] = match self.species { + Species::Pig => &["pig_baby", "cold_pig"], + Species::Cow => &[ + "cow_baby", + "cold_cow", + "cold_cow_baby", + "warm_cow", + "warm_cow_baby", + ], + Species::Mooshroom => &["mooshroom_baby"], + Species::Sheep => &["sheep_baby"], + Species::Chicken => &["chicken_baby", "cold_chicken"], + Species::Rabbit => &["rabbit_baby"], + Species::Horse => &["horse_baby"], + Species::Donkey => &["donkey_baby"], + Species::Mule => &["mule_baby"], + Species::Llama => &["llama_baby"], + Species::TraderLlama => &["trader_llama_baby", "llama"], + Species::Goat => &["goat_baby"], + Species::Panda => &["panda_baby"], + Species::PolarBear => &["polar_bear_baby"], + Species::Fox => &["fox_baby"], + Species::Wolf => &["wolf_baby"], + Species::Cat => &["cat_baby"], + Species::Ocelot => &["ocelot_baby"], + Species::Bee => &["bee_baby"], + Species::Turtle => &["turtle_baby"], + Species::Armadillo => &["armadillo_baby"], + Species::Axolotl => &["axolotl_baby"], + Species::Squid => &["squid_baby"], + Species::GlowSquid => &["glow_squid_baby"], + Species::Salmon => &["salmon_small", "salmon_large"], + Species::TropicalFish => &["tropical_fish_large"], + Species::Pufferfish => &["pufferfish_small", "pufferfish_medium"], + Species::Dolphin => &["dolphin_baby"], + Species::Villager => &["villager_baby", "villager_no_hat", "villager_baby_no_hat"], + Species::Zombie => &["zombie_baby"], + Species::Husk => &["husk_baby"], + Species::Drowned => &["drowned_baby"], + Species::ZombieVillager => &[ + "zombie_villager_baby", + "zombie_villager_no_hat", + "zombie_villager_baby_no_hat", + ], + Species::Piglin => &["piglin_baby"], + Species::ZombifiedPiglin => &["zombified_piglin_baby"], + Species::Hoglin => &["hoglin_baby"], + Species::Zoglin => &["zoglin_baby"], + Species::Strider => &["strider_baby"], + _ => &[], + }; + v.extend_from_slice(extra); + v + } + pub fn flags(&self, fire_immune: bool) -> Flags { + use Species as S; + let s = self.species; + let undead = matches!( + s, + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::Skeleton + | S::Stray + | S::Bogged + | S::WitherSkeleton + | S::Phantom + | S::ZombifiedPiglin + | S::Zoglin + ); + let aquatic = matches!( + s, + S::Squid + | S::GlowSquid + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Dolphin + ); + Flags { + aquatic_swimmer: aquatic, + fall_immune: matches!( + s, + S::Chicken + | S::Bat + | S::Parrot + | S::Bee + | S::Ghast + | S::Blaze + | S::Phantom + | S::IronGolem + | S::Cat + | S::Ocelot + | S::Frog + | S::Slime + | S::MagmaCube + ), + flying: matches!(s, S::Ghast | S::Phantom), + climber: matches!(s, S::Spider | S::CaveSpider), + lava_walker: s == S::Strider, + omnidirectional: matches!(s, S::Bat | S::Bee | S::Parrot), + fire_immune: fire_immune + || matches!( + s, + S::Ghast + | S::Blaze + | S::MagmaCube + | S::Strider + | S::WitherSkeleton + | S::ZombifiedPiglin + | S::Zoglin + | S::Hoglin + ), + burns_in_day: matches!( + s, + S::Zombie + | S::Drowned + | S::ZombieVillager + | S::Skeleton + | S::Stray + | S::Bogged + | S::Phantom + ), + undead, + breathes_water: aquatic + || undead + || matches!( + s, + S::Axolotl + | S::Frog + | S::Turtle + | S::IronGolem + | S::SnowGolem + | S::Ghast + | S::Blaze + ), + needs_water: aquatic, + water_sensitive: matches!(s, S::Enderman | S::Blaze | S::SnowGolem), + animal: !matches!(s, S::Bat) + && !self.hostile_class() + && !aquatic + && !matches!( + s, + S::Villager | S::WanderingTrader | S::IronGolem | S::SnowGolem + ), + } + } + fn hostile_class(&self) -> bool { + use Species as S; + matches!( + self.species, + S::Zombie + | S::Husk + | S::Drowned + | S::ZombieVillager + | S::Skeleton + | S::Stray + | S::Bogged + | S::WitherSkeleton + | S::Creeper + | S::Spider + | S::CaveSpider + | S::Enderman + | S::Endermite + | S::Silverfish + | S::Slime + | S::MagmaCube + | S::Witch + | S::Phantom + | S::Pillager + | S::Vindicator + | S::Piglin + | S::PiglinBrute + | S::ZombifiedPiglin + | S::Hoglin + | S::Zoglin + | S::Ghast + | S::Blaze + ) + } + /// The item tag Animal.isFood tests. + pub fn food_tag(&self) -> Option<&'static str> { + use Species as S; + Some(match self.species { + S::Pig => "pig_food", + S::Cow | S::Mooshroom => "cow_food", + S::Sheep => "sheep_food", + S::Chicken => "chicken_food", + S::Rabbit => "rabbit_food", + S::Horse | S::Donkey | S::Mule => "horse_food", + S::Llama | S::TraderLlama => "llama_food", + S::Goat => "goat_food", + S::Panda => "panda_food", + S::Fox => "fox_food", + S::Wolf => "wolf_food", + S::Cat => "cat_food", + S::Ocelot => "ocelot_food", + S::Parrot => "parrot_food", + S::Bee => "bee_food", + S::Turtle => "turtle_food", + S::Armadillo => "armadillo_food", + S::Frog => "frog_food", + S::Axolotl => "axolotl_food", + S::Hoglin => "hoglin_food", + S::Strider => "strider_food", + S::Piglin => "piglin_food", + _ => return None, + }) + } + pub fn tempt_tag(&self) -> Option<&'static str> { + Some(match self.species { + Species::Horse | Species::Donkey | Species::Mule => "horse_tempt_items", + Species::Llama | Species::TraderLlama => "llama_tempt_items", + Species::Strider => "strider_tempt_items", + _ => return None, + }) + } + pub fn water_slowdown(&self) -> f32 { + match self.species { + Species::PolarBear => 0.98, + _ => 0.8, + } + } + pub fn air_speed(&self) -> f32 { + match self.species { + Species::Phantom => 0.2, + _ => 0.02, + } + } + pub fn baby_scale(&self) -> f64 { + match self.baby { + Baby::Scale(s, _) => s, + _ => 0.5, + } + } + pub fn head_rot_speed(&self) -> f32 { + match self.species { + Species::Frog => 35.0, + _ => 10.0, + } + } + pub fn max_head_x_rot(&self) -> f32 { + match self.species { + Species::Dolphin | Species::Axolotl => 1.0, + Species::Slime | Species::MagmaCube => 0.0, + _ => 40.0, + } + } + pub fn max_head_y_rot(&self) -> f32 { + match self.species { + Species::Dolphin | Species::Axolotl => 1.0, + Species::Frog => 5.0, + Species::Goat => 15.0, + Species::Armadillo => 32.0, + _ => 75.0, + } + } + pub fn ambient_interval(&self) -> i32 { + use Species as S; + match self.species { + S::Turtle => 200, + S::Horse | S::Donkey | S::Mule | S::Llama | S::TraderLlama => 400, + S::Ocelot => 900, + S::Squid + | S::GlowSquid + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Dolphin + | S::Axolotl + | S::IronGolem + | S::SnowGolem => 120, + _ if self.flags(false).animal => 120, + _ => 80, + } + } + pub fn brain(&self) -> Brain { + match self.species { + Species::Chicken => Brain::Chicken, + Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { + Brain::Zombie + } + Species::Skeleton | Species::Stray | Species::Bogged => Brain::Skeleton, + Species::Spider | Species::CaveSpider => Brain::Spider, + Species::Creeper => Brain::Creeper, + _ => Brain::Passive, + } + } +} diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs new file mode 100644 index 000000000..3f14770cc --- /dev/null +++ b/crates/horizon-client/src/mobs/undead.rs @@ -0,0 +1,384 @@ +//! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton, +//! stray, bogged, wither skeleton): goals, bow attacks, water conversion. +use super::{ + Mob, MobEvent, Species, Who, + goals::{ + Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, + NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone, + }, +}; +use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +pub fn register(m: &mut Mob) { + use Species as S; + match m.species() { + S::Zombie | S::Husk | S::ZombieVillager => { + let g = &mut m.ai.goals; + g.add(8, LookAtPlayer::new(8.0)); + g.add(8, RandomLookAround::default()); + g.add(3, MeleeAttack::new(1.0, false).zombie()); + g.add(7, Stroll::avoiding_water(1.0)); + let t = &mut m.ai.targets; + let mut hurt = HurtByTarget::new().alert(); + hurt.alert_except = vec![S::ZombifiedPiglin]; + t.add(1, hurt); + t.add(2, NearestTarget::player(true)); + t.add( + 3, + NearestTarget::species(&[S::Villager, S::WanderingTrader], false), + ); + t.add(3, NearestTarget::species(&[S::IronGolem], true)); + t.add( + 5, + NearestTarget::new( + super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby), + true, + ) + .interval(10), + ); + } + S::Drowned => { + let g = &mut m.ai.goals; + g.add(1, DrownedGoToWater::default()); + g.add(2, MeleeAttack::new(1.0, false).zombie()); + g.add(5, Stroll::new(1.0)); + g.add(8, LookAtPlayer::new(8.0)); + g.add(8, RandomLookAround::default()); + let t = &mut m.ai.targets; + let mut hurt = HurtByTarget::new().alert(); + hurt.alert_except = vec![S::ZombifiedPiglin]; + t.add(1, hurt); + t.add( + 2, + NearestTarget::player(false).when(|m, w| drowned_can_attack(m, w)), + ); + t.add( + 3, + NearestTarget::species(&[S::Villager, S::WanderingTrader], false), + ); + t.add(3, NearestTarget::species(&[S::IronGolem], true)); + t.add(3, NearestTarget::species(&[S::Axolotl], true).interval(10)); + m.ai.nav.can_float = false; + } + S::Skeleton | S::Stray | S::Bogged | S::WitherSkeleton => { + let species = m.species(); + let g = &mut m.ai.goals; + g.add(2, RestrictSun); + g.add(3, FleeSun::new(1.0)); + g.add( + 3, + AvoidEntity::new(Avoid::Species(vec![S::Wolf]), 6.0, 1.0, 1.2), + ); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(8.0)); + g.add(6, RandomLookAround::default()); + let t = &mut m.ai.targets; + t.add(1, HurtByTarget::new()); + t.add(2, NearestTarget::player(true)); + t.add(3, NearestTarget::species(&[S::IronGolem], true)); + t.add( + 3, + NearestTarget::new( + super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby), + true, + ) + .interval(10), + ); + if species == S::WitherSkeleton { + t.add( + 3, + NearestTarget::species(&[S::Piglin, S::PiglinBrute], true), + ); + m.extra.main_hand = Some("minecraft:stone_sword".into()); + m.ai.goals.add(4, MeleeAttack::new(1.2, false)); + } else { + m.extra.main_hand = Some("minecraft:bow".into()); + let interval = if m.species() == S::Bogged { 70 } else { 40 }; + m.ai.goals.add(4, BowAttack::new(1.0, interval, 15.0)); + } + } + _ => {} + } +} +fn drowned_can_attack(m: &Mob, w: &super::MobWorld) -> bool { + // Drowned.okTarget: at night or when the target is in water. + let Some(p) = &w.player else { return false }; + let (x, y, z) = ( + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ); + !w.daylight || w.fluid(x, y, z) == crate::blocks::Fluid::Water || m.fluids.in_water +} +/// Zombie drowning conversion (Zombie.DrowningTracker) and husk -> zombie. +pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { + if matches!(m.species(), Species::Zombie | Species::Husk) && m.alive() { + if m.extra.counter2 > 0 { + m.extra.counter2 -= 1; + if m.extra.counter2 == 0 { + let (kind, sound) = if m.species() == Species::Husk { + ("minecraft:zombie", "entity.husk.converted_to_zombie") + } else { + ("minecraft:drowned", "entity.zombie.converted_to_drowned") + }; + cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0)); + cx.events.push(MobEvent::SpawnKind { + kind: kind.into(), + at: [m.position.x, m.position.y, m.position.z], + setup: super::SpawnSetup { + baby: m.is_baby(), + yaw: m.yaw, + persistent: m.persistent, + ..Default::default() + }, + }); + m.removed = true; + } + } else if m.fluids.eye_in_water { + m.extra.counter += 1; + if m.extra.counter >= 600 { + m.extra.counter2 = 300; + } + } else { + m.extra.counter = -1; + } + } + if m.species() == Species::Drowned { + // Drowned.updateSwimming / travel: swim when the target is in water. + let wants = + m.ai.target + .and_then(|t| cx.w.target_info(t)) + .is_some_and(|t| { + let (x, y, z) = ( + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ); + cx.w.fluid(x, y, z) == crate::blocks::Fluid::Water + }); + m.extra.flag = wants; + if m.fluids.in_water && wants { + m.ai.nav.kind = super::nav::NavKind::Water { breach: false }; + } else if m.ai.nav.kind != super::nav::NavKind::Ground { + m.ai.nav.kind = super::nav::NavKind::Ground; + m.ai.nav.stop(); + } + } +} +/// RangedBowAttackGoal for skeletons. +#[derive(Clone, Debug)] +pub struct BowAttack { + speed: f64, + interval_min: i32, + radius_sqr: f32, + attack_time: i32, + see_time: i32, + strafe_clockwise: bool, + strafe_back: bool, + strafe_time: i32, +} +impl BowAttack { + pub fn new(speed: f64, interval_min: i32, radius: f32) -> Self { + Self { + speed, + interval_min, + radius_sqr: radius * radius, + attack_time: -1, + see_time: 0, + strafe_clockwise: false, + strafe_back: false, + strafe_time: -1, + } + } +} +fn holding_bow(m: &Mob) -> bool { + m.extra.main_hand.as_deref() == Some("minecraft:bow") +} +impl Goal for BowAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.ai.target.is_some() && holding_bow(m) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (self.can_use(m, cx) || !m.ai.nav.is_done()) && holding_bow(m) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.aggressive = true; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.aggressive = false; + self.see_time = 0; + self.attack_time = -1; + m.extra.using_item = 0; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(who) = m.ai.target else { return }; + let Some(t) = cx.w.target_info(who) else { + return; + }; + let d = m.distance_sqr(t.position); + let sees = m.sees(cx.w, who); + if sees != (self.see_time > 0) { + self.see_time = 0; + } + if sees { + self.see_time += 1; + } else { + self.see_time -= 1; + } + if d <= f64::from(self.radius_sqr) && self.see_time >= 20 { + m.nav_stop(); + self.strafe_time += 1; + } else { + m.nav_move_to_entity( + cx.w, + [t.position.x, t.position.y, t.position.z], + 1, + self.speed, + ); + self.strafe_time = -1; + } + if self.strafe_time >= 20 { + if m.random.next_float() < 0.3 { + self.strafe_clockwise = !self.strafe_clockwise; + } + if m.random.next_float() < 0.3 { + self.strafe_back = !self.strafe_back; + } + self.strafe_time = 0; + } + let eye = [t.position.x, t.eye_y, t.position.z]; + if self.strafe_time > -1 { + if d > f64::from(self.radius_sqr * 0.75) { + self.strafe_back = false; + } else if d < f64::from(self.radius_sqr * 0.25) { + self.strafe_back = true; + } + m.ai.mov.strafe( + if self.strafe_back { -0.5 } else { 0.5 }, + if self.strafe_clockwise { 0.5 } else { -0.5 }, + ); + m.turn_to(eye, 30.0, 30.0); + } else { + m.look_at_speed(eye, 30.0, 30.0); + } + if m.extra.using_item > 0 { + if !sees && self.see_time < -60 { + m.extra.using_item = 0; + } else if sees { + let pull = m.extra.using_item; + if pull >= 20 { + m.extra.using_item = 0; + perform_ranged_attack(m, who, cx, bow_power(pull)); + self.attack_time = self.interval_min; + } + } + if m.extra.using_item > 0 { + m.extra.using_item += 1; + } + } else { + self.attack_time -= 1; + if self.attack_time <= 0 && self.see_time >= -60 { + m.extra.using_item = 1; + } + } + } +} +/// BowItem.getPowerForTime +pub fn bow_power(ticks: i32) -> f32 { + let t = ticks as f32 / 20.0; + ((t * t + t * 2.0) / 3.0).min(1.0) +} +/// AbstractSkeleton.performRangedAttack: aim 20% above the target's lower +/// third, speed 1.6, uncertainty 14 - 4 * difficulty. +pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { + let Some(t) = cx.w.target_info(who) else { + return; + }; + let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z); + let height = t.bounds.max_position().y - t.bounds.min_position().y; + let xd = t.position.x - m.position.x; + let yd = t.position.y + height / 3.0 - start.y; + let zd = t.position.z - m.position.z; + let dist = (xd * xd + zd * zd).sqrt(); + // AbstractArrow.setBaseDamageFromMob: power * 2 + triangle(difficulty * 0.11, 0.57425). + let base = f64::from(power) * 2.0 + m.random.triangle(2.0 * 0.11, 0.574_25); + let effect = match m.species() { + Species::Stray => Some(("minecraft:slowness", 600)), + Species::Bogged => Some(("minecraft:poison", 100)), + _ => None, + }; + let mut p = Projectile::new( + ProjectileKind::Arrow { + base_damage: base, + critical: false, + effect, + }, + start, + Some(Who::Mob(m.id)), + ); + p.shoot( + &mut m.random, + [xd, yd + dist * 0.2, zd], + 1.6, + (14 - 2 * 4) as f32, + ); + cx.events.push(MobEvent::Projectile(p)); + let pitch = 1.0 / (m.random.next_float() * 0.4 + 0.8); + cx.events.push(MobEvent::Sound( + "entity.skeleton.shoot", + m.center(), + 1.0, + pitch, + )); +} +/// Drowned.DrownedGoToWaterGoal (simplified to "head for water by day"). +#[derive(Clone, Debug, Default)] +pub struct DrownedGoToWater { + wanted: [f64; 3], +} +impl Goal for DrownedGoToWater { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !cx.w.daylight || m.fluids.in_water { + return false; + } + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + for _ in 0..10 { + let p = [ + bx + m.random.next_int_bound(20).unwrap_or(0) - 10, + by + 2 - m.random.next_int_bound(8).unwrap_or(0), + bz + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; + if cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water { + self.wanted = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + return true; + } + } + false + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_move_to(cx.w, self.wanted, 1.0); + } +} diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs new file mode 100644 index 000000000..7394cb879 --- /dev/null +++ b/crates/horizon-client/src/mobs/world.rs @@ -0,0 +1,145 @@ +//! What mobs read from the level: block solidity, ray clipping for line of +//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent +//! values and the positions of other entities. +use super::{MobWorld, Seen, Species, Who, data}; +use crate::{blocks::Fluid, collisions::SceneCollisions}; +use horizon_core::{ + geometry::{Aabb, Vec3, traverse_blocks}, + position::BlockPos, +}; + +/// Where a target entity is this tick. +#[derive(Clone, Copy, Debug)] +pub struct TargetInfo { + pub position: Vec3, + pub eye_y: f64, + pub bounds: Aabb, + pub alive: bool, + pub is_player: bool, + pub creative: bool, +} +impl MobWorld<'_> { + /// BlockState.isSolid (the legacy solid flag). + pub fn solid(&self, x: i32, y: i32, z: i32) -> bool { + self.data.state(self.world.block(x, y, z)).flags & data::SOLID != 0 + } + pub fn fluid(&self, x: i32, y: i32, z: i32) -> Fluid { + self.facts.get(self.world.block(x, y, z)).fluid + } + pub fn block_name(&self, x: i32, y: i32, z: i32) -> &str { + &self.facts.get(self.world.block(x, y, z)).name + } + pub fn has_tag(&self, tag: &str, block: &str) -> bool { + self.block_tags.get(tag).is_some_and(|s| s.contains(block)) + } + /// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss. + pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let result = traverse_blocks(from, to, 512, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if fluids_block && self.facts.get(state).fluid != Fluid::None { + return Some(()); + } + if self.facts.is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p).map(|_| ()) + }); + matches!(result, Ok(None)) + } + /// LivingEntity.hasLineOfSight: eye to eye within 128 blocks. + pub fn line_of_sight(&self, from_eye: Vec3, to: Vec3) -> bool { + let d = + (to.x - from_eye.x).powi(2) + (to.y - from_eye.y).powi(2) + (to.z - from_eye.z).powi(2); + if d > 128.0 * 128.0 { + return false; + } + self.clear_between(from_eye, to, false) + } + /// Level.canSeeSky: sky light 15 at the position (no roof above). + pub fn can_see_sky(&self, x: i32, y: i32, z: i32) -> bool { + if self.nether { + return false; + } + self.world.light(x, y, z) >> 4 == 15 + } + /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve + /// at the raw (sky darkened) light level. + pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 { + let light = self.world.light(x, y, z); + let sky = i32::from(light >> 4) - self.sky_darken(); + let level = sky.max(i32::from(light & 15)).clamp(0, 15) as f32; + // DimensionType.getBrightness with ambient light 0 (overworld) / 0.1 (nether). + let f = level / 15.0; + let base = f / (4.0 - 3.0 * f); + if self.nether { 0.1 + base * 0.9 } else { base } + } + pub fn sky_darken(&self) -> i32 { + if self.daylight { 0 } else { 11 } + } + pub fn target_info(&self, who: Who) -> Option { + match who { + Who::Player => self.player.as_ref().map(|p| TargetInfo { + position: p.position, + eye_y: p.eye[1], + bounds: p.bounds, + alive: p.alive, + is_player: true, + creative: p.creative, + }), + Who::Mob(id) => self.seen(id).map(|s| TargetInfo { + position: s.position, + eye_y: s.eye_y, + bounds: s.bounds, + alive: s.alive, + is_player: false, + creative: false, + }), + } + } + pub fn seen(&self, id: u32) -> Option<&Seen> { + self.others.iter().find(|s| s.id == id) + } + /// Living mobs of the given species within `range` of `from`, nearest first. + pub fn nearby<'s>( + &'s self, + from: Vec3, + range: f64, + pred: impl Fn(&Seen) -> bool + 's, + ) -> impl Iterator + 's { + let mut v: Vec<&Seen> = self + .others + .iter() + .filter(|s| { + s.alive + && (s.position.x - from.x).abs() <= range + && (s.position.y - from.y).abs() <= range + && (s.position.z - from.z).abs() <= range + }) + .filter(move |s| pred(s)) + .collect(); + v.sort_by(|a, b| { + let da = (a.position.x - from.x).powi(2) + + (a.position.y - from.y).powi(2) + + (a.position.z - from.z).powi(2); + let db = (b.position.x - from.x).powi(2) + + (b.position.y - from.y).powi(2) + + (b.position.z - from.z).powi(2); + da.total_cmp(&db) + }); + v.into_iter() + } + pub fn count_species(&self, species: Species) -> usize { + self.others + .iter() + .filter(|s| s.species == species && s.alive) + .count() + } +} diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs new file mode 100644 index 000000000..7617182d7 --- /dev/null +++ b/crates/horizon-client/src/projectiles.rs @@ -0,0 +1,408 @@ +//! Projectiles fired by mobs and thrown by the player: arrows +//! (`AbstractArrow`, gravity 0.05), throwables (`ThrowableProjectile`: +//! snowballs, eggs, ender pearls, gravity 0.03) and fireballs +//! (`AbstractHurtingProjectile`: no gravity, 0.1 acceleration, 0.95 inertia). +//! The game applies the effects of a hit. +use crate::mobs::Who; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; + +#[derive(Clone, Debug, PartialEq)] +pub enum ProjectileKind { + /// Arrow with its base damage, critical flag and tipped/stray/bogged effect. + Arrow { + base_damage: f64, + critical: bool, + effect: Option<(&'static str, i32)>, + }, + Snowball, + Egg, + EnderPearl, + SmallFireball, + LargeFireball { + power: i32, + }, + LlamaSpit, + /// Splash potion thrown by witches: effect id, duration. + Potion { + effect: &'static str, + ticks: i32, + amplifier: i32, + color: u32, + }, +} +#[derive(Clone, Debug, PartialEq)] +pub struct Projectile { + pub kind: ProjectileKind, + pub owner: Option, + pub position: Vec3, + pub previous: Vec3, + pub velocity: Vec3, + pub yaw: f32, + pub pitch: f32, + pub age: u32, + pub stuck: bool, + /// Whether the projectile has left its owner's box (Projectile.leftOwner). + pub left_owner: bool, +} +/// What a projectile struck this tick. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Hit { + None, + Block { + pos: [i32; 3], + at: Vec3, + face: [i32; 3], + }, + Entity { + who: Who, + at: Vec3, + }, +} +/// The world a projectile flies through: block ray clipping, water, and +/// the boxes of entities it could hit. +pub trait ProjectileWorld { + fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])>; + fn in_water(&self, at: Vec3) -> bool; + fn targets(&self) -> &[(Who, Aabb)]; +} +impl Projectile { + pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { + Self { + kind, + owner, + position, + previous: position, + velocity: Vec3::ZERO, + yaw: 0.0, + pitch: 0.0, + age: 0, + stuck: false, + left_owner: false, + } + } + pub fn is_arrow(&self) -> bool { + matches!(self.kind, ProjectileKind::Arrow { .. }) + } + pub fn is_fireball(&self) -> bool { + matches!( + self.kind, + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } + ) + } + fn gravity(&self) -> f64 { + match self.kind { + ProjectileKind::Arrow { .. } => 0.05, + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 0.0, + ProjectileKind::LlamaSpit => 0.06, + ProjectileKind::Potion { .. } => 0.05, + _ => 0.03, + } + } + /// Projectile.shoot: normalized direction plus triangular noise, times speed. + pub fn shoot( + &mut self, + random: &mut impl RandomSource, + dir: [f64; 3], + speed: f32, + uncertainty: f32, + ) { + let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) + .sqrt() + .max(1.0e-9); + let spread = 0.017_227_5 * f64::from(uncertainty); + let v = [ + (dir[0] / len + random.triangle(0.0, spread)) * f64::from(speed), + (dir[1] / len + random.triangle(0.0, spread)) * f64::from(speed), + (dir[2] / len + random.triangle(0.0, spread)) * f64::from(speed), + ]; + self.velocity = Vec3::new(v[0], v[1], v[2]); + self.update_rotation(); + } + /// Projectile.shootFromRotation for player throws. + pub fn shoot_from_rotation( + &mut self, + random: &mut impl RandomSource, + pitch: f32, + yaw: f32, + offset: f32, + speed: f32, + uncertainty: f32, + source_velocity: Vec3, + source_on_ground: bool, + ) { + let (p, y, o) = ( + pitch.to_radians(), + yaw.to_radians(), + (pitch + offset).to_radians(), + ); + let dir = [ + f64::from(-y.sin() * p.cos()), + f64::from(-o.sin()), + f64::from(y.cos() * p.cos()), + ]; + self.shoot(random, dir, speed, uncertainty); + self.velocity = Vec3::new( + self.velocity.x + source_velocity.x, + self.velocity.y + + if source_on_ground { + 0.0 + } else { + source_velocity.y + }, + self.velocity.z + source_velocity.z, + ); + } + /// AbstractHurtingProjectile: movement along the direction at the acceleration power. + pub fn fireball( + kind: ProjectileKind, + position: Vec3, + owner: Option, + dir: [f64; 3], + ) -> Self { + let mut p = Self::new(kind, position, owner); + let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) + .sqrt() + .max(1.0e-9); + p.velocity = Vec3::new(dir[0] / len * 0.1, dir[1] / len * 0.1, dir[2] / len * 0.1); + p.update_rotation(); + p + } + fn update_rotation(&mut self) { + let v = self.velocity; + let sd = (v.x * v.x + v.z * v.z).sqrt(); + self.yaw = v.x.atan2(v.z).to_degrees() as f32; + self.pitch = v.y.atan2(sd).to_degrees() as f32; + } + /// One tick: returns whether to keep the projectile and what it hit. + pub fn tick(&mut self, w: &impl ProjectileWorld) -> (bool, Hit) { + self.previous = self.position; + self.age += 1; + if self.stuck { + // AbstractArrow despawns 1200 ticks after sticking. + return (self.age < 1200, Hit::None); + } + let water = w.in_water(self.position); + match self.kind { + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { + let inertia = if water { 0.8 } else { 0.95 }; + let v = self.velocity; + let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); + self.velocity = Vec3::new( + (v.x + v.x / len * 0.1) * inertia, + (v.y + v.y / len * 0.1) * inertia, + (v.z + v.z / len * 0.1) * inertia, + ); + } + ProjectileKind::Arrow { .. } => {} + _ => { + // ThrowableProjectile: gravity, then inertia. + self.velocity.y -= self.gravity(); + let inertia = if water { 0.8 } else { 0.99 }; + self.velocity = Vec3::new( + self.velocity.x * inertia, + self.velocity.y * inertia, + self.velocity.z * inertia, + ); + } + } + let from = self.position; + let to = Vec3::new( + from.x + self.velocity.x, + from.y + self.velocity.y, + from.z + self.velocity.z, + ); + let block = w.clip(from, to); + let end = block.map_or(to, |b| b.0); + // ProjectileUtil.getEntityHitResult: boxes inflated by 0.3 along the path. + let mut best: Option<(Who, Vec3, f64)> = None; + for (who, b) in w.targets() { + if Some(*who) == self.owner && !self.left_owner { + continue; + } + let inflated = b.inflate(Vec3::new(0.3, 0.3, 0.3)); + if let Some(at) = inflated.clip(from, end) { + let d = (at.x - from.x).powi(2) + (at.y - from.y).powi(2) + (at.z - from.z).powi(2); + if best.is_none_or(|bb| d < bb.2) { + best = Some((*who, at, d)); + } + } + } + if !self.left_owner { + // Leave the owner once no target box (the owner's) contains us. + let owner_box = w + .targets() + .iter() + .find(|(who, _)| Some(*who) == self.owner) + .map(|(_, b)| *b); + self.left_owner = owner_box + .is_none_or(|b| !b.inflate(Vec3::new(1.0, 1.0, 1.0)).contains(self.position)); + } + if let Some((who, at, _)) = best { + self.position = at; + return (false, Hit::Entity { who, at }); + } + if let Some((at, pos, face)) = block { + self.position = at; + if self.is_arrow() { + // AbstractArrow.onHitBlock: stick, nudged back out of the face. + let v = self.velocity; + let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); + self.position = Vec3::new( + at.x - v.x / len * 0.05, + at.y - v.y / len * 0.05, + at.z - v.z / len * 0.05, + ); + self.stuck = true; + self.age = 0; + return (true, Hit::Block { pos, at, face }); + } + return (false, Hit::Block { pos, at, face }); + } + self.position = to; + if self.is_arrow() { + // AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity. + let inertia = if water { 0.6 } else { 0.99 }; + self.velocity = Vec3::new( + self.velocity.x * inertia, + self.velocity.y * inertia - self.gravity(), + self.velocity.z * inertia, + ); + self.update_rotation(); + } else if !self.is_fireball() { + self.update_rotation(); + } + let alive = + self.position.y > -128.0 && self.age < if self.is_fireball() { 1200 } else { 6000 }; + (alive, Hit::None) + } + /// AbstractArrow.onHitEntity damage: ceil(speed * base) plus crit bonus. + pub fn arrow_damage(&self, random: &mut impl RandomSource) -> f32 { + let ProjectileKind::Arrow { + base_damage, + critical, + .. + } = self.kind + else { + return 0.0; + }; + let v = self.velocity; + let speed = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt(); + let mut damage = (speed * base_damage).clamp(0.0, f64::from(i32::MAX)).ceil() as i32; + if critical { + let bonus = random.next_int_bound(damage / 2 + 2).unwrap_or(0); + damage = damage.saturating_add(bonus); + } + damage as f32 + } + /// The item sprite drawn for thrown projectiles (ThrownItemRenderer). + pub fn item_sprite(&self) -> Option<&'static str> { + Some(match self.kind { + ProjectileKind::Snowball => "item/snowball", + ProjectileKind::Egg => "item/egg", + ProjectileKind::EnderPearl => "item/ender_pearl", + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { + "item/fire_charge" + } + ProjectileKind::Potion { .. } => "item/splash_potion", + ProjectileKind::LlamaSpit => "entity/llama/llama_spit", + ProjectileKind::Arrow { .. } => return None, + }) + } + /// Render scale of the item billboard (fireball renderers). + pub fn sprite_scale(&self) -> f32 { + match self.kind { + ProjectileKind::LargeFireball { .. } => 3.0, + ProjectileKind::SmallFireball => 0.75, + _ => 1.0, + } + } +} +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + struct Empty(Vec<(Who, Aabb)>); + impl ProjectileWorld for Empty { + fn clip(&self, _: Vec3, _: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> { + None + } + fn in_water(&self, _: Vec3) -> bool { + false + } + fn targets(&self) -> &[(Who, Aabb)] { + &self.0 + } + } + #[test] + fn snowball_falls_with_throwable_gravity_and_drag() { + let mut p = Projectile::new(ProjectileKind::Snowball, Vec3::new(0.0, 100.0, 0.0), None); + p.velocity = Vec3::new(1.0, 0.0, 0.0); + let w = Empty(vec![]); + p.tick(&w); + // ThrowableProjectile: gravity before inertia, then move. + assert!((p.velocity.y - (-0.03 * 0.99)).abs() < 1e-9); + assert!((p.position.x - 0.99).abs() < 1e-9); + } + #[test] + fn arrow_applies_drag_then_gravity_after_moving() { + let mut p = Projectile::new( + ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + Vec3::new(0.0, 100.0, 0.0), + None, + ); + p.velocity = Vec3::new(3.0, 0.0, 0.0); + let w = Empty(vec![]); + p.tick(&w); + assert!((p.position.x - 3.0).abs() < 1e-9); + assert!((p.velocity.x - 2.97).abs() < 1e-9); + assert!((p.velocity.y + 0.05).abs() < 1e-9); + } + #[test] + fn arrow_hits_entity_box_inflated_by_margin() { + let target = Aabb::new(Vec3::new(2.0, 99.0, -0.3), Vec3::new(2.6, 100.8, 0.3)); + let mut p = Projectile::new( + ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + Vec3::new(0.0, 100.0, 0.0), + None, + ); + p.velocity = Vec3::new(3.0, 0.0, 0.0); + let w = Empty(vec![(Who::Mob(7), target)]); + let (keep, hit) = p.tick(&w); + assert!(!keep); + assert!(matches!( + hit, + Hit::Entity { + who: Who::Mob(7), + .. + } + )); + let mut r = LegacyRandom::new(1); + // ceil(3 * 2) = 6 for a non-critical arrow. + assert_eq!(p.arrow_damage(&mut r), 6.0); + } + #[test] + fn fireball_accelerates_along_its_direction() { + let mut p = Projectile::fireball( + ProjectileKind::SmallFireball, + Vec3::new(0.0, 100.0, 0.0), + None, + [1.0, 0.0, 0.0], + ); + let w = Empty(vec![]); + p.tick(&w); + // (0.1 + 0.1) * 0.95 + assert!((p.velocity.x - 0.19).abs() < 1e-9); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobDataExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobDataExporter.java new file mode 100644 index 000000000..2163d8d3c --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobDataExporter.java @@ -0,0 +1,197 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.zip.ZipFile; +import com.mojang.serialization.JsonOps; +import net.minecraft.SharedConstants; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagFile; +import net.minecraft.tags.TagKey; +import net.minecraft.tags.TagLoader; +import net.minecraft.client.animation.AnimationChannel; +import net.minecraft.client.animation.AnimationDefinition; +import net.minecraft.client.animation.Keyframe; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.SpawnPlacementTypes; +import net.minecraft.world.entity.SpawnPlacements; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.pathfinder.PathComputationType; +import net.minecraft.world.level.pathfinder.PathType; +import net.minecraft.world.level.pathfinder.WalkNodeEvaluator; + +/** + * Original exporter of the facts the client's mob AI and renderer read from vanilla code: + * per-state pathfinding types (WalkNodeEvaluator.getPathTypeFromState), pathfindability, + * spawn-surface predicates, each entity type's spawn placement, and every keyframe + * animation definition of the client's entity models. + */ +@SuppressWarnings("unchecked") +public final class VanillaMobDataExporter { + /** A level holding one block state at the origin and air elsewhere. */ + private record OneBlock(BlockState state) implements BlockGetter { + public BlockEntity getBlockEntity(BlockPos pos) { return null; } + public BlockState getBlockState(BlockPos pos) { return pos.equals(BlockPos.ZERO) ? state : Blocks.AIR.defaultBlockState(); } + public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + public int getHeight() { return 384; } + public int getMinY() { return -64; } + } + + private static JsonArray states() throws Exception { + Method pathType = WalkNodeEvaluator.class.getDeclaredMethod("getPathTypeFromState", BlockGetter.class, BlockPos.class); + pathType.setAccessible(true); + var out = new JsonArray(); + var empty = EmptyBlockGetter.INSTANCE; + for (var state : Block.BLOCK_STATE_REGISTRY) { + var level = new OneBlock(state); + var type = (PathType) pathType.invoke(null, level, BlockPos.ZERO); + var shape = state.getCollisionShape(empty, BlockPos.ZERO); + var o = new JsonArray(); + o.add(type.name()); + int flags = 0; + if (state.isPathfindable(PathComputationType.LAND)) flags |= 1; + if (state.isPathfindable(PathComputationType.WATER)) flags |= 2; + if (state.isPathfindable(PathComputationType.AIR)) flags |= 4; + if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.ZOMBIE)) flags |= 8; + if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.OCELOT)) flags |= 16; + if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.POLAR_BEAR)) flags |= 32; + if (state.isRedstoneConductor(empty, BlockPos.ZERO)) flags |= 64; + if (net.minecraft.world.level.NaturalSpawner.isValidEmptySpawnBlock(level, BlockPos.ZERO, state, state.getFluidState(), EntityTypes.ZOMBIE)) flags |= 128; + if (state.isFaceSturdy(empty, BlockPos.ZERO, Direction.UP)) flags |= 256; + if (state.isSolid()) flags |= 512; + if (state.isSolidRender()) flags |= 1024; + o.add(flags); + o.add(shape.isEmpty() ? 0.0 : shape.max(Direction.Axis.Y)); + out.add(o); + } + return out; + } + + private static JsonObject placements() { + var out = new JsonObject(); + for (var type : BuiltInRegistries.ENTITY_TYPE) { + var placement = SpawnPlacements.getPlacementType(type); + String name = placement == SpawnPlacementTypes.ON_GROUND ? "on_ground" + : placement == SpawnPlacementTypes.IN_WATER ? "in_water" + : placement == SpawnPlacementTypes.IN_LAVA ? "in_lava" : "no_restrictions"; + var o = new JsonObject(); + o.addProperty("placement", name); + o.addProperty("heightmap", SpawnPlacements.getHeightmapType(type).getSerializedName()); + out.add(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString(), o); + } + return out; + } + + private static JsonArray vector(org.joml.Vector3fc v) { + var a = new JsonArray(); + a.add(v.x()); a.add(v.y()); a.add(v.z()); + return a; + } + + private static JsonObject definition(AnimationDefinition d) { + var o = new JsonObject(); + o.addProperty("length", d.lengthInSeconds()); + o.addProperty("looping", d.looping()); + var bones = new JsonObject(); + for (var entry : new TreeMap<>(d.boneAnimations()).entrySet()) { + var channels = new JsonArray(); + for (AnimationChannel channel : entry.getValue()) { + var c = new JsonObject(); + var target = channel.target(); + c.addProperty("target", target == AnimationChannel.Targets.POSITION ? "position" + : target == AnimationChannel.Targets.ROTATION ? "rotation" : "scale"); + var frames = new JsonArray(); + for (Keyframe k : channel.keyframes()) { + var f = new JsonArray(); + f.add(k.timestamp()); + f.add(vector(k.preTarget())); + f.add(vector(k.postTarget())); + f.add(k.interpolation() == AnimationChannel.Interpolations.CATMULLROM ? "catmullrom" : "linear"); + frames.add(f); + } + c.add("keyframes", frames); + channels.add(c); + } + bones.add(entry.getKey(), channels); + } + o.add("bones", bones); + return o; + } + + private static JsonObject animations(String clientJar) throws Exception { + var out = new JsonObject(); + var names = new TreeSet(); + try (var zip = new ZipFile(clientJar)) { + var entries = zip.entries(); + while (entries.hasMoreElements()) { + var name = entries.nextElement().getName(); + if (name.startsWith("net/minecraft/client/animation/definitions/") && name.endsWith(".class") && !name.contains("$")) + names.add(name.substring(0, name.length() - 6).replace('/', '.')); + } + } + for (var name : names) { + var cls = Class.forName(name); + for (var field : cls.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) && field.getType() == AnimationDefinition.class) { + field.setAccessible(true); + out.add(cls.getSimpleName() + "." + field.getName(), definition((AnimationDefinition) field.get(null))); + } + } + } + return out; + } + + /** Binds one registry's vanilla tags from the jar's data pack, as a server reload would. */ + private static void bindTags(ZipFile jar, Registry registry, ResourceKey> key, String folder) throws Exception { + var loader = new TagLoader>((id, required) -> registry.get(id).map(value -> (Holder) value), "tags/" + folder); + var definitions = new HashMap>(); + var prefix = "data/minecraft/tags/" + folder + "/"; + var entries = jar.entries(); + while (entries.hasMoreElements()) { + var entry = entries.nextElement(); + var name = entry.getName(); + if (!name.startsWith(prefix) || !name.endsWith(".json")) continue; + var text = new String(jar.getInputStream(entry).readAllBytes(), StandardCharsets.UTF_8); + var file = TagFile.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseString(text)).getOrThrow(); + var list = new ArrayList(); + for (var e : file.entries()) list.add(new TagLoader.EntryWithSource(e, "vanilla")); + definitions.put(Identifier.parse("minecraft:" + name.substring(prefix.length(), name.length() - 5)), list); + } + var tags = new HashMap, List>>(); + loader.build(definitions).forEach((id, values) -> tags.put(TagKey.create(key, id), List.copyOf(values))); + registry.prepareTagReload(new TagLoader.LoadResult<>(key, tags)).apply(); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + try (var jar = new ZipFile(args[1])) { + bindTags(jar, BuiltInRegistries.BLOCK, Registries.BLOCK, "block"); + bindTags(jar, BuiltInRegistries.FLUID, Registries.FLUID, "fluid"); + } + var result = new JsonObject(); + result.add("states", states()); + result.add("placements", placements()); + result.add("animations", animations(args[1])); + Files.writeString(Path.of(args[0]), new Gson().toJson(result), StandardCharsets.UTF_8); + } +} diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 6be907b70..fb4bc29db 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -343,6 +343,22 @@ def main(): subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityModelExporter', str(entity_models)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + # Mob AI and animation facts: per-state path types, spawn placements and the + # client's keyframe animation definitions (needs the client jar). + mob_data = root / 'mob-data.json' + mob_oracle = oracle.with_name('VanillaMobDataExporter.java') + mob_sources = base.source_hashes([mob_oracle]) + if not (previous.get('mob_data_exporters_sha256') == mob_sources and mob_data.exists() + and previous.get('client_sha256') == origin['client_sha256']): + classes = lab.LOCAL / 'mob-data' / 'classes'; classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + with (root / 'mob-data-export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', dependencies, '-d', str(classes), str(mob_oracle)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaMobDataExporter', str(mob_data), str(jars['client'])], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) creative = root / 'creative-tabs.json' creative_oracle = oracle.with_name('VanillaCreativeTabsExporter.java') creative_sources = base.source_hashes([creative_oracle]) @@ -371,6 +387,7 @@ def main(): 'gameplay_exporters_sha256': gameplay_sources, 'entity_model_exporters_sha256': entity_sources, 'creative_exporters_sha256': creative_sources, + 'mob_data_exporters_sha256': mob_sources, 'entity_types_exporters_sha256': entity_types_sources, 'behaviour_exporters_sha256': behaviour_sources, 'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'],