From a77c929d81773fe133897e76d79010fd37a7670c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:24:12 +0200 Subject: [PATCH] Add breezes and wind charges Breeze: chooses the nearest player or iron golem (or whoever hurt it), long jumps behind its target after inhaling, shoots a wind charge, slides to new spots and shoots again when stuck, with the vanilla timers, poses, keyframe animations, wind and eyes layers, sounds and block dust at its feet; arrows and other projectiles bounce off it. Wind charges: the item a player throws (half a second between throws), the charge a breeze shoots, and their burst, which does no damage but knocks players, mobs, projectiles and primed TNT away, cancels the thrower's fall, opens wooden doors, trapdoors and gates, presses buttons, flips levers, rings bells and snuffs candles; gust particles for the burst. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/breezes.rs | 65 ++ crates/horizon-client/src/game/creatures.rs | 61 +- crates/horizon-client/src/game/explosion.rs | 2 +- crates/horizon-client/src/game/wind.rs | 503 +++++++++++++ crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 9 + crates/horizon-client/src/mobs/anim.rs | 2 + crates/horizon-client/src/mobs/breeze.rs | 785 ++++++++++++++++++++ crates/horizon-client/src/mobs/living.rs | 9 + crates/horizon-client/src/mobs/render.rs | 18 + crates/horizon-client/src/mobs/species.rs | 17 + crates/horizon-client/src/particles.rs | 67 +- crates/horizon-client/src/projectiles.rs | 7 + 14 files changed, 1547 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/breezes.rs create mode 100644 crates/horizon-client/src/game/wind.rs create mode 100644 crates/horizon-client/src/mobs/breeze.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 065433937..e7b3bc807 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8,6 +8,7 @@ mod beacon; mod blockctl; mod boats; mod books; +mod breezes; mod cartography; mod chat; mod combat; @@ -62,6 +63,7 @@ mod totem; mod trading; mod trident; mod wandering_trader; +mod wind; mod wither; use horizon_client::{ Result, diff --git a/crates/horizon-client/src/game/breezes.rs b/crates/horizon-client/src/game/breezes.rs new file mode 100644 index 000000000..52e3b36a9 --- /dev/null +++ b/crates/horizon-client/src/game/breezes.rs @@ -0,0 +1,65 @@ +//! Breeze particles (`Breeze.tick`): block dust at its feet while it stands, +//! a burst of twenty while it slides and a short trail along a long jump. +use super::Game; +use horizon_client::{ + mobs::{Species, breeze}, + particles::Particle, +}; + +impl Game<'_> { + pub(super) fn tick_breeze_effects(&mut self) { + let Some(camera) = self.player.as_ref().map(|p| p.position) else { + return; + }; + for i in 0..self.mobs.len() { + let m = &self.mobs[i]; + if m.species() != Species::Breeze + || !m.alive() + || m.position.distance_squared(camera) > 32.0 * 32.0 + { + continue; + } + let pose = breeze::pose(m); + let (amount, jump_trail) = match pose { + breeze::SLIDING => (20, false), + breeze::LONG_JUMPING => (3, true), + _ => (1, false), + }; + if jump_trail { + self.mobs[i].extra.scratch[1] += 1; + if self.mobs[i].extra.scratch[1] > 5 { + continue; + } + } else { + self.mobs[i].extra.scratch[1] = 0; + } + let m = &self.mobs[i]; + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let mut state = self.world.block(x, y, z); + if self.res.facts.is_air(state) { + state = self.world.block(x, (m.position.y - 0.2).floor() as i32, z); + } + let Some((sprite, tint)) = self.particle_sprite(state) else { + continue; + }; + let at = if jump_trail { + [ + m.position.x + m.velocity.x, + m.position.y + m.velocity.y + f64::from(0.1_f32), + m.position.z + m.velocity.z, + ] + } else { + [m.position.x, m.position.y, m.position.z] + }; + for _ in 0..amount { + let particle = + Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint); + self.particles.push(particle); + } + } + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 9bf3b9c99..8d5a6d0c3 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -30,6 +30,8 @@ pub(super) struct Creatures { /// Player status effects applied by mobs: (effect, ticks left, amplifier). pub player_fire: i32, pub pearl_cooldown: u32, + /// The wind charge's use cooldown (ticks). + pub wind_cooldown: u32, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -649,6 +651,7 @@ impl Game<'_> { self.tick_projectiles()?; self.tick_fangs(); self.tick_allays(); + self.tick_breeze_effects(); self.tick_player_effects(); self.piglin_pickups(); Ok(()) @@ -1291,6 +1294,7 @@ impl Game<'_> { self.creatures.player_fire -= 1; } } + self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1); if self.creatures.pearl_cooldown > 0 { self.creatures.pearl_cooldown -= 1; } @@ -1308,6 +1312,7 @@ impl Game<'_> { fn tick_projectiles(&mut self) -> Result<()> { let mut projectiles = std::mem::take(&mut self.creatures.projectiles); let mut hits = Vec::new(); + let mut deflections: Vec<[f64; 3]> = Vec::new(); { let mut targets: Vec<(Who, Aabb)> = self .mobs @@ -1326,16 +1331,55 @@ impl Game<'_> { .into_iter() .map(|(id, b)| (Who::Mob(id), b)), ); + let breezes: Vec = self + .mobs + .iter() + .filter(|m| m.alive() && m.species() == Species::Breeze) + .map(|m| m.id) + .collect(); + let jitter = self.world.random.next_float(); let w = self.mob_world_base(&[]); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { let (keep, hit) = p.tick(&pw); + let wind = matches!( + p.kind, + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge + ); + // Entity.deflection: a breeze turns every projectile but wind charges away. + if let Hit::Entity { + who: Who::Mob(id), + at, + } = hit + && !wind + && breezes.contains(&id) + { + super::wind::reverse(p, jitter); + deflections.push([at.x, at.y, at.z]); + return true; + } + // AbstractWindCharge.tick: out of the world's top it bursts. + if wind && keep && p.position.y > 350.0 { + hits.push(( + p.clone(), + Hit::Block { + pos: [0; 3], + at: p.position, + face: [0; 3], + }, + )); + return false; + } if hit != Hit::None { hits.push((p.clone(), hit)); } keep }); } + for at in deflections { + self.audio + .play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0); + } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { self.projectile_hit(&p, hit)?; @@ -1351,6 +1395,12 @@ impl Game<'_> { Hit::Entity { at, .. } | Hit::Block { at, .. } => at, Hit::None => return Ok(()), }; + if matches!( + p.kind, + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge + ) { + return self.wind_charge_hit(p, hit); + } if let Hit::Entity { who: Who::Mob(id), .. } = hit @@ -2052,6 +2102,7 @@ impl Game<'_> { self.creatures.pearl_cooldown = 20; ProjectileKind::EnderPearl } + "minecraft:wind_charge" => return self.throw_wind_charge(), _ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack), _ => return Ok(false), }; @@ -2267,6 +2318,14 @@ impl Game<'_> { } continue; } + // WindChargeRenderer. + if matches!( + a.kind, + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge + ) { + self.wind_charge_geometry(a, c, packed, out); + continue; + } // WitherSkullRenderer: the skull model facing its flight. if let Some(dangerous) = super::wither::skull_kind(a) { static SKULL: std::sync::OnceLock> = @@ -2340,7 +2399,7 @@ fn eat_sound(s: Species) -> &'static str { 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::Blaze | S::Ghast | S::Hoglin | S::Zoglin | S::PiglinBrute | S::Breeze => 10, S::Slime | S::MagmaCube => m.extra.size.max(1) as u32, S::Endermite => 3, S::Bat diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9185252f1..7af422e94 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -78,7 +78,7 @@ impl Game<'_> { true } /// `ServerExplosion.getSeenPercent` for an entity box. - fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 { + pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 { let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0); let ys = 1.0 / ((max[1] - min[1]) * 2.0 + 1.0); let zs = 1.0 / ((max[2] - min[2]) * 2.0 + 1.0); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs new file mode 100644 index 000000000..b3cc188d8 --- /dev/null +++ b/crates/horizon-client/src/game/wind.rs @@ -0,0 +1,503 @@ +//! Wind charges: the item a player throws (`WindChargeItem`), the charges +//! breezes shoot, and the burst they make (`ServerExplosion` with +//! `TRIGGER_BLOCK`: no damage, only knockback and the blocks that react). +use super::Game; +use horizon_client::{ + Result, + mobs::{Damage, DamageKind, Species, Who}, + particles::{ParticleOptions, ParticleType}, + projectiles::{Hit, Projectile, ProjectileKind}, +}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::level::PlayerContext; +use std::collections::BTreeSet; + +/// `WindCharge.RADIUS` and the knockback multiplier of its damage calculator. +const PLAYER_RADIUS: f32 = 1.2; +const PLAYER_KNOCKBACK: f32 = 1.22; +/// `BreezeWindCharge.RADIUS`. +const BREEZE_RADIUS: f32 = 3.0; + +/// `Projectile.deflect` with `ProjectileDeflection.REVERSE`. +pub(super) fn reverse(p: &mut Projectile, jitter: f32) { + p.velocity = Vec3::new( + p.velocity.x * -0.5, + p.velocity.y * -0.5, + p.velocity.z * -0.5, + ); + p.yaw += 170.0 + jitter * 20.0; +} +/// Whether a block reacts to a wind charge's burst by being used. +fn triggers(name: &str) -> bool { + let n = name.trim_start_matches("minecraft:"); + // Doors and trapdoors open unless iron; gates, buttons, levers and bells react. + (n.ends_with("_door") || n.ends_with("_trapdoor")) && !n.starts_with("iron_") + || n.ends_with("_fence_gate") + || n.ends_with("_button") + || n == "lever" + || n == "bell" +} +impl Game<'_> { + /// `WindChargeItem.use`. + pub(super) fn throw_wind_charge(&mut self) -> Result { + if self.creatures.wind_cooldown > 0 { + return Ok(true); + } + self.creatures.wind_cooldown = 10; + let (Some(eye), Some(p)) = (self.eye_position(), self.player.as_ref()) else { + return Ok(false); + }; + let (velocity, on_ground, pos) = (p.velocity, p.ground.on_ground, p.position); + let start = Vec3::new(pos.x, eye[1], pos.z); + let mut proj = Projectile::new(ProjectileKind::WindCharge, 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 pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); + self.audio + .play("minecraft:entity.wind_charge.throw", Some(eye), 0.5, pitch); + self.stats.add("used", "minecraft:wind_charge", 1); + 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) + } + /// A wind charge meeting an entity or a block (or flying too high). + pub(super) fn wind_charge_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { + let breeze = p.kind == ProjectileKind::BreezeWindCharge; + let (radius, knockback) = if breeze { + (BREEZE_RADIUS, 1.0) + } else { + (PLAYER_RADIUS, PLAYER_KNOCKBACK) + }; + let center = match hit { + Hit::Entity { who, at } => { + self.wind_charge_damage(p, who); + [at.x, at.y, at.z] + } + // onHitBlock: a quarter of a block out along the face. + Hit::Block { at, face, .. } => [ + at.x + f64::from(face[0]) * 0.25, + at.y + f64::from(face[1]) * 0.25, + at.z + f64::from(face[2]) * 0.25, + ], + Hit::None => return Ok(()), + }; + self.wind_burst( + center, + radius, + knockback, + breeze, + p.owner == Some(Who::Player), + ) + } + /// `AbstractWindCharge.onHitEntity`: one point of damage. + fn wind_charge_damage(&mut self, p: &Projectile, who: Who) { + let owner_breeze = matches!(p.owner, Some(Who::Mob(id)) + if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Breeze)); + match who { + Who::Player => { + if !self.creative { + self.mob_hits_player_kind( + 1.0, + [p.previous.x, p.previous.y, p.previous.z], + "minecraft:wind_charge", + ); + } + } + Who::Mob(id) => { + let source = Damage { + kind: DamageKind::Thrown, + attacker: p.owner, + from: Some([p.previous.x, p.previous.y, p.previous.z]), + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + // Breeze.isInvulnerableTo: its own kind's charges. + if owner_breeze && m.species() == Species::Breeze { + return; + } + m.damage(1.0, source); + } + if p.owner == Some(Who::Player) { + self.last_hurt_by_player.insert(id); + } + } + } + } + /// The exploded positions: rays through everything but the blocks that + /// stop wind (`blocks_wind_charge_explosions`). + fn wind_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { + let stops = self + .res + .items + .block_tags + .get("minecraft:blocks_wind_charge_explosions") + .cloned() + .unwrap_or_default(); + let (min_y, max_y) = (horizon_client::chunk::MIN_Y, 320); + let mut set: BTreeSet<[i32; 3]> = BTreeSet::new(); + for xx in 0..16 { + for yy in 0..16 { + for zz in 0..16 { + if !(xx == 0 || xx == 15 || yy == 0 || yy == 15 || zz == 0 || zz == 15) { + continue; + } + let mut d = [ + f64::from(xx as f32 / 15.0 * 2.0 - 1.0), + f64::from(yy as f32 / 15.0 * 2.0 - 1.0), + f64::from(zz as f32 / 15.0 * 2.0 - 1.0), + ]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + for c in &mut d { + *c /= len; + } + let mut power = radius * (0.7 + self.world.random.next_float() * 0.6); + let mut at = center; + while power > 0.0 { + let pos = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + if pos[1] < min_y || pos[1] >= max_y { + break; + } + let name = &self + .res + .facts + .get(self.world.block(pos[0], pos[1], pos[2])) + .name; + if stops.contains(&**name) { + power -= (3_600_000.0_f32 + 0.3) * 0.3; + } + if power > 0.0 { + set.insert(pos); + } + for i in 0..3 { + at[i] += d[i] * f64::from(0.3_f32); + } + power -= 0.225_000_01; + } + } + } + } + set.into_iter().collect() + } + /// `ServerExplosion.hurtEntities` for a calculator that damages nothing: + /// knockback scaled by distance, exposure and the multiplier. + fn wind_knockback( + &mut self, + center: [f64; 3], + radius: f32, + multiplier: f32, + player_charge: bool, + ) { + let diameter = f64::from(radius * 2.0); + let distance = |p: [f64; 3]| { + ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) + .sqrt() + }; + let direction = |origin: [f64; 3]| { + let d = [ + origin[0] - center[0], + origin[1] - center[1], + origin[2] - center[2], + ]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if l < 1.0e-5 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + } + }; + let multiplier = f64::from(multiplier); + // The player (not a spectator; a flying creative player takes none). + if let Some(p) = self.player.as_ref() + && !self.spectator() + { + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = distance(feet) / diameter; + let flying = self.creative && p.flying; + if dist <= 1.0 && !flying { + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let power = (1.0 - dist) * f64::from(exposure) * multiplier; + let dir = direction(eye); + if let Some(p) = self.player.as_mut() { + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + // ServerPlayer.onExplosionHit: a player's own charge cancels the fall. + if player_charge { + let at = p.position; + p.impulse.set_ignore_fall_damage(true, Some(at)); + } + } + } + } + let mut mobs = std::mem::take(&mut self.mobs); + for m in mobs.iter_mut().filter(|m| m.alive()) { + let feet = [m.position.x, m.position.y, m.position.z]; + let dist = distance(feet) / diameter; + if dist > 1.0 { + continue; + } + let (w, h) = (m.kind.width / 2.0, f64::from(m.height())); + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let eye = [feet[0], m.eye_y(), feet[2]]; + let power = (1.0 - dist) * f64::from(exposure) * multiplier; + let dir = direction(eye); + m.velocity = Vec3::new( + m.velocity.x + dir[0] * power, + m.velocity.y + dir[1] * power, + m.velocity.z + dir[2] * power, + ); + } + self.mobs = mobs; + // Arrows and other projectiles (the charges themselves ignore it). + let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| { + let feet = [position.x, position.y, position.z]; + let dist = distance(feet) / diameter; + if dist > 1.0 { + return; + } + let exposure = game.seen_percent( + center, + [feet[0] - 0.125, feet[1], feet[2] - 0.125], + [feet[0] + 0.125, feet[1] + 0.25, feet[2] + 0.125], + ); + let power = (1.0 - dist) * f64::from(exposure) * multiplier; + let dir = direction(feet); + *velocity = Vec3::new( + velocity.x + dir[0] * power, + velocity.y + dir[1] * power, + velocity.z + dir[2] * power, + ); + }; + let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + for p in projectiles.iter_mut().filter(|p| { + !p.stuck + && !matches!( + p.kind, + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge + ) + }) { + push(p.position, &mut p.velocity, self); + } + self.creatures.projectiles = projectiles; + let mut arrows = std::mem::take(&mut self.arrows); + for a in arrows.iter_mut().filter(|a| !a.stuck) { + push(a.position, &mut a.velocity, self); + } + self.arrows = arrows; + let mut tnts = std::mem::take(&mut self.tnts); + for t in &mut tnts { + push(t.position, &mut t.velocity, self); + } + self.tnts = tnts; + } + /// The burst: knockback, the blocks that react, the gust and the sound. + fn wind_burst( + &mut self, + center: [f64; 3], + radius: f32, + multiplier: f32, + breeze: bool, + player_charge: bool, + ) -> Result<()> { + let mut targets = self.wind_positions(center, radius); + self.wind_knockback(center, radius, multiplier, player_charge); + // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing. + if !breeze || self.ui.rules.bool("mob_griefing") { + // Util.shuffle(list, level.random) + for i in (2..=targets.len()).rev() { + let swap = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize; + targets.swap(i - 1, swap); + } + for pos in targets { + self.wind_trigger_block(pos)?; + } + } + let sound = if breeze { + "minecraft:entity.breeze.wind_burst" + } else { + "minecraft:entity.wind_charge.wind_burst" + }; + let pitch = (1.0 + + (super::explosion::client_float() - super::explosion::client_float()) * 0.2) + * 0.7; + self.audio.play(sound, Some(center), 4.0, pitch); + // Explosion.isSmall: below a radius of 2. + let ty = if radius < 2.0 { + ParticleType::GustEmitterSmall + } else { + ParticleType::GustEmitterLarge + }; + self.particles + .add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + Ok(()) + } + /// `BlockBehaviour.onExplosionHit` for `TRIGGER_BLOCK`: doors, gates, + /// buttons, levers and bells react as if used; candles go out. + fn wind_trigger_block(&mut self, pos: [i32; 3]) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + let name = self.res.facts.get(state).name.clone(); + let prop = |game: &Self, key: &str| { + game.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key).cloned()) + }; + if name.ends_with("candle") || name.ends_with("candle_cake") { + if prop(self, "lit").as_deref() == Some("true") { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + "minecraft:entity.generic.extinguish_fire", + Some(at), + 1.0, + 1.0, + ); + self.set_state_named(pos, &name, &["candles", "waterlogged"])?; + } + return Ok(()); + } + if !triggers(&name) { + return Ok(()); + } + // Doors react in their lower half only; powered ones and pressed + // buttons stay as they are. + if name.ends_with("_door") && prop(self, "half").as_deref() != Some("lower") { + return Ok(()); + } + if prop(self, "powered").as_deref() == Some("true") && &*name != "minecraft:lever" { + return Ok(()); + } + let at = Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ); + let player = PlayerContext { + yaw: self.yaw, + pitch: self.pitch, + may_build: true, + can_eat: false, + game_master: false, + }; + self.with_level(|b, level, ticks| { + b.use_without_item( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + Direction::Up, + at, + player, + ) + }); + self.process_level_events()?; + Ok(()) + } + /// `WindChargeRenderer`: the spinning charge and its wind. + pub(super) fn wind_charge_geometry( + &self, + p: &Projectile, + at: glam::Vec3, + light: u32, + out: &mut Vec, + ) { + static MODEL: std::sync::OnceLock> = + std::sync::OnceLock::new(); + let model = MODEL.get_or_init(|| { + horizon_client::mobs::load_model(&self.options.resources, "minecraft:wind_charge#main") + }); + let Some(model) = model else { return }; + let Some(r) = self + .res + .atlas + .sprites + .get("entity/projectiles/wind_charge") + .copied() + else { + return; + }; + let age = p.age as f32; + let mut poses = horizon_client::mobs::anim::Poses::new(model); + poses.yrot("wind_charge", -age * 16.0_f32.to_radians()); + poses.yrot("wind", age * 16.0_f32.to_radians()); + let base = glam::Mat4::from_translation(at) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + horizon_client::mobs::render::draw( + model, + base, + &poses, + [r.u0, r.v0, r.u1, r.v1], + 0xFFFF_FFFF, + light, + 0, + out, + ); + } +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_burst_opens_wooden_doors_but_not_iron_ones() { + assert!(triggers("minecraft:oak_door")); + assert!(triggers("minecraft:copper_trapdoor")); + assert!(!triggers("minecraft:iron_door")); + assert!(!triggers("minecraft:iron_trapdoor")); + assert!(triggers("minecraft:lever")); + assert!(triggers("minecraft:stone_button")); + assert!(triggers("minecraft:bell")); + assert!(!triggers("minecraft:stone")); + } + #[test] + fn a_deflected_projectile_turns_around_at_half_speed() { + let mut p = Projectile::new(ProjectileKind::Snowball, Vec3::ZERO, None); + p.velocity = Vec3::new(2.0, -1.0, 0.0); + reverse(&mut p, 0.5); + assert!((p.velocity.x + 1.0).abs() < 1e-9 && (p.velocity.y - 0.5).abs() < 1e-9); + assert!((p.yaw - 180.0).abs() < 1e-4); + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3e0d9a01a..5377baba2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -9,6 +9,7 @@ pub mod ai; pub mod allay; pub mod anim; pub mod aquatic; +pub mod breeze; pub mod camel; pub mod caravan; pub mod control; @@ -482,6 +483,8 @@ pub struct Extra { pub leash: Option, pub leash_pending: Option, pub leash_spin: f64, + /// More species scratch values. + pub scratch: [i32; 4], } #[derive(Clone, Debug)] pub struct Mob { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 1f07db6c1..d8ef5d275 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -88,6 +88,7 @@ pub enum Family { Allay, Villager, Trader, + Breeze, } pub fn family(s: Species) -> Family { use Species as S; @@ -124,6 +125,7 @@ pub fn family(s: Species) -> Family { S::Allay => Family::Allay, S::Villager => Family::Villager, S::WanderingTrader => Family::Trader, + S::Breeze => Family::Breeze, S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin, S::Horse | S::Donkey @@ -177,6 +179,7 @@ pub fn register(m: &mut Mob) { Family::Allay => super::allay::register(m), Family::Villager => super::villager::register(m), Family::Trader => super::trader::register(m), + Family::Breeze => super::breeze::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -402,6 +405,11 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air", Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return, Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item", + // Breeze.playAmbientSound. + Species::Breeze => match super::breeze::ambient(m) { + Some(s) => s, + None => return, + }, // Shulker.playAmbientSound: silent while closed. Species::Shulker if m.extra.counter == 0 => return, Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", @@ -575,6 +583,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Ravager => super::ravager::ai_step(m, w, events), Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), + Species::Breeze => super::breeze::ai_step(m, events), Species::Villager => super::villager::ai_step(m, w), Species::WanderingTrader => { super::villager::ai_step(m, w); diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index cbfe2da3a..8f7ed27fc 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -8,6 +8,7 @@ use std::f32::consts::PI; /// The setupAnim implementation a model uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Anim { + Breeze, Allay, Camel, Wither, @@ -345,6 +346,7 @@ pub fn setup( ) { match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), + Anim::Breeze => super::breeze::anim(m, s, p, w_anims), Anim::Llama => super::llama::anim(m, s, p), Anim::Allay => super::allay::anim(m, s, p), Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs new file mode 100644 index 000000000..9667a827a --- /dev/null +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -0,0 +1,785 @@ +//! Breezes (`Breeze`, `BreezeAi`): the brain's idle and fight activities as +//! one simulation (start attacking the nearest player or iron golem or whoever +//! hurt it, slide to a walk target, then shoot, long jump, shoot when stuck or +//! slide), memories with vanilla's expiry, the poses and their animations, +//! `BreezeModel`'s layers and the wind charges it shoots. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float, Goal, goal_clone}, + keyframes::Animation, +}; +use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::HashMap; + +// Breeze state (see `brain`): `variant3` the pose, `variant` the pose the +// animations last saw, `ints[0..6]` the memories (shoot, shoot cooldown, +// shoot charging, shoot recovering, jump cooldown, jump inhaling) as the +// remaining ticks plus one, `point` the walk target with `vector[0]` its +// speed and `vector[1]` how close is close enough, `home` the jump target, +// `vector[2]` the whirl sound clock, `flag` the long jump behaviour with its +// end tick in `anim_ticks`, `flag2` the shoot behaviour with its end tick in +// `egg_time`, `counter` the end tick of the slide to the walk target (0 when +// not sliding), `counter2` the end tick of doing nothing, `anger` the +// cooldown before the next try to walk, `scratch[0]` the ticks it may still +// be unable to attack its target. AnimState states: +// idle, shoot, slide, slide back, inhale, long jump. +pub const STANDING: u8 = 0; +pub const SHOOTING: u8 = 1; +pub const INHALING: u8 = 2; +pub const LONG_JUMPING: u8 = 3; +pub const SLIDING: u8 = 4; + +const SHOOT: usize = 0; +const SHOOT_COOLDOWN: usize = 1; +const SHOOT_CHARGING: usize = 2; +const SHOOT_RECOVERING: usize = 3; +const JUMP_COOLDOWN: usize = 4; +const JUMP_INHALING: usize = 5; + +const SHOOT_INITIAL_DELAY: i32 = 15; +const SHOOT_RECOVER_DELAY: i32 = 4; +const SHOOT_COOLDOWN_TICKS: i32 = 10; +const INHALING_TICKS: i32 = 10; +const ALLOWED_ANGLES: [i32; 5] = [40, 55, 60, 75, 80]; + +pub fn register(m: &mut Mob) { + m.set_malus(super::path::PathType::OnTopOfTrapdoor, -1.0); + m.set_malus(super::path::PathType::Fire, -1.0); + // Swim(0.8) and the brain. + m.ai.goals.add(0, Float); + m.ai.goals.add(0, Brain); +} +pub fn pose(m: &Mob) -> u8 { + m.extra.variant3 +} +fn set_pose(m: &mut Mob, pose: u8) { + m.extra.variant3 = pose; +} +fn has(m: &Mob, memory: usize) -> bool { + m.extra.ints[memory] > 0 +} +/// `Brain.setMemoryWithExpiry`: present now and for `ttl` more ticks. +fn remember(m: &mut Mob, memory: usize, ttl: i32) { + m.extra.ints[memory] = ttl + 1; +} +fn forget(m: &mut Mob, memory: usize) { + m.extra.ints[memory] = 0; +} +fn walk_target(m: &Mob) -> bool { + m.extra.point.is_some() +} +fn now(m: &Mob) -> i32 { + m.age as i32 +} +/// `Breeze.getFiringYPosition`. +pub fn firing_y(m: &Mob) -> f64 { + m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32) +} +/// `Breeze.withinInnerCircleRange`. +fn within_inner_circle(m: &Mob, target: Vec3) -> bool { + let me = Vec3::new( + m.position.x.floor() + 0.5, + m.position.y.floor() + 0.5, + m.position.z.floor() + 0.5, + ); + (target.x - me.x).powi(2) + (target.z - me.z).powi(2) < 16.0 && (target.y - me.y).abs() < 10.0 +} +/// `Entity.lookAt` with the eyes anchor: snap body and head to face a point. +fn snap_look(m: &mut Mob, at: [f64; 3]) { + let (dx, dy, dz) = ( + at[0] - m.position.x, + at[1] - m.eye_y(), + at[2] - m.position.z, + ); + let flat = (dx * dx + dz * dz).sqrt(); + m.head_pitch = (-dy.atan2(flat).to_degrees()) as f32; + m.yaw = (dz.atan2(dx).to_degrees() - 90.0) as f32; + m.head_yaw = m.yaw; + m.previous_head_pitch = m.head_pitch; + m.previous_yaw = m.yaw; + m.previous_head_yaw = m.yaw; +} +/// `BreezeUtil.hasLineOfSight`. +fn line_of_sight(m: &Mob, w: &MobWorld, target: Vec3) -> bool { + let from = m.position; + let range = 50.0_f64.max(m.attrs.follow_range); + from.distance(target) <= range && w.clear_between(from, target, false) +} +/// `BreezeUtil.randomPointBehindTarget`: four to eight blocks behind the +/// target's facing, with a spread of 45 degrees. +fn point_behind(m: &mut Mob, target: Vec3, head_yaw: f32) -> Vec3 { + let view = head_yaw + 180.0 + m.random.next_gaussian() as f32 * 90.0 / 2.0; + let r = 4.0 + m.random.next_float() * 4.0; + let d = Vec3::direction_from_rotation(0.0, view).scale(f64::from(r)); + target.add_vector(d) +} +/// The attack target's position, eye height, facing and whether it is a +/// player. +struct Quarry { + position: Vec3, + eye: f64, + yaw: f32, + height: f64, +} +fn quarry(m: &Mob, cx: &Cx, who: Who) -> Option { + let t = cx.w.target_info(who)?; + let yaw = match who { + Who::Player => { + cx.w.player + .as_ref() + .map_or(0.0, |p| (-p.look[0]).atan2(p.look[2]).to_degrees() as f32) + } + Who::Mob(id) => cx.w.seen(id).map_or(m.yaw, |s| s.yaw), + }; + Some(Quarry { + position: t.position, + eye: t.eye_y, + yaw, + height: t.bounds.max_position().y - t.bounds.min_position().y, + }) +} +/// `TargetingConditions.forCombat().range(follow)` plus `canAttack`: a +/// player (not in creative or spectator) or an iron golem it can see. +fn attackable(m: &mut Mob, cx: &Cx, who: Who) -> bool { + let follow = m.attrs.follow_range; + match who { + Who::Player => m.can_target_player(cx.w, follow, true), + Who::Mob(id) => { + let Some(s) = cx.w.seen(id) else { + return false; + }; + s.alive + && s.species == Species::IronGolem + && m.distance_sqr(s.position) <= follow * follow + && m.sees(cx.w, who) + } + } +} +/// `BreezeAttackEntitySensor` and `HurtBySensor`: candidates for +/// `StartAttacking`. +fn nearest_attackable(m: &mut Mob, cx: &Cx) -> Option { + let follow = m.attrs.follow_range; + let mut candidates: Vec<(f64, Who)> = Vec::new(); + if let Some(p) = &cx.w.player + && p.alive + && !p.creative + && !p.spectator + { + candidates.push((m.distance_sqr(p.position), Who::Player)); + } + for s in + cx.w.nearby(m.position, follow, |s| s.species == Species::IronGolem) + { + candidates.push((m.distance_sqr(s.position), Who::Mob(s.id))); + } + candidates.sort_by(|a, b| a.0.total_cmp(&b.0)); + candidates + .into_iter() + .map(|c| c.1) + .find(|w| attackable(m, cx, *w)) +} +fn hurt_by(m: &Mob, cx: &Cx) -> Option { + let (d, at) = m.last_damage?; + if i64::from(m.age) - at > 40 { + return None; + } + match d.attacker? { + Who::Player => Some(Who::Player), + Who::Mob(id) => { + cx.w.seen(id) + .filter(|s| s.alive && s.species == Species::IronGolem) + .map(|_| Who::Mob(id)) + } + } +} +/// The goal that runs the brain every tick. +#[derive(Clone, Debug)] +struct Brain; +impl Goal for Brain { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + true + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + brain(m, cx); + } +} +/// `Brain.tick`: memories expire, sensors scan, behaviours start in +/// priority order for the active activity, then the running ones tick. +fn brain(m: &mut Mob, cx: &mut Cx) { + for i in 0..6 { + if m.extra.ints[i] > 0 { + m.extra.ints[i] -= 1; + } + } + if m.extra.anger > 0 { + m.extra.anger -= 1; + } + let fight = m.ai.target.is_some() && !walk_target(m); + if fight { + stop_if_target_invalid(m, cx); + start_shoot(m, cx); + start_long_jump(m, cx); + start_shoot_when_stuck(m); + start_slide(m, cx); + } else { + // StartAttacking on the nearest attackable, then on whoever hurt it. + if m.ai.target.is_none() { + let scan = (m.age + m.id).is_multiple_of(20); + let found = if scan { + nearest_attackable(m, cx) + } else { + None + }; + let found = found.or_else(|| hurt_by(m, cx)); + if let Some(who) = found { + m.ai.target = Some(who); + m.extra.anger = 0; + m.extra.counter2 = 0; + } + } + start_walking(m, cx); + idle_stroll(m, cx); + } + tick_shoot(m, cx); + tick_long_jump(m, cx); + tick_walking(m, cx); +} +/// `StopAttackingIfTargetInvalid` with `wasEntityAttackableLastNTicks(100)`: +/// the target is dropped once it has not been attackable for 100 ticks. +fn stop_if_target_invalid(m: &mut Mob, cx: &mut Cx) { + let Some(who) = m.ai.target else { return }; + let alive = cx.w.target_info(who).is_some_and(|t| t.alive); + if alive && attackable(m, cx, who) { + m.extra.scratch[0] = 100; + return; + } + m.extra.scratch[0] -= 1; + if !alive || m.extra.scratch[0] < 0 { + m.ai.target = None; + m.extra.scratch[0] = 0; + } +} +/// `Shoot.checkExtraStartConditions` and `start`. +fn start_shoot(m: &mut Mob, cx: &mut Cx) { + if m.extra.flag2 + || !has(m, SHOOT) + || has(m, SHOOT_COOLDOWN) + || has(m, SHOOT_CHARGING) + || has(m, SHOOT_RECOVERING) + || walk_target(m) + || m.extra.home.is_some() + || pose(m) != STANDING + { + return; + } + let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else { + return; + }; + if m.position.distance_squared(q.position) >= 256.0 { + forget(m, SHOOT); + return; + } + m.extra.flag2 = true; + m.extra.egg_time = now(m) + SHOOT_INITIAL_DELAY + 1 + SHOOT_RECOVER_DELAY; + set_pose(m, SHOOTING); + remember(m, SHOOT_CHARGING, SHOOT_INITIAL_DELAY); + let at = m.center(); + cx.events + .push(MobEvent::Sound("entity.breeze.inhale", at, 1.0, 1.0)); +} +fn tick_shoot(m: &mut Mob, cx: &mut Cx) { + if !m.extra.flag2 { + return; + } + let target = m.ai.target; + if now(m) > m.extra.egg_time || target.is_none() || !has(m, SHOOT) { + // Shoot.stop. + m.extra.flag2 = false; + if pose(m) == SHOOTING { + set_pose(m, STANDING); + } + remember(m, SHOOT_COOLDOWN, SHOOT_COOLDOWN_TICKS); + forget(m, SHOOT); + return; + } + let Some(q) = target.and_then(|w| quarry(m, cx, w)) else { + return; + }; + snap_look(m, [q.position.x, q.eye, q.position.z]); + if !has(m, SHOOT_CHARGING) && !has(m, SHOOT_RECOVERING) { + remember(m, SHOOT_RECOVERING, SHOOT_RECOVER_DELAY); + let start = Vec3::new(m.position.x, firing_y(m), m.position.z); + let passenger_offset = 0.3; + let (xd, yd, zd) = ( + q.position.x - m.position.x, + q.position.y + q.height * passenger_offset - start.y, + q.position.z - m.position.z, + ); + let mut p = Projectile::new( + ProjectileKind::BreezeWindCharge, + start, + Some(Who::Mob(m.id)), + ); + // 5 - 4 * difficulty at normal. + p.shoot(&mut m.random, [xd, yd, zd], 0.7, -3.0); + cx.events.push(MobEvent::Projectile(p)); + cx.events + .push(MobEvent::Sound("entity.breeze.shoot", m.center(), 1.5, 1.0)); + } +} +/// `ShootWhenStuck`. +fn start_shoot_when_stuck(m: &mut Mob) { + if has(m, SHOOT) || has(m, JUMP_INHALING) || m.extra.home.is_some() || walk_target(m) { + return; + } + if m.rider.is_some() || m.fluids.in_water || m.extra.levitation_effect() { + remember(m, SHOOT, 60); + } +} +impl super::Extra { + fn levitation_effect(&self) -> bool { + self.effects.iter().any(|e| e.0 == "minecraft:levitation") + } +} +/// `Slide.start`: pick a point to slide to. +fn start_slide(m: &mut Mob, cx: &mut Cx) { + if has(m, SHOOT) + || has(m, JUMP_COOLDOWN) + || walk_target(m) + || !m.on_ground + || m.fluids.in_water + || pose(m) != STANDING + { + return; + } + let Some(q) = m.ai.target.and_then(|w| quarry(m, cx, w)) else { + return; + }; + let mut position: Option = None; + if within_inner_circle(m, q.position) + && let Some(away) = + m.default_random_pos_away(cx.w, 5, 5, [q.position.x, q.position.y, q.position.z]) + { + let away = Vec3::new(away[0], away[1], away[2]); + if line_of_sight(m, cx.w, away) + && q.position.distance_squared(away) > q.position.distance_squared(m.position) + { + position = Some(away); + } + } + let position = position.unwrap_or_else(|| { + if m.random.next_boolean() { + point_behind(m, q.position, q.yaw) + } else { + // randomPointInMiddleCircle: stop four to eight blocks short. + let d = q.position.subtract(m.position); + let distance = d.length() - (8.0 + (4.0 - 8.0) * m.random.next_double()); + m.position.add_vector(d.normalize().scale(distance)) + } + }); + m.extra.point = Some([position.x.floor(), position.y.floor(), position.z.floor()]); + m.extra.vector[0] = 0.6; + m.extra.vector[1] = 1.0; +} +/// `SlideToTargetSink` (`MoveToTargetSink`): walk to the walk target. +fn start_walking(m: &mut Mob, cx: &mut Cx) { + if m.extra.counter != 0 { + return; + } + let Some(target) = m.extra.point else { + return; + }; + if m.extra.anger > 0 { + return; + } + let close = m.extra.vector[1] as i32; + let here = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let reached = (target[0] as i32 - here[0]).abs() + + (target[1] as i32 - here[1]).abs() + + (target[2] as i32 - here[2]).abs() + <= close; + let speed = m.extra.vector[0]; + if !reached && m.nav_move_to(cx.w, [target[0] + 0.5, target[1], target[2] + 0.5], speed) { + m.extra.counter = now(m) + 20 + m.random.next_int_bound(21).unwrap_or(0); + cx.events + .push(MobEvent::Sound("entity.breeze.slide", m.center(), 1.0, 1.0)); + set_pose(m, SLIDING); + } else { + m.extra.point = None; + } +} +fn tick_walking(m: &mut Mob, _cx: &mut Cx) { + if m.extra.counter == 0 { + return; + } + let reached = m.extra.point.is_none_or(|target| { + let here = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + (target[0] as i32 - here[0]).abs() + + (target[1] as i32 - here[1]).abs() + + (target[2] as i32 - here[2]).abs() + <= m.extra.vector[1] as i32 + }); + if now(m) > m.extra.counter || m.ai.nav.is_done() || reached { + // SlideToTargetSink.stop. + m.extra.counter = 0; + m.extra.point = None; + m.nav_stop(); + set_pose(m, STANDING); + if m.ai.target.is_some() { + remember(m, SHOOT, 60); + } + } +} +/// `RunOne` of `DoNothing(20, 100)` and `RandomStroll.stroll(0.6)`. +fn idle_stroll(m: &mut Mob, cx: &mut Cx) { + if m.extra.counter != 0 || walk_target(m) || m.ai.target.is_some() { + return; + } + if now(m) < m.extra.counter2 { + return; + } + if m.random.next_int_bound(3).unwrap_or(0) == 0 { + m.extra.counter2 = now(m) + 20 + m.random.next_int_bound(81).unwrap_or(0); + } else if let Some(p) = m.land_random_pos(cx.w, 10, 7) { + m.extra.point = Some([p[0].floor(), p[1].floor(), p[2].floor()]); + m.extra.vector[0] = 0.6; + m.extra.vector[1] = 0.0; + } +} +fn can_jump_from_here(m: &Mob, w: &MobWorld) -> bool { + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + if w.block_name(x, y, z) == "minecraft:honey_block" { + return false; + } + (1..=4).all(|i| { + w.facts.is_air(w.world.block(x, y + i, z)) + || w.fluid(x, y + i, z) == crate::blocks::Fluid::Water + }) +} +/// `LongJump.snapToSurface`: the block above the surface below the point, +/// else above the ceiling over it. +fn snap_to_surface(w: &MobWorld, p: Vec3) -> Option<[i32; 3]> { + let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); + let y0 = p.y.floor() as i32; + for y in (y0 - 10..=y0).rev() { + let top = f64::from(w.data.state(w.world.block(x, y, z)).top); + if top > 0.0 { + let hit = (f64::from(y) + top).min(p.y); + return Some([x, hit.floor() as i32 + 1, z]); + } + } + for y in y0..=y0 + 10 { + if w.data.state(w.world.block(x, y, z)).top > 0.0 { + return Some([x, y + 1, z]); + } + } + None +} +fn dangerous_block(name: &str) -> bool { + matches!( + name, + "minecraft:fire" + | "minecraft:soul_fire" + | "minecraft:lava" + | "minecraft:magma_block" + | "minecraft:campfire" + | "minecraft:soul_campfire" + | "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ) +} +/// `LongJump.canRun` and `start`. +fn start_long_jump(m: &mut Mob, cx: &mut Cx) { + if m.extra.flag + || has(m, SHOOT) + || has(m, JUMP_COOLDOWN) + || walk_target(m) + || !can_run_long_jump(m, cx) + { + return; + } + m.extra.flag = true; + m.extra.anim_ticks = now(m) + 200; + if !has(m, JUMP_INHALING) { + remember(m, JUMP_INHALING, INHALING_TICKS); + } + set_pose(m, INHALING); + let at = m.center(); + cx.events + .push(MobEvent::Sound("entity.breeze.charge", at, 1.0, 1.0)); + if let Some(t) = m.extra.home { + snap_look( + m, + [ + f64::from(t[0]) + 0.5, + f64::from(t[1]) + 0.5, + f64::from(t[2]) + 0.5, + ], + ); + } +} +fn can_run_long_jump(m: &mut Mob, cx: &mut Cx) -> bool { + if !m.on_ground && !m.fluids.in_water { + return false; + } + if m.fluids.water > m.eye_height() || m.fluids.in_lava { + return false; + } + if m.extra.home.is_some() { + return true; + } + let Some(who) = m.ai.target else { + return false; + }; + let Some(q) = quarry(m, cx, who) else { + return false; + }; + let follow = m.attrs.follow_range; + let distance = m.position.distance(q.position); + if distance >= follow { + m.ai.target = None; + return false; + } + if distance - 4.0 <= 0.0 || !can_jump_from_here(m, cx.w) { + return false; + } + let behind = point_behind(m, q.position, q.yaw); + let Some(target) = snap_to_surface(cx.w, behind) else { + return false; + }; + if dangerous_block(cx.w.block_name(target[0], target[1] - 1, target[2])) { + return false; + } + let centre = Vec3::new( + f64::from(target[0]) + 0.5, + f64::from(target[1]) + 0.5, + f64::from(target[2]) + 0.5, + ); + if !line_of_sight(m, cx.w, centre) + && !line_of_sight(m, cx.w, centre.add_vector(Vec3::new(0.0, 4.0, 0.0))) + { + return false; + } + m.extra.home = Some(target); + true +} +/// `LongJumpUtil.calculateJumpVectorForAngle` without the collision check. +fn jump_vector(m: &Mob, target: Vec3, max_velocity: f32, angle: i32) -> Option { + let pos = m.position; + let plane = Vec3::new(target.x - pos.x, 0.0, target.z - pos.z) + .normalize() + .scale(0.5); + let aim = target.subtract(plane); + let d = aim.subtract(pos); + let angrad = f64::from(angle as f32 * std::f32::consts::PI / 180.0); + let xz = d.z.atan2(d.x); + let r2 = d.x * d.x + d.z * d.z; + let r = r2.sqrt(); + let g = m.kind.gravity; + let sin2 = f64::from((2.0 * angrad as f32).sin()); + let cos_sq = angrad.cos().powi(2); + let v0sq = r2 * g / (r * sin2 - 2.0 * d.y * cos_sq); + if v0sq < 0.0 { + return None; + } + let v0 = v0sq.sqrt(); + if v0 > f64::from(max_velocity) { + return None; + } + let v0r = v0 * angrad.cos(); + let v0y = v0 * angrad.sin(); + Some(Vec3::new(v0r * xz.cos(), v0y, v0r * xz.sin()).scale(f64::from(0.95_f32))) +} +fn tick_long_jump(m: &mut Mob, cx: &mut Cx) { + if !m.extra.flag { + return; + } + let ongoing = pose(m) != STANDING && !has(m, JUMP_COOLDOWN); + if now(m) > m.extra.anim_ticks || !ongoing { + // LongJump.stop. + m.extra.flag = false; + if matches!(pose(m), LONG_JUMPING | INHALING) { + set_pose(m, STANDING); + } + m.extra.home = None; + forget(m, JUMP_INHALING); + m.extra.variant2 = 0; + return; + } + let in_water = m.fluids.in_water; + if !in_water && m.extra.variant2 != 0 { + m.extra.variant2 = 0; + } + let finished_inhaling = !has(m, JUMP_INHALING) && pose(m) == INHALING; + if finished_inhaling { + let target = m.extra.home.map(|t| { + Vec3::new( + f64::from(t[0]) + 0.5, + f64::from(t[1]), + f64::from(t[2]) + 0.5, + ) + }); + let mut angles = ALLOWED_ANGLES; + for i in (1..angles.len()).rev() { + let j = m.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + angles.swap(i, j); + } + let max = 0.058_333_334_f32 * m.attrs.follow_range as f32; + let v = target.and_then(|t| angles.iter().find_map(|&a| jump_vector(m, t, max, a))); + let Some(v) = v else { + set_pose(m, STANDING); + return; + }; + if in_water { + m.extra.variant2 = 1; + } + let at = m.center(); + cx.events + .push(MobEvent::Sound("entity.breeze.jump", at, 1.0, 1.0)); + set_pose(m, LONG_JUMPING); + m.yaw = m.body_yaw; + m.velocity = v; + m.on_ground = false; + return; + } + let landed_in_water = in_water && m.extra.variant2 == 0; + if pose(m) == LONG_JUMPING && (m.on_ground || landed_in_water) { + let at = m.center(); + cx.events + .push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0)); + set_pose(m, STANDING); + let hurt = m + .last_damage + .is_some_and(|(_, t)| i64::from(m.age) - t <= 40); + remember(m, JUMP_COOLDOWN, if hurt { 2 } else { 10 }); + remember(m, SHOOT, 100); + } +} +/// Whether `Breeze.shouldDiscardFriction` applies (a long jump in the air). +pub fn discards_friction(m: &Mob) -> bool { + m.species() == Species::Breeze && pose(m) == LONG_JUMPING +} +/// `Breeze.tick` and the client's pose-driven animation states. +pub fn ai_step(m: &mut Mob, events: &mut Vec) { + let age = m.age as f32; + let current = pose(m); + if current != m.extra.variant { + // resetAnimations, then the pose's own animation. + let st = &mut m.anim.states; + st[1].stop(); + st[0].stop(); + st[4].stop(); + st[5].stop(); + match current { + SHOOTING => st[1].start_if_stopped(age), + INHALING => st[4].start_if_stopped(age), + SLIDING => st[2].start_if_stopped(age), + _ => {} + } + m.extra.variant = current; + } + if current == LONG_JUMPING { + m.anim.states[5].start_if_stopped(age); + } + m.anim.states[0].start_if_stopped(age); + if current != SLIDING && m.anim.states[2].started.is_some() { + m.anim.states[3].start(age); + m.anim.states[2].stop(); + } + // The whirl sound. + if m.extra.vector[2] <= 0.0 { + m.extra.vector[2] = f64::from(1 + m.random.next_int_bound(80).unwrap_or(0)); + } else { + m.extra.vector[2] -= 1.0; + if m.extra.vector[2] <= 0.0 { + let pitch = 0.7 + 0.4 * m.random.next_float(); + let volume = 0.8 + 0.2 * m.random.next_float(); + events.push(MobEvent::Sound( + "entity.breeze.whirl", + [m.position.x, m.position.y, m.position.z], + volume, + pitch, + )); + } + } +} +/// `Breeze.playAmbientSound` and its sound selection. +pub fn ambient(m: &Mob) -> Option<&'static str> { + if m.ai.target.is_some() && m.on_ground { + return None; + } + Some(if m.on_ground { + "entity.breeze.idle_ground" + } else { + "entity.breeze.idle_air" + }) +} +/// `BreezeModel.setupAnim`: the six keyframe animations. +pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap) { + let age = s.age; + for (state, name) in [ + (&m.anim.states[0], "IDLE"), + (&m.anim.states[1], "SHOOT"), + (&m.anim.states[2], "SLIDE"), + (&m.anim.states[3], "SLIDE_BACK"), + (&m.anim.states[4], "INHALE"), + (&m.anim.states[5], "JUMP"), + ] { + if let (Some(ms), Some(a)) = ( + state.millis(age), + animations.get(&format!("BreezeAnimation.{name}")), + ) { + a.apply(ms, 1.0, p); + } + } +} +#[cfg(test)] +mod tests { + #[test] + fn a_memory_is_present_for_its_ttl_plus_the_tick_it_was_set() { + // setMemoryWithExpiry(15) at tick T: present T through T + 15. + let mut v = 16; + let mut present = 1; + for _ in 0..30 { + if v > 0 { + v -= 1; + } + if v > 0 { + present += 1; + } + } + assert_eq!(present, 16); + } + #[test] + fn the_highest_arc_reaches_a_target_within_range() { + // Angle 80 degrees: v0^2 = r^2 g / (r sin 2a - 2 y cos^2 a). + let g = 0.08; + let (r, y): (f64, f64) = (10.0, 0.0); + let a = 60.0_f64.to_radians(); + let v0sq = r * r * g / (r * (2.0 * a).sin() - 2.0 * y * a.cos().powi(2)); + assert!(v0sq.sqrt() < 1.4); + } +} diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 327b0662b..9be5214cd 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -121,6 +121,10 @@ impl Mob { self.extra.age < 0 } pub fn fluid_jump_threshold(&self) -> f64 { + // Breeze.getFluidJumpThreshold: its eye height. + if self.species() == super::Species::Breeze { + return self.eye_height(); + } if self.eye_height() < 0.4 { 0.0 } else { 0.4 } } pub fn is_in_liquid(&self) -> bool { @@ -306,6 +310,11 @@ impl Mob { } else { y -= self.gravity(); } + // LivingEntity.shouldDiscardFriction (a breeze's long jump). + if super::breeze::discards_friction(self) { + self.velocity = Vec3::new(movement.x, y, movement.z); + return; + } let drag = 0.91f32; let f = friction * drag; let vertical = if self.kind.flags.omnidirectional { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 2eeaea675..22f1960c6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -313,6 +313,24 @@ pub fn layers(m: &Mob) -> Vec { false, ); } + // BreezeWindLayer (the scroll is not reproduced: atlas sprites do + // not wrap) and BreezeEyesLayer. + S::Breeze => { + push( + &mut v, + "breeze#wind", + "entity/breeze/breeze_wind", + white, + false, + ); + push( + &mut v, + "breeze#eyes", + "entity/breeze/breeze_eyes", + white, + true, + ); + } // LlamaDecorLayer: the carpet, or the trader's blanket. S::Llama | S::TraderLlama => { if let Some((model, texture)) = super::llama::decor(m) { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index a0bf56dd2..4cda0ffb7 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -83,6 +83,7 @@ pub enum Species { Wither, Camel, Allay, + Breeze, } /// Baby bounding boxes (each class's BABY_DIMENSIONS). #[derive(Clone, Copy, Debug)] @@ -928,6 +929,20 @@ pub const ALL: &[Def] = &[ Some("entity.camel.step"), Baby::Abs(0.95, 1.4, 1.38) ), + def!( + Breeze, + "breeze", + "breeze#main", + "entity/breeze/breeze", + A::Breeze, + [ + "entity.breeze.idle_ground", + "entity.breeze.hurt", + "entity.breeze.death" + ], + None, + Baby::None + ), def!( Wither, "wither", @@ -1416,6 +1431,7 @@ impl Def { pub fn head_rot_speed(&self) -> f32 { match self.species { Species::Frog => 35.0, + Species::Breeze => 25.0, _ => 10.0, } } @@ -1430,6 +1446,7 @@ impl Def { match self.species { Species::Dolphin | Species::Axolotl => 1.0, Species::Frog => 5.0, + Species::Breeze => 30.0, Species::Goat => 15.0, Species::Armadillo => 32.0, _ => 75.0, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 8fa53a860..6a3b41a2b 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -119,13 +119,22 @@ particle_types! { Soul = "soul", SculkSoul = "sculk_soul", DragonBreath = "dragon_breath", + Gust = "gust", + SmallGust = "small_gust", + GustEmitterLarge = "gust_emitter_large", + GustEmitterSmall = "gust_emitter_small", } impl ParticleType { /// `ParticleType.getOverrideLimiter`: spawned regardless of distance. pub fn override_limiter(self) -> bool { matches!( self, - Self::DamageIndicator | Self::ExplosionEmitter | Self::Explosion | Self::Poof + Self::DamageIndicator + | Self::ExplosionEmitter + | Self::Explosion + | Self::Poof + | Self::GustEmitterLarge + | Self::GustEmitterSmall ) } } @@ -231,6 +240,11 @@ enum Behaviour { Crit, HugeExplosion, ExplosionSeed, + /// `GustSeedParticle`: three gusts around it every `delay + 1` ticks. + GustSeed { + scale: f64, + delay: i32, + }, Campfire, SimpleAnimated { fade: Option<[f32; 3]>, @@ -1429,6 +1443,34 @@ impl ParticleEngine { q.behaviour = Behaviour::ExplosionSeed; q } + // GustParticle: a still, bright, opaque quad that animates over + // its 12 to 15 ticks; the small one is scaled to 15%. + T::Gust | T::SmallGust => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.velocity = [0.0; 3]; + q.lifetime = 12 + r.next_int_bound(4).unwrap_or(0); + q.size = 1.0; + q.set_size(1.0, 1.0); + if ty == T::SmallGust { + q.scale(0.15); + } + q.light = Light::FullBright; + q.behaviour = Behaviour::HugeExplosion; + q.set = set; + q + } + T::GustEmitterLarge | T::GustEmitterSmall => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + let (scale, lifetime, delay) = if ty == T::GustEmitterLarge { + (3.0, 7, 0) + } else { + (1.0, 3, 2) + }; + q.lifetime = lifetime; + q.no_render = true; + q.behaviour = Behaviour::GustSeed { scale, delay }; + q + } T::CampfireCosySmoke | T::CampfireSignalSmoke => { let mut q = Particle::at(r, ty, p); q.scale(3.0); @@ -2156,6 +2198,29 @@ impl ParticleEngine { } self.sprite_from_age(p); } + Behaviour::GustSeed { scale, delay } => { + if p.age % (delay + 1) == 0 { + for _ in 0..3 { + let r = &mut self.random; + let at = [ + p.position[0] + (r.next_double() - r.next_double()) * scale, + p.position[1] + (r.next_double() - r.next_double()) * scale, + p.position[2] + (r.next_double() - r.next_double()) * scale, + ]; + let f = f64::from(p.age as f32 / p.lifetime as f32); + self.add( + &ParticleOptions::simple(ParticleType::Gust), + at, + [f, 0.0, 0.0], + ); + } + } + let age = p.age; + p.age += 1; + if age == p.lifetime { + p.removed = true; + } + } Behaviour::ExplosionSeed => { for _ in 0..6 { let r = &mut self.random; diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 596dc8e18..28054b428 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -25,6 +25,10 @@ pub enum ProjectileKind { power: i32, }, LlamaSpit, + /// A player's `WindCharge` and a breeze's `BreezeWindCharge`: straight + /// flight that bursts on whatever it meets. + WindCharge, + BreezeWindCharge, /// `ShulkerBullet`: homing on `target` in axis-aligned steps. ShulkerBullet { target: Who, @@ -484,6 +488,7 @@ impl Projectile { ); } ProjectileKind::Arrow { .. } => {} + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {} // LlamaSpit.tick: gone in water; drag and gravity follow the move. ProjectileKind::LlamaSpit => { if water { @@ -628,6 +633,8 @@ impl Projectile { ProjectileKind::Potion { .. } => "item/splash_potion", ProjectileKind::LlamaSpit => "entity/llama/llama_spit", ProjectileKind::ShulkerBullet { .. } => "entity/shulker/spark", + // Drawn as `WindChargeModel` by the game. + ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => return None, ProjectileKind::WitherSkull { dangerous: false } => "entity/wither/wither", ProjectileKind::WitherSkull { dangerous: true } => "entity/wither/wither_invulnerable", ProjectileKind::Arrow { .. } => return None,