diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 682ae8606..a02fc467b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -7,6 +7,7 @@ //! behaviour, models, animations and sounds. pub mod ai; pub mod anim; +pub mod aquatic; pub mod data; pub mod control; pub mod farm; @@ -310,6 +311,14 @@ impl Damage { matches!(self.kind, DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball) } } +/// Per-mob attribute base values (the type's defaults unless changed). +#[derive(Clone, Copy, Debug)] +pub struct Attrs { + pub speed: f64, + pub attack_damage: f32, + pub max_health: f32, + pub follow_range: f64, +} /// Species-specific persistent state (variants, colours, taming, ageing...). #[derive(Clone, Debug, Default)] pub struct Extra { @@ -350,6 +359,8 @@ pub struct Extra { pub home: Option<[i32; 3]>, pub point: Option<[f64; 3]>, pub vector: [f64; 3], + /// Active status effects: (effect id, ticks left, amplifier). + pub effects: Vec<(&'static str, i32, i32)>, } #[derive(Clone, Debug)] pub struct Mob { @@ -398,6 +409,8 @@ pub struct Mob { pub removed: bool, /// Client-side animation clocks (attack swing, eating, shaking...). pub anim: anim::AnimState, + /// Attribute values that differ per mob (slime size, babies, effects). + pub attrs: Attrs, } /// Events a mob tick asks the game to act on. #[derive(Clone, Debug)] @@ -538,6 +551,7 @@ impl Mob { last_damage: None, removed: false, anim: anim::AnimState::default(), + attrs: Attrs { speed: kind.speed, attack_damage: kind.attack_damage, max_health: kind.max_health, follow_range: kind.follow_range }, kind, }; ai::register(&mut mob); @@ -652,6 +666,29 @@ impl Mob { (p.x - self.position.x).powi(2) + (p.y - self.position.y).powi(2) + (p.z - self.position.z).powi(2) } /// Movement speed attribute bonus (baby zombies, sprinting modifiers). + /// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level). + pub fn movement_speed(&self) -> f64 { + let mut v = self.attrs.speed * self.speed_bonus(); + for (e, _, amp) in &self.extra.effects { + match *e { + "minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1), + "minecraft:slowness" => v *= (1.0 - 0.15 * f64::from(amp + 1)).max(0.0), + _ => {} + } + } + v + } + pub fn has_effect(&self, effect: &str) -> bool { + self.extra.effects.iter().any(|e| e.0 == effect) + } + pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { + if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { + e.1 = e.1.max(ticks); + e.2 = e.2.max(amplifier); + } else { + self.extra.effects.push((effect, ticks, amplifier)); + } + } pub fn speed_bonus(&self) -> f64 { ai::speed_bonus(self) } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 1aebaa162..00739f766 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -2,7 +2,7 @@ //! `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, + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, aquatic, control::{BodyRotation, LookControl, MoveControl}, farm, goals::{Cx, GoalSelector}, @@ -57,20 +57,50 @@ impl Mob { } } } -pub fn register(m: &mut Mob) { +/// The module implementing a species' behaviour. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Family { + Farm, + Undead, + Hostile, + Aquatic, + Generic, +} +pub fn family(s: Species) -> Family { 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), + match s { + S::Pig | S::Cow | S::Mooshroom | S::Sheep | S::Chicken => Family::Farm, + S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::Skeleton | S::Stray | S::Bogged | S::WitherSkeleton => Family::Undead, + S::Creeper | S::Spider | S::CaveSpider => Family::Hostile, + S::Squid | S::GlowSquid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => Family::Aquatic, + _ => Family::Generic, + } +} +pub fn register(m: &mut Mob) { + match family(m.species()) { + Family::Farm => farm::register(m), + Family::Undead => undead::register(m), + Family::Hostile => hostile::register(m), + Family::Aquatic => aquatic::register(m), + Family::Generic => generic(m), + } +} +/// Mob.tick additions that run before the entity tick (creeper fuse, puffing). +fn pre_tick(m: &mut Mob, events: &mut Vec) { + match family(m.species()) { + Family::Hostile => { + if m.species() == Species::Creeper { + hostile::creeper_tick(m, events) + } + } + Family::Aquatic => aquatic::tick(m, events), + _ => {} + } +} +/// Move controls implemented by the species (MoveKind::Custom). +pub fn custom_move_control(m: &mut Mob) { + if family(m.species()) == Family::Aquatic { + aquatic::fish_move_control(m) } } /// A fallback for species without bespoke goals yet: animals stroll and @@ -113,10 +143,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { 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), - _ => {} - } + pre_tick(m, events); if m.removed { return false; } @@ -218,6 +245,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.damage(1.0, Damage::of(DamageKind::Drown)); } } + tick_effects(m); if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -245,7 +273,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { 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 { + if m.extra.tame && m.health < m.attrs.max_health / 2.0 { "entity.wolf.whine" } else { "entity.wolf.pant" @@ -388,6 +416,9 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { } } fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if family(m.species()) == Family::Aquatic { + aquatic::ai_step(m, w, events); + } match m.species() { Species::Chicken => farm::chicken_ai_step(m, w, events), Species::Sheep => { @@ -493,7 +524,7 @@ pub fn after_hurt(m: &mut Mob, _source: &Damage) { } /// 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 mut amount = m.attrs.attack_damage; let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); match m.species() { @@ -547,6 +578,31 @@ pub fn ate(m: &mut Mob) { } /// 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 + match family(m.species()) { + Family::Aquatic => aquatic::travel(m, w, input, events), + _ => false, + } +} + +/// MobEffect ticking for the effects mobs receive (poison, wither, regeneration). +fn tick_effects(m: &mut Mob) { + let mut effects = std::mem::take(&mut m.extra.effects); + for (effect, ticks, amp) in &mut effects { + let interval = |base: i32| (base >> (*amp).max(0)).max(1); + match *effect { + "minecraft:poison" if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => { + m.damage(1.0, Damage::of(DamageKind::Magic)); + } + "minecraft:wither" if *ticks % interval(40) == 0 => { + m.damage(1.0, Damage::of(DamageKind::Magic)); + } + "minecraft:regeneration" if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => { + m.health = (m.health + 1.0).min(m.attrs.max_health); + } + _ => {} + } + *ticks -= 1; + } + effects.retain(|e| e.1 > 0); + m.extra.effects = effects; } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b77a863f8..3f23d6ff4 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -70,20 +70,19 @@ pub struct AnimState { 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, + /// Per-species animation values (tail wag, squid tentacles, squish...) + /// with their previous-tick copies for interpolation. + pub v: [f32; 8], + pub vo: [f32; 8], } 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; + self.vo = self.v; + } + /// Interpolated value `i` at the render partial tick. + pub fn lerp(&self, i: usize, partial: f32) -> f32 { + self.vo[i] + (self.v[i] - self.vo[i]) * partial } pub fn end_tick(&mut self, _swinging: bool) {} } @@ -326,6 +325,7 @@ pub fn setup( ) { let _ = w_anims; match m.kind.anim { + Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => super::aquatic::anim(m, s, p), Anim::Quadruped | Anim::PolarBear | Anim::Panda | Anim::Goat => quadruped(p, s), Anim::Sheep => { quadruped(p, s); diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs new file mode 100644 index 000000000..2b753d912 --- /dev/null +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -0,0 +1,427 @@ +//! Water mobs: squid and glow squid (tentacle propulsion), cod, salmon, +//! tropical fish and pufferfish (`AbstractFish`, puffing), and dolphins +//! (breathing, smooth swimming). +use super::{ + Mob, MobEvent, MobWorld, Species, + anim::{Poses, State}, + control::MoveKind, + goals::{ + Avoid, AvoidEntity, BreathAir, Cx, Goal, HurtByTarget, LookAtPlayer, MeleeAttack, Panic, + RandomLookAround, Stroll, TryFindWater, goal_clone, + }, + nav::NavKind, +}; +use crate::blocks::Fluid; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::f32::consts::PI; + +// Squid animation slots in AnimState.v. +const TENTACLE_MOVEMENT: usize = 0; +const TENTACLE_ANGLE: usize = 1; +const X_BODY_ROT: usize = 2; +const Z_BODY_ROT: usize = 3; +const TENTACLE_SPEED: usize = 4; +const ROTATE_SPEED: usize = 5; + +pub fn register(m: &mut Mob) { + use Species as S; + match m.species() { + S::Squid | S::GlowSquid => { + m.ai.goals.add(0, SquidRandomMovement); + m.ai.goals.add(1, SquidFlee { ticks: 0 }); + m.ai.mov.kind = MoveKind::Custom; + m.ai.nav.kind = NavKind::Water { breach: false }; + let speed = 1.0 / (m.random.next_float() + 1.0) * 0.2; + m.anim.v[TENTACLE_SPEED] = speed; + } + S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish => { + let puffer = m.species() == S::Pufferfish; + let g = &mut m.ai.goals; + g.add(0, Panic::new(1.25)); + g.add(2, AvoidEntity::new(Avoid::Player, 8.0, 1.6, 1.4)); + g.add(4, Stroll::swimming(1.0, 40)); + if puffer { + g.add(1, PufferfishPuff); + } + m.ai.mov.kind = MoveKind::Custom; + m.ai.nav.kind = NavKind::Water { breach: false }; + } + S::Dolphin => { + let g = &mut m.ai.goals; + g.add(0, BreathAir); + g.add(0, TryFindWater::default()); + g.add(4, Stroll::swimming(1.0, 10)); + g.add(4, RandomLookAround::default()); + g.add(5, LookAtPlayer::new(6.0)); + g.add(6, MeleeAttack::new(1.2, true)); + m.ai.targets.add(1, HurtByTarget::new().alert()); + m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, max_turn_y: 10.0, in_water: 0.02, outside: 0.1, gravity: true }; + m.ai.look.kind = super::control::LookKind::SmoothSwimming(10.0); + m.ai.nav.kind = NavKind::Water { breach: true }; + m.air = 4800; + } + _ => {} + } +} +/// Pre-tick updates (Pufferfish.tick puff state). +pub fn tick(m: &mut Mob, events: &mut Vec) { + if m.species() != Species::Pufferfish || !m.alive() { + return; + } + let puff = m.extra.size; + if m.extra.counter > 0 { + if puff == 0 { + m.sound("entity.puffer_fish.blow_up", events); + m.extra.size = 1; + } else if m.extra.counter > 40 && puff == 1 { + m.sound("entity.puffer_fish.blow_up", events); + m.extra.size = 2; + } + m.extra.counter += 1; + } else if puff != 0 { + if m.extra.counter2 > 60 && puff == 2 { + m.sound("entity.puffer_fish.blow_out", events); + m.extra.size = 1; + } else if m.extra.counter2 > 100 && puff == 1 { + m.sound("entity.puffer_fish.blow_out", events); + m.extra.size = 0; + } + m.extra.counter2 += 1; + } +} +/// Pufferfish.getScale by puff state (the dimensions scale with it). +pub fn puff_scale(state: i32) -> f64 { + match state { + 0 => 0.5, + 1 => 0.7, + _ => 1.0, + } +} +/// Species aiStep additions. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + use Species as S; + match m.species() { + S::Squid | S::GlowSquid => squid_ai_step(m), + S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish => { + // AbstractFish.aiStep flops on land (applied before travel next tick). + if !m.fluids.in_water && m.on_ground && m.vertical_collision_below { + let (a, b) = (m.random.next_float(), m.random.next_float()); + m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.05), m.velocity.y + 0.4, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.05)); + m.on_ground = false; + let flop = match m.species() { + S::Cod => "entity.cod.flop", + S::Salmon => "entity.salmon.flop", + S::TropicalFish => "entity.tropical_fish.flop", + _ => "entity.puffer_fish.flop", + }; + m.sound(flop, events); + } + if m.species() == S::Pufferfish && m.alive() && m.extra.size > 0 { + // Pufferfish.playerTouch / touch: sting with poison. + if let Some(p) = &w.player + && p.alive + && !p.creative + && m.bounds().inflate(Vec3::new(0.3, 0.3, 0.3)).intersects(p.bounds) + && m.ai.no_action_time % 10 == 0 + { + let amount = 1.0 + m.extra.size as f32; + events.push(MobEvent::AttackPlayer(amount, [m.position.x, m.position.y, m.position.z])); + events.push(MobEvent::EffectPlayer { effect: "minecraft:poison", ticks: 60 * m.extra.size, amplifier: 0 }); + m.sound("entity.puffer_fish.sting", events); + } + } + } + S::Dolphin => { + // Dolphin.tick: moisture out of water, hop on land. + if m.fluids.in_water || w.raining { + m.extra.counter = 2400; + } else { + m.extra.counter -= 1; + if m.extra.counter <= 0 { + m.damage(1.0, super::Damage::of(super::DamageKind::Drown)); + } + if m.on_ground { + let (a, b) = (m.random.next_float(), m.random.next_float()); + m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.2), m.velocity.y + 0.5, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.2)); + m.yaw = m.random.next_float() * 360.0; + m.on_ground = false; + } + } + // LivingEntity air: dolphins drown underwater and refill instantly in air. + if !m.fluids.eye_in_water { + m.air = 4800; + } + } + _ => {} + } +} +/// Squid.aiStep: tentacle cycle, propulsion and body rotation. +fn squid_ai_step(m: &mut Mob) { + let v = &mut m.anim.v; + v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED]; + if v[TENTACLE_MOVEMENT] > PI * 2.0 { + v[TENTACLE_MOVEMENT] -= PI * 2.0; + if m.random.next_int_bound(10).unwrap_or(1) == 0 { + m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2; + } + } + let v = &mut m.anim.v; + if m.fluids.in_water { + if v[TENTACLE_MOVEMENT] < PI { + let scale = v[TENTACLE_MOVEMENT] / PI; + v[TENTACLE_ANGLE] = (scale * scale * PI).sin() * PI * 0.25; + if scale > 0.75 { + let mv = m.extra.vector; + m.velocity = Vec3::new(mv[0], mv[1], mv[2]); + m.anim.v[ROTATE_SPEED] = 1.0; + } else { + m.anim.v[ROTATE_SPEED] *= 0.8; + } + } else { + v[TENTACLE_ANGLE] = 0.0; + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + m.anim.v[ROTATE_SPEED] *= 0.99; + } + let mv = m.velocity; + let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt(); + m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1; + m.yaw = m.body_yaw; + let v = &mut m.anim.v; + v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5; + v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1; + } else { + v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].sin().abs() * PI * 0.25; + let yd = m.velocity.y - m.kind.gravity; + m.velocity = Vec3::new(0.0, yd * 0.98, 0.0); + let v = &mut m.anim.v; + v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02; + } +} +/// Species travel overrides. Returns true when handled. +pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec) -> bool { + use Species as S; + match m.species() { + // Squid.travel: move by the current velocity only. + S::Squid | S::GlowSquid => { + m.do_move(w, events); + true + } + // AbstractFish.travelInWater / Dolphin.travelInWater. + S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin if m.fluids.in_water => { + let speed = if m.species() == S::Dolphin { m.ai.speed } else { 0.01 }; + m.move_relative(speed, input); + m.do_move(w, events); + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + if m.ai.target.is_none() { + m.velocity.y -= 0.005; + } + true + } + _ => false, + } +} +/// FishMoveControl.tick (fish use it instead of the default move control). +pub fn fish_move_control(m: &mut Mob) { + if !matches!(m.species(), Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish) { + return; + } + if m.fluids.eye_in_water { + m.velocity.y += 0.005; + } + if m.ai.mov.operation == super::control::Operation::MoveTo && !m.ai.nav.is_done() { + let target = (m.ai.mov.speed_modifier * m.movement_speed()) as f32; + let speed = m.ai.speed + (target - m.ai.speed) * 0.125; + m.set_speed(speed); + let [wx, wy, wz] = m.ai.mov.wanted; + let (xd, yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z); + if yd != 0.0 { + let dd = (xd * xd + yd * yd + zd * zd).sqrt(); + m.velocity.y += f64::from(m.ai.speed) * (yd / dd) * 0.1; + } + if xd != 0.0 || zd != 0.0 { + let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0; + m.yaw = super::control::rotlerp(m.yaw, y_rot, 90.0); + m.body_yaw = m.yaw; + } + } else { + m.set_speed(0.0); + } +} +/// Squid.SquidRandomMovementGoal +#[derive(Clone, Debug)] +pub struct SquidRandomMovement; +impl Goal for SquidRandomMovement { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + if m.ai.no_action_time > 100 { + m.extra.vector = [0.0; 3]; + } else if m.random.next_int_bound(super::goals::reduced(50)).unwrap_or(1) == 0 || !m.fluids.in_water || m.extra.vector == [0.0; 3] { + let angle = m.random.next_float() * PI * 2.0; + let y = -0.1 + m.random.next_float() * 0.2; + m.extra.vector = [f64::from(angle.cos() * 0.2), f64::from(y), f64::from(angle.sin() * 0.2)]; + } + } +} +/// Squid.SquidFleeGoal (keeps vanilla's discarded normalize()). +#[derive(Clone, Debug)] +pub struct SquidFlee { + ticks: i32, +} +impl Goal for SquidFlee { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return false }; + m.fluids.in_water && m.distance_sqr(by.position) < 100.0 + } + fn start(&mut self, _: &mut Mob, _: &mut Cx) { + self.ticks = 0; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.ticks += 1; + let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return }; + let mut f = [m.position.x - by.position.x, m.position.y - by.position.y, m.position.z - by.position.z]; + let at = [(m.position.x + f[0]).floor() as i32, (m.position.y + f[1]).floor() as i32, (m.position.z + f[2]).floor() as i32]; + let air = cx.w.facts.is_air(cx.w.world.block(at[0], at[1], at[2])); + if cx.w.fluid(at[0], at[1], at[2]) == Fluid::Water || air { + let length = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt(); + if length > 0.0 { + let mut avoid = 3.0; + if length > 5.0 { + avoid -= (length - 5.0) / 5.0; + } + if avoid > 0.0 { + f = f.map(|c| c * avoid); + } + } + if air { + f[1] = 0.0; + } + m.extra.vector = [f[0] / 20.0, f[1] / 20.0, f[2] / 20.0]; + } + } +} +/// Pufferfish.PufferfishPuffGoal: inflate when a mob or player is within 2. +#[derive(Clone, Debug)] +pub struct PufferfishPuff; +impl Goal for PufferfishPuff { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let area = m.bounds().inflate(Vec3::new(2.0, 2.0, 2.0)); + let player = cx.w.player.as_ref().is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); + // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. + let mob = cx.w.others.iter().any(|s| { + s.id != m.id && s.alive && !matches!(s.species, Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish | Species::Squid | Species::GlowSquid | Species::Dolphin | Species::Axolotl) && area.intersects(s.bounds) + }); + player || mob + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.extra.counter = 1; + m.extra.counter2 = 0; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.extra.counter = 0; + } +} +/// finalizeSpawn variants (tropical fish patterns and colours). +pub fn finalize(m: &mut Mob) { + if m.species() == Species::TropicalFish { + // TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour). + const COMMON: [(u8, u8, u8); 22] = [ + (7, 1, 7), (6, 7, 7), (6, 7, 11), (11, 0, 7), (1, 11, 7), (0, 1, 0), (5, 6, 3), (9, 10, 4), (11, 0, 14), (5, 0, 4), (8, 0, 7), + (11, 0, 1), (3, 9, 6), (4, 5, 3), (10, 14, 0), (2, 7, 14), (9, 14, 0), (6, 0, 4), (0, 14, 0), (1, 7, 0), (3, 9, 4), (6, 4, 4), + ]; + let (p, b, c) = if m.random.next_float() < 0.9 { + COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize] + } else { + (m.random.next_int_bound(12).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8) + }; + m.extra.variant = p; + m.extra.variant2 = b; + m.extra.variant3 = c; + } +} +/// Model animation for the water mobs. +pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + use Species as S; + let amp = if m.fluids.in_water { 1.0 } else { 1.5 }; + match m.species() { + S::Squid | S::GlowSquid => { + let angle = m.anim.lerp(TENTACLE_ANGLE, s.partial); + for i in 0..8 { + p.xrot(&format!("tentacle{i}"), angle); + } + } + S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()), + S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()), + S::Salmon => { + let (a, k) = if m.fluids.in_water { (1.0, 1.0) } else { (1.3, 1.7) }; + p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin()); + } + S::Pufferfish => { + let fin = 0.2 - 0.4 * (s.age * 0.2).sin(); + if p.has("right_blue_fin") { + p.zrot("right_blue_fin", -fin); + p.zrot("left_blue_fin", fin); + } else { + p.zrot("right_fin", -fin); + p.zrot("left_fin", fin); + } + } + S::Dolphin => { + p.xrot("body", s.x_rot.to_radians()); + p.yrot("body", s.y_rot.to_radians()); + let moving = m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z > 1.0e-7; + if moving { + p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).cos(); + p.xrot("tail", -0.1 * (s.age * 0.3).cos()); + p.xrot("tail_fin", -0.2 * (s.age * 0.3).cos()); + } + } + _ => {} + } +} +/// Renderer setupRotations for the water mobs (replacing or extending the default). +pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { + use Species as S; + let age = m.age as f32 + alpha; + match m.species() { + S::Squid | S::GlowSquid => { + let baby = m.is_baby(); + let x = m.anim.lerp(X_BODY_ROT, alpha); + let z = m.anim.lerp(Z_BODY_ROT, alpha); + Some( + glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { 0.25 } else { 0.5 }, 0.0)) + * glam::Mat4::from_rotation_y((180.0 - body).to_radians()) + * glam::Mat4::from_rotation_x(x.to_radians()) + * glam::Mat4::from_rotation_y(z.to_radians()) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { -0.6 } else { -1.2 }, 0.0)), + ) + } + S::Cod | S::Salmon | S::TropicalFish => { + let (a, k) = if m.species() == S::Salmon && !m.fluids.in_water { (1.3, 1.7) } else { (1.0, 1.0) }; + let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians()) * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians()); + if !m.fluids.in_water { + let off = if m.species() == S::Cod { glam::Vec3::new(0.1, 0.1, -0.1) } else { glam::Vec3::new(0.2, 0.1, 0.0) }; + t *= glam::Mat4::from_translation(off) * glam::Mat4::from_rotation_z(PI / 2.0); + } + Some(t) + } + S::Pufferfish => Some(glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0)) * glam::Mat4::from_rotation_y((180.0 - body).to_radians())), + _ => None, + } +} diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 974559e66..10c42f5c4 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -124,9 +124,9 @@ impl Mob { } /// 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(); + let attr_speed = self.movement_speed(); match self.ai.mov.kind { - MoveKind::Custom => {} + MoveKind::Custom => super::ai::custom_move_control(self), MoveKind::Ground => self.ground_move_tick(w, attr_speed), MoveKind::Flying { max_turn, hovers } => { let m = &mut self.ai.mov; diff --git a/crates/horizon-client/src/mobs/cube.rs b/crates/horizon-client/src/mobs/cube.rs new file mode 100644 index 000000000..6fef85290 --- /dev/null +++ b/crates/horizon-client/src/mobs/cube.rs @@ -0,0 +1,260 @@ +//! Slimes and magma cubes (`AbstractCubeMob`): sized bodies, hopping +//! movement (`CubeMobMoveControl`), random directions, contact damage, +//! squish animation and splitting. +use super::{ + Mob, MobEvent, MobWorld, Species, + anim::{Poses, State}, + control::{MoveKind, Operation, rotlerp}, + goals::{Cx, Goal, JUMP, LOOK, MOVE, NearestTarget, Prey, goal_clone, reduced}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +// AnimState slots. +const SQUISH: usize = 0; +const TARGET_SQUISH: usize = 1; + +pub fn register(m: &mut Mob) { + m.ai.goals.add(1, CubeFloat); + m.ai.goals.add(2, CubeAttack { tired: 0 }); + m.ai.goals.add(4, CubeRandomDirection { degrees: 0.0, next: 0 }); + m.ai.goals.add(5, CubeKeepJumping); + m.ai.targets.add(1, NearestTarget::new(Prey::Player, true).interval(10).when(|m, w| w.player.as_ref().is_some_and(|p| (p.position.y - m.position.y).abs() <= 4.0))); + m.ai.targets.add(3, NearestTarget::species(&[Species::IronGolem], true)); + m.ai.mov.kind = MoveKind::Custom; + m.ai.nav.can_float = true; + m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI); + set_size(m, 1); +} +/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size. +pub fn set_size(m: &mut Mob, size: i32) { + let size = size.clamp(1, 127); + m.extra.size = size; + m.attrs.max_health = (size * size) as f32; + m.attrs.speed = 0.2 + 0.1 * f64::from(size); + m.attrs.attack_damage = size as f32; + m.health = m.attrs.max_health; +} +/// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0). +pub fn finalize(m: &mut Mob) { + let scale = m.random.next_int_bound(3).unwrap_or(0); + set_size(m, 1 << scale); +} +fn tiny(m: &Mob) -> bool { + m.extra.size <= 1 +} +fn can_deal_damage(m: &Mob) -> bool { + m.species() == Species::MagmaCube || !tiny(m) +} +fn jump_delay(m: &mut Mob) -> i32 { + let base = m.random.next_int_bound(20).unwrap_or(0) + 10; + if m.species() == Species::MagmaCube { base * 4 } else { base } +} +fn sound_pitch(m: &mut Mob) -> f32 { + let adjust = if tiny(m) { 1.4 } else { 0.8 }; + ((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) * adjust +} +/// CubeMobMoveControl.tick +pub fn move_control(m: &mut Mob, events: &mut Vec) { + let want = m.extra.vector[0] as f32; + m.yaw = rotlerp(m.yaw, want, 90.0); + m.head_yaw = m.yaw; + m.body_yaw = m.yaw; + if m.ai.mov.operation != Operation::MoveTo { + m.ai.zza = 0.0; + return; + } + m.ai.mov.operation = Operation::Wait; + let speed = (m.ai.mov.speed_modifier * m.movement_speed()) as f32; + if m.on_ground { + m.set_speed(speed); + let delay = m.extra.counter; + m.extra.counter -= 1; + if delay <= 0 { + m.extra.counter = jump_delay(m); + if m.extra.flag { + m.extra.counter /= 3; + } + m.ai.jump = true; + let jump = match (m.species(), tiny(m)) { + (Species::MagmaCube, _) => "entity.magma_cube.jump", + (_, true) => "entity.slime.jump_small", + _ => "entity.slime.jump", + }; + let pitch = sound_pitch(m); + let vol = super::ai::sound_volume(m); + events.push(MobEvent::Sound(jump, m.center(), vol, pitch)); + } else { + m.ai.xxa = 0.0; + m.ai.zza = 0.0; + m.set_speed(0.0); + } + } else { + m.set_speed(speed); + } +} +fn set_direction(m: &mut Mob, y_rot: f32, aggressive: bool) { + m.extra.vector[0] = f64::from(y_rot); + m.extra.flag = aggressive; +} +fn set_wanted(m: &mut Mob, speed: f64) { + m.ai.mov.speed_modifier = speed; + m.ai.mov.operation = Operation::MoveTo; +} +/// AbstractCubeMob.jumpFromGround (and MagmaCube's size boost). +pub fn jump(m: &mut Mob) { + let boost = if m.species() == Species::MagmaCube { m.extra.size as f32 * 0.1 } else { 0.0 }; + m.velocity.y = f64::from(m.jump_power() + boost); +} +/// AbstractCubeMob.tick squish and landing sounds, plus contact damage. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let v = &mut m.anim.v; + v[SQUISH] += (v[TARGET_SQUISH] - v[SQUISH]) * 0.5; + let was = m.extra.flag2; + if m.on_ground && !was { + let squish = match (m.species(), tiny(m)) { + (Species::MagmaCube, true) => "entity.magma_cube.squish_small", + (Species::MagmaCube, false) => "entity.magma_cube.squish", + (_, true) => "entity.slime.squish_small", + _ => "entity.slime.squish", + }; + let pitch = ((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) / 0.8; + let vol = super::ai::sound_volume(m); + events.push(MobEvent::Sound(squish, m.center(), vol, pitch)); + m.anim.v[TARGET_SQUISH] = -0.5; + } else if !m.on_ground && was { + m.anim.v[TARGET_SQUISH] = 1.0; + } + m.extra.flag2 = m.on_ground; + m.anim.v[TARGET_SQUISH] *= if m.species() == Species::MagmaCube { 0.9 } else { 0.6 }; + // playerTouch -> dealDamage + if can_deal_damage(m) + && m.alive() + && let Some(p) = &w.player + && p.alive + && !p.creative + && m.bounds().intersects(p.bounds) + { + let reach = 2.04f32.sqrt() as f64 - 0.6; + if m.bounds().inflate(Vec3::new(reach, 0.0, reach)).intersects(p.bounds) { + let damage = m.attrs.attack_damage + if m.species() == Species::MagmaCube { 2.0 } else { 0.0 }; + events.push(MobEvent::AttackPlayer(damage, [m.position.x, m.position.y, m.position.z])); + if m.species() == Species::Slime { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + events.push(MobEvent::Sound("entity.slime.attack", m.center(), 1.0, pitch)); + } + } + } +} +/// MagmaCubeModel.setupAnim (slimes have no animation). +pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + if m.species() == Species::MagmaCube { + let squish = m.anim.lerp(SQUISH, s.partial).max(0.0); + for i in 0..8 { + p.get(&format!("cube{i}"))[1] = -((4 - i) as f32) * squish * 1.7; + } + } +} +/// AbstractCubeMobRenderer.scale: size with squash and stretch. +pub fn scale(m: &Mob, alpha: f32) -> glam::Mat4 { + let size = m.extra.size.max(1) as f32; + let squish = m.anim.lerp(SQUISH, alpha) / (size * 0.5 + 1.0); + let w = 1.0 / (squish + 1.0); + let mut t = glam::Mat4::IDENTITY; + if m.species() == Species::Slime { + t = glam::Mat4::from_scale(glam::Vec3::splat(0.999)) * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.001, 0.0)); + } + t * glam::Mat4::from_scale(glam::Vec3::new(w * size, 1.0 / w * size, w * size)) +} +/// CubeMobFloatGoal +#[derive(Clone, Debug)] +struct CubeFloat; +impl Goal for CubeFloat { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.is_in_liquid() + } + 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; + } + set_wanted(m, 1.2); + } +} +/// CubeMobAttackGoal: face the target and hop at it for up to 300 ticks. +#[derive(Clone, Debug)] +struct CubeAttack { + tired: i32, +} +impl Goal for CubeAttack { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.target_info(cx.w).is_some_and(|t| t.alive && !(t.is_player && t.creative)) + } + fn start(&mut self, _: &mut Mob, _: &mut Cx) { + self.tired = reduced(300); + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.target_info(cx.w).is_some_and(|t| t.alive && !(t.is_player && t.creative)) { + return false; + } + self.tired -= 1; + self.tired > 0 + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(t) = m.target_info(cx.w) { + m.turn_to([t.position.x, t.eye_y, t.position.z], 10.0, 10.0); + } + let (yaw, aggressive) = (m.yaw, can_deal_damage(m)); + set_direction(m, yaw, aggressive); + } +} +/// CubeMobRandomDirectionGoal +#[derive(Clone, Debug)] +struct CubeRandomDirection { + degrees: f32, + next: i32, +} +impl Goal for CubeRandomDirection { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.ai.target.is_none() && (m.on_ground || m.is_in_liquid() || m.has_effect("minecraft:levitation")) + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + self.next -= 1; + if self.next <= 0 { + self.next = reduced(40 + m.random.next_int_bound(60).unwrap_or(0)); + self.degrees = m.random.next_int_bound(360).unwrap_or(0) as f32; + } + set_direction(m, self.degrees, false); + } +} +/// CubeMobKeepOnJumpingGoal +#[derive(Clone, Debug)] +struct CubeKeepJumping; +impl Goal for CubeKeepJumping { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + set_wanted(m, 1.0); + } +} diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs new file mode 100644 index 000000000..7f7a2ae81 --- /dev/null +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -0,0 +1,306 @@ +//! Endermen: anger from being stared at, teleporting (randomly in daylight, +//! when hit by projectiles or water, and towards a distant target), freezing +//! while looked at, and picking up / placing `enderman_holdable` blocks. +use super::{ + Damage, Mob, MobEvent, MobWorld, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float, Goal, HurtByTarget, JUMP, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, Stroll, TARGET, goal_clone, reduced}, +}; +use crate::blocks::Fluid; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, FreezeWhenLookedAt); + g.add(2, MeleeAttack::new(1.0, false)); + let mut stroll = Stroll::avoiding_water(1.0); + stroll.water_avoiding = Some(0.0); + g.add(7, stroll); + g.add(8, LookAtPlayer::new(8.0)); + g.add(8, RandomLookAround::default()); + g.add(10, LeaveBlock); + g.add(11, TakeBlock); + m.ai.targets.add(1, LookForPlayer { pending: false, aggro: 0, teleport: 0 }); + m.ai.targets.add(2, HurtByTarget::new()); + m.ai.targets.add(3, NearestTarget::species(&[Species::Endermite], true).reach()); + m.set_malus(super::path::PathType::Water, -1.0); +} +/// Enderman.isBeingStaredBy: the player's look within a cone of 0.025 / distance +/// of the eyes, with line of sight, and no carved pumpkin. +pub fn stared_at(m: &Mob, w: &MobWorld) -> bool { + let Some(p) = &w.player else { return false }; + if !p.alive || p.head.as_deref() == Some("minecraft:carved_pumpkin") { + return false; + } + let look = p.look; + let dir = [m.position.x - p.position.x, m.eye_y() - p.eye[1], m.position.z - p.position.z]; + let dist = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt(); + if dist < 1.0e-6 { + return false; + } + let dot = (look[0] * dir[0] + look[1] * dir[1] + look[2] * dir[2]) / dist; + dot > 1.0 - 0.025 / dist && w.line_of_sight(Vec3::new(p.eye[0], p.eye[1], p.eye[2]), Vec3::new(m.position.x, m.eye_y(), m.position.z)) +} +/// Enderman.teleport(x, y, z): drop to standing ground, require free space without liquid. +pub fn teleport_to(m: &mut Mob, w: &MobWorld, x: f64, y: f64, z: f64, events: &mut Vec) -> bool { + let (bx, bz) = (x.floor() as i32, z.floor() as i32); + if !w.world.loaded(bx, bz) { + return false; + } + let mut by = y.floor() as i32; + while by > crate::chunk::MIN_Y && !w.facts.get(w.world.block(bx, by, bz)).full_collision { + by -= 1; + } + let ground = w.facts.get(w.world.block(bx, by, bz)); + if !ground.full_collision || ground.fluid == Fluid::Water { + return false; + } + let ny = f64::from(by + 1); + let half = f64::from(m.width()) / 2.0; + let b = Aabb::new(Vec3::new(x - half, ny, z - half), Vec3::new(x + half, ny + f64::from(m.height()), z + half)); + if !w.no_collision(b) || w.fluids(b, ny + m.eye_height()).in_water || w.fluids(b, ny).in_lava { + return false; + } + let old = m.center(); + m.position = Vec3::new(x, ny, z); + m.previous = m.position; + m.velocity = Vec3::ZERO; + m.ai.nav.stop(); + events.push(MobEvent::Sound("entity.enderman.teleport", old, 1.0, 1.0)); + events.push(MobEvent::Sound("entity.enderman.teleport", m.center(), 1.0, 1.0)); + true +} +pub fn teleport_random(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { + if !m.alive() { + return false; + } + let x = m.position.x + (m.random.next_double() - 0.5) * 64.0; + let y = m.position.y + f64::from(m.random.next_int_bound(64).unwrap_or(32) - 32); + let z = m.position.z + (m.random.next_double() - 0.5) * 64.0; + teleport_to(m, w, x, y, z, events) +} +fn teleport_towards(m: &mut Mob, w: &MobWorld, at: Vec3, eye_y: f64, events: &mut Vec) -> bool { + let mut d = [m.position.x - at.x, m.position.y + f64::from(m.height()) * 0.5 - eye_y, m.position.z - at.z]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1.0e-9); + d = d.map(|c| c / len); + let x = m.position.x + (m.random.next_double() - 0.5) * 8.0 - d[0] * 16.0; + let y = m.position.y + f64::from(m.random.next_int_bound(16).unwrap_or(8) - 8) - d[1] * 16.0; + let z = m.position.z + (m.random.next_double() - 0.5) * 8.0 - d[2] * 16.0; + teleport_to(m, w, x, y, z, events) +} +/// Enderman.customServerAiStep: in daylight, flee by teleporting. +pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { + if cx.w.daylight && m.age as i32 >= m.extra.counter + 600 { + let br = super::hostile::mob_brightness(m, cx.w); + let (x, y, z) = (m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32); + if br > 0.5 && cx.w.can_see_sky(x, y, z) && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 { + m.ai.target = None; + teleport_random(m, cx.w, cx.events); + } + } + // Being angry (target set) makes the head "creepy" (render). + m.extra.flag = m.ai.target.is_some(); +} +/// Enderman.hurtServer: projectiles miss (teleport away), others may teleport. +pub fn on_damage(m: &mut Mob, source: &Damage) -> bool { + if source.is_projectile() { + // repeatedlyTryToTeleport is applied by the next AI step. + m.extra.counter2 = 64; + return false; + } + true +} +pub fn after_hurt(m: &mut Mob, source: &Damage) { + if source.attacker.is_none() && m.random.next_int_bound(10).unwrap_or(0) != 0 { + m.extra.counter2 = 1; + } +} +/// Pending teleports (repeatedlyTryToTeleport: up to 64 tries). +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + // Enderman.aiStep: never jumps. + m.ai.jumping = false; + if m.extra.counter2 > 0 { + let tries = m.extra.counter2; + m.extra.counter2 = 0; + for _ in 0..tries { + if teleport_random(m, w, events) { + break; + } + } + } + if (m.fluids.in_water || w.raining && w.can_see_sky(m.position.x.floor() as i32, m.eye_y().floor() as i32, m.position.z.floor() as i32)) && m.alive() { + // Hurt by water: teleport away. + m.extra.counter2 = m.extra.counter2.max(1); + } +} +/// EndermanModel.setupAnim: half-speed clamped limbs, held-block arms, creepy head. +pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + super::anim::humanoid_pub(p, s, m); + for part in ["right_arm", "left_arm", "right_leg", "left_leg"] { + let x = p.get(part)[3] * 0.5; + p.xrot(part, x.clamp(-0.4, 0.4)); + } + if m.extra.carried.is_some() { + p.xrot("right_arm", -0.5); + p.xrot("left_arm", -0.5); + p.zrot("right_arm", 0.05); + p.zrot("left_arm", -0.05); + } + if m.extra.flag { + p.get("head")[1] -= 5.0; + p.get("hat")[1] += 5.0; + } +} +/// EndermanFreezeWhenLookedAt +#[derive(Clone, Debug)] +struct FreezeWhenLookedAt; +impl Goal for FreezeWhenLookedAt { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.ai.target != Some(Who::Player) { + return false; + } + let Some(p) = &cx.w.player else { return false }; + m.distance_sqr(p.position) <= 256.0 && stared_at(m, cx.w) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(p) = &cx.w.player { + let at = [p.position.x, p.eye[1], p.position.z]; + m.look_at(at); + } + } +} +/// EndermanLookForPlayerGoal: anger after being stared at for 5 ticks, +/// teleport away when stared at close up, or towards a far target. +#[derive(Clone, Debug)] +struct LookForPlayer { + pending: bool, + aggro: i32, + teleport: i32, +} +impl Goal for LookForPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = &cx.w.player else { return false }; + self.pending = p.alive && !p.creative && m.distance_sqr(p.position) <= m.attrs.follow_range.powi(2) && stared_at(m, cx.w); + self.pending + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.aggro = reduced(5); + self.teleport = 0; + // setBeingStaredAt: play the stare sound. + m.extra.counter = m.age as i32; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + self.pending = false; + m.ai.target = None; + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = cx.w.player.clone() else { return false }; + if self.pending { + if !stared_at(m, cx.w) { + return false; + } + m.turn_to(p.eye, 10.0, 10.0); + return true; + } + p.alive && !p.creative && m.ai.target == Some(Who::Player) && m.distance_sqr(p.position) <= m.attrs.follow_range.powi(2) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + if self.pending { + self.aggro -= 1; + if self.aggro <= 0 { + self.pending = false; + m.ai.target = Some(Who::Player); + cx.events.push(MobEvent::Sound("entity.enderman.stare", m.center(), 2.5, 1.0)); + } + } else if m.ai.target == Some(Who::Player) { + if stared_at(m, cx.w) { + if m.distance_sqr(p.position) < 16.0 { + teleport_random(m, cx.w, cx.events); + } + self.teleport = 0; + } else { + let far = m.distance_sqr(p.position) > 256.0; + let t = self.teleport; + if far { + self.teleport += 1; + } + if far && t >= reduced(30) && teleport_towards(m, cx.w, p.position, p.eye[1], cx.events) { + self.teleport = 0; + } + } + } + } +} +/// EndermanTakeBlockGoal +#[derive(Clone, Debug)] +struct TakeBlock; +impl Goal for TakeBlock { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.carried.is_none() && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0 + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let x = (m.position.x - 2.0 + m.random.next_double() * 4.0).floor() as i32; + let y = (m.position.y + m.random.next_double() * 3.0).floor() as i32; + let z = (m.position.z - 2.0 + m.random.next_double() * 4.0).floor() as i32; + let state = cx.w.world.block(x, y, z); + let name = cx.w.facts.get(state).name.to_string(); + if !cx.w.has_tag("minecraft:enderman_holdable", &name) { + return; + } + // Reachable: the clip from the mob's column hits this block first. + let from = Vec3::new(m.position.x.floor() + 0.5, f64::from(y) + 0.5, m.position.z.floor() + 0.5); + let to = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5); + let dx = (x - m.position.x.floor() as i32).abs() + (z - m.position.z.floor() as i32).abs(); + if dx > 0 && !cx.w.clear_between(from, Vec3::new(to.x - (to.x - from.x) * 0.3, to.y, to.z - (to.z - from.z) * 0.3), false) { + return; + } + cx.events.push(MobEvent::SetBlock { pos: [x, y, z], state: cx.w.world.air }); + m.extra.carried = Some(state); + } +} +/// EndermanLeaveBlockGoal +#[derive(Clone, Debug)] +struct LeaveBlock; +impl Goal for LeaveBlock { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.carried.is_some() && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0 + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(carried) = m.extra.carried else { return }; + let x = (m.position.x - 1.0 + m.random.next_double() * 2.0).floor() as i32; + let y = (m.position.y + m.random.next_double() * 2.0).floor() as i32; + let z = (m.position.z - 1.0 + m.random.next_double() * 2.0).floor() as i32; + let target = cx.w.world.block(x, y, z); + let below = cx.w.world.block(x, y - 1, z); + let bf = cx.w.facts.get(below); + let free = !cx.w.others.iter().any(|s| s.bounds.intersects(Aabb::new(Vec3::new(f64::from(x), f64::from(y), f64::from(z)), Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1))))); + if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" && bf.full_collision && free { + cx.events.push(MobEvent::SetBlock { pos: [x, y, z], state: carried }); + m.extra.carried = None; + } + } +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index fdb4a2387..c030ecd87 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -530,6 +530,8 @@ pub struct Stroll { pub check_no_action: bool, /// WaterAvoidingRandomStrollGoal probability of a plain stroll. pub water_avoiding: Option, + /// RandomSwimmingGoal: BehaviorUtils.getRandomSwimmablePos. + pub swim: bool, pub force: bool, wanted: [f64; 3], } @@ -540,6 +542,7 @@ impl Stroll { interval: 120, check_no_action: true, water_avoiding: None, + swim: false, force: false, wanted: [0.0; 3], } @@ -554,6 +557,10 @@ impl Stroll { self.interval = i; self } + /// RandomSwimmingGoal(speed, interval) + pub fn swimming(speed: f64, interval: i32) -> Self { + Self { swim: true, ..Self::new(speed).interval(interval) } + } } impl Goal for Stroll { goal_clone!(); @@ -580,6 +587,19 @@ impl Goal for Stroll { m.default_random_pos(cx.w, 10, 7) } } + None if self.swim => { + let mut p = m.default_random_pos(cx.w, 10, 7); + let mut count = 0; + while let Some(q) = p { + let s = cx.w.world.block(q[0].floor() as i32, q[1].floor() as i32, q[2].floor() as i32); + if cx.w.data.state(s).flags & super::data::WATER != 0 || count >= 10 { + break; + } + count += 1; + p = m.default_random_pos(cx.w, 10, 7); + } + p + } None => m.default_random_pos(cx.w, 10, 7), }; let Some(p) = pos else { return false }; @@ -934,7 +954,7 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m if !t.alive || t.is_player && t.creative { return false; } - if m.distance_sqr(t.position) > m.kind.follow_range * m.kind.follow_range { + if m.distance_sqr(t.position) > m.attrs.follow_range * m.attrs.follow_range { return false; } if must_see { @@ -980,7 +1000,7 @@ impl Goal for NearestTarget { { return false; } - let range = m.kind.follow_range; + let range = m.attrs.follow_range; self.found = None; match &self.prey { Prey::Player => { @@ -1113,7 +1133,7 @@ impl Goal for HurtByTarget { if self.alert && let Some(by) = m.ai.target { - let range = m.kind.follow_range; + let range = m.attrs.follow_range; let species = m.species(); let id = m.id; let pos = m.position; @@ -1636,3 +1656,78 @@ impl Goal for EatBlock { } } } + +/// BreathAirGoal: swim up to air when the air supply runs low. +#[derive(Clone, Debug, Default)] +pub struct BreathAir; +impl BreathAir { + fn find_air(m: &mut Mob, cx: &mut Cx) { + let (x, y, z) = (m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32); + let mut dest = None; + for yy in y..=y + 8 { + let s = cx.w.world.block(x, yy, z); + let f = cx.w.facts.get(s); + if (f.fluid == crate::blocks::Fluid::None || &*f.name == "minecraft:bubble_column") && cx.w.data.state(s).flags & super::data::LAND != 0 { + dest = Some([x, yy, z]); + break; + } + } + let d = dest.unwrap_or([x, (m.position.y + 8.0).floor() as i32, z]); + m.nav_move_to(cx.w, [f64::from(d[0]), f64::from(d[1] + 1), f64::from(d[2])], 1.0); + } +} +impl Goal for BreathAir { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.air < 140 + } + fn interruptable(&self) -> bool { + false + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.nav_stop(); + Self::find_air(m, cx); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + Self::find_air(m, cx); + let input = Vec3::new(f64::from(m.ai.xxa), f64::from(m.ai.yya), f64::from(m.ai.zza)); + m.move_relative(0.02, input); + let mut ev = Vec::new(); + m.do_move(cx.w, &mut ev); + cx.events.extend(ev); + } +} +/// TryFindLiquidGoal (water): head for nearby water when stranded on land. +#[derive(Clone, Debug, Default)] +pub struct TryFindWater { + wanted: [f64; 3], +} +impl Goal for TryFindWater { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.on_ground || 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]), f64::from(p[1]), f64::from(p[2])]; + 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/living.rs b/crates/horizon-client/src/mobs/living.rs index 20af8ba26..31357b90b 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -99,7 +99,10 @@ impl Mob { super::species::Baby::None => {} } } - if self.extra.size > 0 { + if self.kind.species == super::Species::Pufferfish { + let s = super::aquatic::puff_scale(self.extra.size); + (w, h, e) = (w * s, h * s, e * s); + } else if self.extra.size > 0 { let s = f64::from(self.extra.size); (w, h, e) = (w * s, h * s, e * s); } diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index d2b318ff4..6dc6986a0 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -134,7 +134,7 @@ impl Mob { if self.ai.target.is_none() { return 3; } - let mut sacrifice = (self.health - self.kind.max_health * 0.33) as i32; + let mut sacrifice = (self.health - self.attrs.max_health * 0.33) as i32; sacrifice -= (3 - 2) * 4; sacrifice.max(0) + 3 } @@ -145,7 +145,7 @@ impl Mob { 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) + (self.attrs.follow_range as f32).max(self.ai.nav.required_path_length) } fn can_update_path(&self) -> bool { match self.ai.nav.kind { @@ -237,7 +237,7 @@ impl Mob { return Some(path.clone()); } let pm = self.path_mob(); - let max_visited = ((self.kind.follow_range * 16.0).floor() as f32 + let max_visited = ((self.attrs.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); diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index ae3859835..45c1f4406 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -193,9 +193,34 @@ pub fn body(m: &Mob) -> (String, String) { "entity/strider/strider" }), ), + S::Squid => (baby_or(m, "squid#main", "squid_baby#main"), b("entity/squid/squid")), + S::GlowSquid => (baby_or(m, "glow_squid#main", "glow_squid_baby#main"), b("entity/squid/glow_squid")), + S::Dolphin => (baby_or(m, "dolphin#main", "dolphin_baby#main"), b("entity/dolphin/dolphin")), + S::Pufferfish => { + let model = match m.extra.size { + 0 => "pufferfish_small#main", + 1 => "pufferfish_medium#main", + _ => "pufferfish_big#main", + }; + (model.into(), "entity/fish/pufferfish".into()) + } + S::TropicalFish => { + if m.extra.variant < 6 { + ("tropical_fish_small#main".into(), "entity/fish/tropical_a".into()) + } else { + ("tropical_fish_large#main".into(), "entity/fish/tropical_b".into()) + } + } _ => (m.kind.model_key(), m.kind.texture.clone()), } } +/// LivingEntityRenderer.getModelTint (tropical fish base colour). +pub fn body_color(m: &Mob) -> u32 { + match m.species() { + Species::TropicalFish => abgr(DYE[m.extra.variant2 as usize & 15]), + _ => 0xFFFF_FFFF, + } +} /// Extra render layers drawn over the body with the same pose. pub fn layers(m: &Mob) -> Vec { use Species as S; @@ -294,6 +319,11 @@ pub fn layers(m: &Mob) -> Vec { false, ), S::Creeper if m.extra.charged => {} + S::TropicalFish => { + // TropicalFishPatternLayer: the pattern tinted with the pattern colour. + let (model, letter, n) = if m.extra.variant < 6 { ("tropical_fish_small#pattern", "a", m.extra.variant + 1) } else { ("tropical_fish_large#pattern", "b", m.extra.variant - 5) }; + push(&mut v, model, &format!("entity/fish/tropical_{letter}_pattern_{n}"), abgr(DYE[m.extra.variant3 as usize & 15]), false); + } S::Villager | S::ZombieVillager => { let base = if m.species() == S::Villager { "villager" @@ -364,8 +394,9 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { 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()); + let rotation = super::aquatic::rotations(m, alpha, body) + .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())); + let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation; if m.death_time > 0 { let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) .sqrt() @@ -466,11 +497,12 @@ pub fn render( .layer(&model_key) .cloned() .unwrap_or_else(|| m.kind.model.clone()); + let mut poses = Poses::new(&model); + anim::setup(m, &s, &mut poses, &data.animations); 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); + draw(&model, base, &poses, uv, body_color(m), light, overlay, out); } + held_items(m, &model, base, &poses, atlas, light, out); for layer in layers(m) { let Some(part) = m.kind.layer(&layer.model).cloned() else { continue; @@ -505,3 +537,86 @@ pub fn render_single( anim::setup(m, &s, &mut poses, &std::collections::HashMap::new()); draw(&model, base, &poses, uv, 0xFFFF_FFFF, light, overlay, out); } + +/// The transform of a named part (ModelPart.translateAndRotate down the tree). +pub fn part_matrix(part: &Part, parent: glam::Mat4, poses: &Poses, name: &str, x_offset: f32) -> Option { + let mut p = poses.pose(part); + if part.name == name { + p[0] += x_offset; + } + let m = parent + * 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 part.name == name { + return Some(m); + } + part.children.iter().find_map(|c| part_matrix(c, m, poses, name, x_offset)) +} +/// ItemModel thirdperson_righthand display transform by item model parent. +fn item_display(item: &str) -> ([f32; 3], [f32; 3], [f32; 3]) { + let name = item.trim_start_matches("minecraft:"); + if name == "bow" { + ([-80.0, 260.0, -40.0], [-1.0, -2.0, 2.5], [0.9; 3]) + } else if name == "crossbow" { + ([-90.0, 0.0, -60.0], [2.0, 0.1, -3.0], [0.9; 3]) + } else if name == "fishing_rod" || name == "carrot_on_a_stick" || name == "warped_fungus_on_a_stick" { + ([0.0, 90.0, 55.0], [0.0, 4.0, 2.5], [0.85; 3]) + } else if ["_sword", "_axe", "_pickaxe", "_shovel", "_hoe", "trident", "mace", "stick", "bone", "blaze_rod"].iter().any(|t| name.ends_with(t)) { + ([0.0, -90.0, 55.0], [0.0, 4.0, 0.5], [0.85; 3]) + } else { + ([0.0, 0.0, 0.0], [0.0, 3.0, 1.0], [0.55; 3]) + } +} +/// The sprite drawn for a held item (bow pull frames while charging). +fn item_sprite(m: &Mob, item: &str) -> String { + let name = item.trim_start_matches("minecraft:"); + if name == "bow" && m.extra.using_item > 0 { + let pull = m.extra.using_item as f32 * 0.05; + let frame = if pull >= 0.9 { 2 } else if pull >= 0.65 { 1 } else { 0 }; + return format!("item/bow_pulling_{frame}"); + } + if name == "crossbow" && m.extra.flag2 { + return "item/crossbow_arrow".into(); + } + format!("item/{name}") +} +/// ItemInHandLayer: items in the mob's hands. +fn held_items(m: &Mob, model: &Part, base: glam::Mat4, poses: &Poses, atlas: Atlas, light: u32, out: &mut Vec) { + let skeleton = matches!(m.species(), Species::Skeleton | Species::Stray | Species::Bogged | Species::WitherSkeleton); + for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] { + let Some(item) = item else { continue }; + let arm = if left { "left_arm" } else { "right_arm" }; + let offset = if skeleton { if left { -1.0 } else { 1.0 } } else { 0.0 }; + let Some(mut t) = part_matrix(model, base, poses, arm, offset) else { continue }; + let Some(uv) = atlas(&item_sprite(m, item)) else { continue }; + let baby = m.is_baby(); + let (ox, oy, oz) = if baby { (0.0, 1.0, -4.5) } else { (1.0, 2.0, -10.0) }; + t *= glam::Mat4::from_rotation_x((-90.0f32).to_radians()) * glam::Mat4::from_rotation_y(PI); + t *= glam::Mat4::from_translation(glam::Vec3::new(if left { -ox } else { ox } / 16.0, oy / 16.0, oz / 16.0)); + // ItemTransform.apply (mirrored for the left hand). + let (rot, tr, sc) = item_display(item); + let (ry, rz, tx) = if left { (-rot[1], -rot[2], -tr[0]) } else { (rot[1], rot[2], tr[0]) }; + t *= glam::Mat4::from_translation(glam::Vec3::new(tx, tr[1], tr[2]) / 16.0); + t *= glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, rot[0].to_radians(), ry.to_radians(), rz.to_radians())); + t *= glam::Mat4::from_scale(glam::Vec3::from(sc)); + t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); + draw_item_plane(t, uv, light, out); + } +} +/// A generated item model: the sprite on two faces 1/16 apart. +pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec) { + let (u0, v0, u1, v1) = (uv[0], uv[1], uv[2], uv[3]); + let south = 8.5 / 16.0; + let north = 7.5 / 16.0; + let quads = [ + [([0.0, 0.0, south], [u0, v1]), ([1.0, 0.0, south], [u1, v1]), ([1.0, 1.0, south], [u1, v0]), ([0.0, 1.0, south], [u0, v0])], + [([1.0, 0.0, north], [u1, v1]), ([0.0, 0.0, north], [u0, v1]), ([0.0, 1.0, north], [u0, v0]), ([1.0, 1.0, north], [u1, v0])], + ]; + for q in quads { + for (p, uv) in q { + let pos = t.transform_point3(glam::Vec3::from(p)); + out.push(Vertex { pos: pos.to_array(), uv, layer: 0, color: 0xFFFF_FFFF, light }); + } + } +} diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index f6f3be965..765bfb038 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -124,17 +124,11 @@ pub fn spawn_rules_ok( // 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 + // GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water. + S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water", + S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => { + // WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level. + (50..=63).contains(&y) && w.fluid(x, y - 1, z) == Fluid::Water && w.block_name(x, y + 1, z) == "minecraft:water" } S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay", S::Strider => w.fluid(x, y, z) == Fluid::Lava, @@ -204,6 +198,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts) { S::Villager => { m.extra.variant = villager_type(biome); } + S::TropicalFish => super::aquatic::finalize(m), _ => {} } } diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs new file mode 100644 index 000000000..eee488303 --- /dev/null +++ b/crates/horizon-client/src/mobs/witch.rs @@ -0,0 +1,177 @@ +//! Witches (potion drinking and splash potion attacks) and the shared +//! `RangedAttackGoal` (also used by snow golems). +use super::{ + Mob, MobEvent, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, Stroll, goal_clone}, +}; +use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(1, Float); + g.add(2, RangedAttack::new(1.0, 60, 60, 10.0, witch_attack)); + g.add(2, Stroll::avoiding_water(1.0)); + g.add(3, LookAtPlayer::new(8.0)); + g.add(3, RandomLookAround::default()); + m.ai.targets.add(1, HurtByTarget::new()); + m.ai.targets.add(3, NearestTarget::player(true).interval(10)); +} +/// The callback a ranged mob uses to fire (`RangedAttackMob.performRangedAttack`). +pub type Fire = fn(&mut Mob, Who, f32, &mut Cx); + +/// RangedAttackGoal(speed, intervalMin, intervalMax, radius). +#[derive(Clone, Debug)] +pub struct RangedAttack { + speed: f64, + min: i32, + max: i32, + radius: f32, + fire: Fire, + attack_time: i32, + see_time: i32, +} +impl RangedAttack { + pub fn new(speed: f64, min: i32, max: i32, radius: f32, fire: Fire) -> Self { + Self { speed, min, max, radius, fire, attack_time: -1, see_time: 0 } + } +} +impl Goal for RangedAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.target_info(cx.w).is_some_and(|t| t.alive) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_use(m, cx) || m.target_info(cx.w).is_some_and(|t| t.alive) && !m.ai.nav.is_done() + } + fn stop(&mut self, _: &mut Mob, _: &mut Cx) { + self.see_time = 0; + self.attack_time = -1; + } + 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 d2 = m.distance_sqr(t.position); + let sees = m.sees(cx.w, who); + if sees { + self.see_time += 1; + } else { + self.see_time = 0; + } + if d2 <= f64::from(self.radius * self.radius) && self.see_time >= 5 { + m.nav_stop(); + } else { + m.nav_move_to_entity(cx.w, [t.position.x, t.position.y, t.position.z], 1, self.speed); + } + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 30.0, 30.0); + self.attack_time -= 1; + if self.attack_time == 0 { + if !sees { + return; + } + let dist = (d2.sqrt() as f32) / self.radius; + let power = dist.clamp(0.1, 1.0); + (self.fire)(m, who, power, cx); + self.attack_time = (dist * (self.max - self.min) as f32 + self.min as f32).floor() as i32; + } else if self.attack_time < 0 { + let f = d2.sqrt() / f64::from(self.radius); + self.attack_time = (f64::from(self.min) + f * f64::from(self.max - self.min)).floor() as i32; + } + } +} +/// Witch.performRangedAttack: harming by default, slowness at range, poison +/// on healthy targets, weakness up close. +fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { + if m.extra.using_item > 0 { + return; + } + let Some(t) = cx.w.target_info(who) else { return }; + let xd = t.position.x - m.position.x; + let yd = t.eye_y - 1.1 - m.position.y; + let zd = t.position.z - m.position.z; + let dist = (xd * xd + zd * zd).sqrt(); + let health = if t.is_player { 20.0 } else { cx.w.seen(match who { Who::Mob(id) => id, Who::Player => 0 }).map_or(20.0, |s| s.health) }; + let (effect, ticks, amplifier) = if dist >= 8.0 { + ("minecraft:slowness", 1800, 0) + } else if health >= 8.0 { + ("minecraft:poison", 900, 0) + } else if dist <= 3.0 && m.random.next_float() < 0.25 { + ("minecraft:weakness", 1800, 0) + } else { + ("minecraft:instant_damage", 1, 0) + }; + let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z); + let mut p = Projectile::new(ProjectileKind::Potion { effect, ticks, amplifier, color: 0 }, start, Some(Who::Mob(m.id))); + // Splash potions throw with gravity 0.05. + p.shoot(&mut m.random, [xd, yd + dist * 0.2, zd], if dist <= 2.0 { 0.45 } else { 0.75 }, 8.0); + cx.events.push(MobEvent::Projectile(p)); + let pitch = 0.8 + m.random.next_float() * 0.4; + cx.events.push(MobEvent::Sound("entity.witch.throw", m.center(), 1.0, pitch)); +} +/// Witch.aiStep: drink water breathing, fire resistance, healing or swiftness. +pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { + if !m.alive() { + return; + } + if m.extra.using_item > 0 { + m.extra.using_item -= 1; + if m.extra.using_item <= 0 { + m.extra.using_item = 0; + if let Some(potion) = m.extra.main_hand.take() { + match potion.as_ref() { + "minecraft:water_breathing" => m.add_effect("minecraft:water_breathing", 3600, 0), + "minecraft:fire_resistance" => m.add_effect("minecraft:fire_resistance", 3600, 0), + "minecraft:healing" => m.health = (m.health + 4.0).min(m.attrs.max_health), + "minecraft:swiftness" => m.add_effect("minecraft:speed", 3600, 0), + _ => {} + } + } + m.extra.flag = false; + } + return; + } + let potion = if m.random.next_float() < 0.15 && m.fluids.eye_in_water && !m.has_effect("minecraft:water_breathing") { + Some("minecraft:water_breathing") + } else if m.random.next_float() < 0.15 && (m.fire_ticks > 0 || m.last_damage.is_some_and(|(d, _)| d.is_fire())) && !m.has_effect("minecraft:fire_resistance") { + Some("minecraft:fire_resistance") + } else if m.random.next_float() < 0.05 && m.health < m.attrs.max_health { + Some("minecraft:healing") + } else if m.random.next_float() < 0.5 && m.ai.target.is_some() && !m.has_effect("minecraft:speed") && target_far { + Some("minecraft:swiftness") + } else { + None + }; + if let Some(p) = potion { + m.extra.main_hand = Some(p.into()); + // PotionItem use duration 32 ticks. + m.extra.using_item = 32; + m.extra.flag = true; + let pitch = 0.8 + m.random.next_float() * 0.4; + cx_events.push(MobEvent::Sound("entity.witch.drink", m.center(), 1.0, pitch)); + } +} +/// WitchModel.setupAnim (VillagerModel base with a wobbling nose). +pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + p.yrot("head", s.y_rot.to_radians()); + p.xrot("head", s.x_rot.to_radians()); + p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5); + p.xrot("left_leg", (s.pos * 0.6662 + std::f32::consts::PI).cos() * 1.4 * s.speed * 0.5); + let speed = 0.01 * (m.id % 10) as f32; + p.xrot("nose", (s.age * speed).sin() * 4.5 * std::f32::consts::PI / 180.0); + p.zrot("nose", (s.age * speed).cos() * 2.5 * std::f32::consts::PI / 180.0); + if m.extra.main_hand.is_some() { + let n = p.get("nose"); + n[0] = 0.0; + n[1] = 1.0; + n[2] = -1.5; + n[3] = -0.9; + } + let _ = Species::Witch; +}