Port vanilla mob AI framework: goals, A* pathfinding, controls, projectiles
Mobs now run vanilla's tick order with a GoalSelector/target selector (priorities, MOVE/LOOK/JUMP/TARGET flags), PathNavigation over the walk/swim/fly/amphibious node evaluators, Move/Look/Jump/BodyRotation controls and LivingEntity travel in air, water and lava. Path types, spawn surfaces and keyframe animations come from a new exporter (VanillaMobDataExporter -> mob-data.json). Farm animals, zombies, skeletons, creepers and spiders get their vanilla goals; projectiles (arrows, snowballs, eggs, ender pearls, fireballs) share one system; natural spawning follows NaturalSpawner with category caps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
|
||||
//! block interaction, inventory and HUD.
|
||||
mod control;
|
||||
mod creatures;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -9,8 +10,8 @@ use horizon_client::{
|
||||
blocks::{BlockFacts, Fluid},
|
||||
chunk::{HEIGHT, MIN_Y},
|
||||
clock::FixedStep,
|
||||
entities::{Arrow, ArrowHit, Experience, ExperienceOrb, ItemEntity},
|
||||
mobs::{Mob, MobEvent, MobType, MobTypes, MobWorld},
|
||||
entities::{Arrow, Experience, ExperienceOrb, ItemEntity},
|
||||
mobs::{Mob, MobType, MobTypes},
|
||||
particles::Particle,
|
||||
containers::{BlockEntity, Providers},
|
||||
creative::{Creative, Names},
|
||||
@@ -275,6 +276,7 @@ pub struct Resources {
|
||||
icons: HashMap<String, Option<Icon>>,
|
||||
layer_names: HashMap<u32, String>,
|
||||
mob_types: HashMap<String, Arc<MobType>>,
|
||||
mob_data: horizon_client::mobs::MobData,
|
||||
providers: Providers,
|
||||
chest_model: Option<horizon_client::mobs::Part>,
|
||||
nether_environment: Environment,
|
||||
@@ -343,6 +345,7 @@ struct Game<'a> {
|
||||
spawn_search: u32,
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
creatures: creatures::Creatures,
|
||||
attack_ticks: u32,
|
||||
last_hurt_by_player: HashSet<u32>,
|
||||
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
|
||||
@@ -935,6 +938,9 @@ impl Game<'_> {
|
||||
Ok(())
|
||||
}
|
||||
fn use_item(&mut self) -> Result<()> {
|
||||
if self.interact_mob()? {
|
||||
return Ok(());
|
||||
}
|
||||
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
|
||||
// MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item.
|
||||
if !(sneaking && self.held().is_some())
|
||||
@@ -965,6 +971,9 @@ impl Game<'_> {
|
||||
}
|
||||
let Some(stack) = self.held().cloned() else { return Ok(()) };
|
||||
let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) };
|
||||
if self.throw_item(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
if &*stack.item == "minecraft:bow" {
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.selected, 0));
|
||||
@@ -2078,17 +2087,8 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mobs.
|
||||
for mob in &self.mobs {
|
||||
let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera;
|
||||
if d.length_squared() > 128.0 * 128.0 {
|
||||
continue;
|
||||
}
|
||||
let Some(r) = self.res.atlas.sprites.get(&mob.kind.texture).copied() else { continue };
|
||||
let light = self.world.light(mob.position.x.floor() as i32, (mob.position.y + mob.kind.eye_height).floor() as i32, mob.position.z.floor() as i32);
|
||||
let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8;
|
||||
horizon_client::mobs::render(mob, alpha as f32, camera, [r.u0, r.v0, r.u1, r.v1], packed, &mut out);
|
||||
}
|
||||
// Mobs and their projectiles.
|
||||
self.mob_geometry(camera, alpha, &mut out);
|
||||
// Arrows: two crossed quads along the flight direction.
|
||||
if let Some(r) = self.res.atlas.sprites.get("entity/projectiles/arrow").copied() {
|
||||
for a in &self.arrows {
|
||||
@@ -2277,106 +2277,6 @@ impl Game<'_> {
|
||||
// Level.updateSkyBrightness: darkening from the sky light level.
|
||||
(15.0 - 15.0 * sky.sky_light_level).round() as i32
|
||||
}
|
||||
fn weighted<'b>(&mut self, entries: &'b [horizon_client::biome::SpawnEntry]) -> Option<&'b horizon_client::biome::SpawnEntry> {
|
||||
let supported: Vec<&horizon_client::biome::SpawnEntry> =
|
||||
entries.iter().filter(|e| self.res.mob_types.contains_key(&e.entity)).collect();
|
||||
let total: u32 = supported.iter().map(|e| e.weight).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut r = self.world.random.next_int_bound(total as i32).ok()? as u32;
|
||||
supported.into_iter().find(|e| {
|
||||
if r < e.weight {
|
||||
true
|
||||
} else {
|
||||
r -= e.weight;
|
||||
false
|
||||
}
|
||||
})
|
||||
}
|
||||
fn add_mob(&mut self, kind: &str, x: f64, y: f64, z: f64, persistent: bool) {
|
||||
let Some(t) = self.res.mob_types.get(kind).cloned() else { return };
|
||||
self.next_entity += 1;
|
||||
let yaw = self.world.random.next_float() * 360.0;
|
||||
let mut mob = Mob::new(self.next_entity, t, Vec3::new(x, y, z), yaw);
|
||||
mob.persistent = persistent;
|
||||
self.mobs.push(mob);
|
||||
}
|
||||
/// NaturalSpawner.spawnMobsForChunkGeneration for the creature category.
|
||||
fn spawn_chunk_creatures(&mut self, cx: i32, cz: i32) {
|
||||
let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { return };
|
||||
let biome = self.res.biomes.get(chunk.biome(8, 64, 8)).clone();
|
||||
let Some(entries) = biome.spawns.get("creature").cloned() else { return };
|
||||
while self.world.random.next_float() < biome.creature_probability {
|
||||
let Some(entry) = self.weighted(&entries).cloned() else { return };
|
||||
let count = entry.min + self.world.random.next_int_bound((entry.max - entry.min + 1) as i32).unwrap_or(0) as u32;
|
||||
let mut x = cx * 16 + self.world.random.next_int_bound(16).unwrap_or(0);
|
||||
let mut z = cz * 16 + self.world.random.next_int_bound(16).unwrap_or(0);
|
||||
for _ in 0..count {
|
||||
if let Some(y) = self.land_column(x, z) {
|
||||
let below = self.world.block(x, y - 1, z);
|
||||
if self.res.facts.get(below).name.contains("grass") {
|
||||
self.add_mob(&entry.entity, f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5, true);
|
||||
}
|
||||
}
|
||||
x = (x + self.world.random.next_int_bound(5).unwrap_or(0) - self.world.random.next_int_bound(5).unwrap_or(0)).clamp(cx * 16, cx * 16 + 15);
|
||||
z = (z + self.world.random.next_int_bound(5).unwrap_or(0) - self.world.random.next_int_bound(5).unwrap_or(0)).clamp(cz * 16, cz * 16 + 15);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// NaturalSpawner.spawnCategoryForPosition for monsters near the player.
|
||||
fn spawn_monsters(&mut self) {
|
||||
let Some(p) = self.player.as_ref().map(|p| p.position) else { return };
|
||||
if self.creative && false {
|
||||
return;
|
||||
}
|
||||
let monsters = self.mobs.iter().filter(|m| m.hostile()).count();
|
||||
if monsters >= 70 {
|
||||
return;
|
||||
}
|
||||
let r = &mut self.world.random;
|
||||
let cx = (p.x.floor() as i32 >> 4) + r.next_int_bound(17).unwrap_or(8) - 8;
|
||||
let cz = (p.z.floor() as i32 >> 4) + r.next_int_bound(17).unwrap_or(8) - 8;
|
||||
let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { return };
|
||||
let x = cx * 16 + r.next_int_bound(16).unwrap_or(0);
|
||||
let z = cz * 16 + r.next_int_bound(16).unwrap_or(0);
|
||||
let top = self.land_column(x, z).unwrap_or(MIN_Y + 1).max(MIN_Y + 1);
|
||||
let y = MIN_Y + self.world.random.next_int_bound((top - MIN_Y + 1).max(1)).unwrap_or(0);
|
||||
let biome = self.res.biomes.get(chunk.biome(x, y, z)).clone();
|
||||
let Some(entries) = biome.spawns.get("monster").cloned() else { return };
|
||||
let Some(entry) = self.weighted(&entries).cloned() else { return };
|
||||
let darken = self.sky_darken();
|
||||
let pack = entry.min + self.world.random.next_int_bound((entry.max - entry.min + 1) as i32).unwrap_or(0) as u32;
|
||||
let (mut sx, mut sz) = (x, z);
|
||||
for _ in 0..pack.min(4) {
|
||||
sx += self.world.random.next_int_bound(6).unwrap_or(0) - self.world.random.next_int_bound(6).unwrap_or(0);
|
||||
sz += self.world.random.next_int_bound(6).unwrap_or(0) - self.world.random.next_int_bound(6).unwrap_or(0);
|
||||
let (fx, fy, fz) = (f64::from(sx) + 0.5, f64::from(y), f64::from(sz) + 0.5);
|
||||
let d2 = (fx - p.x).powi(2) + (fy - p.y).powi(2) + (fz - p.z).powi(2);
|
||||
if d2 < 24.0 * 24.0 || d2 > 128.0 * 128.0 {
|
||||
continue;
|
||||
}
|
||||
let free = |g: &Self, yy: i32| {
|
||||
let f = g.res.facts.get(g.world.block(sx, yy, sz));
|
||||
!f.full_collision && f.fluid == Fluid::None
|
||||
};
|
||||
let below = self.res.facts.get(self.world.block(sx, y - 1, sz));
|
||||
if !below.full_collision || below.fluid != Fluid::None || !free(self, y) || !free(self, y + 1) {
|
||||
continue;
|
||||
}
|
||||
// Monster.isDarkEnoughToSpawn: sky light vs random(32), then
|
||||
// block light 0 and darkened brightness within uniform(0, 7).
|
||||
let light = self.world.light(sx, y, sz);
|
||||
let (sky, block) = (i32::from(light >> 4), i32::from(light & 15));
|
||||
if sky > self.world.random.next_int_bound(32).unwrap_or(0) || block > 0 {
|
||||
continue;
|
||||
}
|
||||
if (sky - darken).max(0) > self.world.random.next_int_bound(8).unwrap_or(0) {
|
||||
continue;
|
||||
}
|
||||
self.add_mob(&entry.entity, fx, fy, fz, false);
|
||||
}
|
||||
}
|
||||
fn mob_hit(&self) -> Option<(usize, f64)> {
|
||||
let eye = self.eye_position()?;
|
||||
let dir = view_vector(self.yaw, self.pitch);
|
||||
@@ -2539,7 +2439,13 @@ impl Game<'_> {
|
||||
let dist = ((m.position.x - center[0]).powi(2) + (m.position.y - center[1]).powi(2) + (m.position.z - center[2]).powi(2)).sqrt() / diameter;
|
||||
if dist <= 1.0 && m.alive() {
|
||||
let impact = 1.0 - dist;
|
||||
m.hurt(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, Some(center), &mut self.world.random);
|
||||
let source = horizon_client::mobs::Damage { kind: horizon_client::mobs::DamageKind::Explosion, attacker: None, from: Some(center) };
|
||||
if m.damage(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, source) {
|
||||
let (dx, dy, dz) = (m.position.x - center[0], m.position.y - center[1], m.position.z - center[2]);
|
||||
let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4);
|
||||
let k = impact * (1.0 - m.kind.knockback_resistance);
|
||||
m.velocity = Vec3::new(m.velocity.x + dx / l * k, m.velocity.y + dy / l * k, m.velocity.z + dz / l * k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -2589,152 +2495,7 @@ impl Game<'_> {
|
||||
Arc::new(c)
|
||||
}
|
||||
fn tick_mobs(&mut self) -> Result<()> {
|
||||
self.attack_ticks = self.attack_ticks.saturating_add(1);
|
||||
// Generation-time creature packs for newly generated chunks.
|
||||
let fresh: Vec<(i32, i32)> = self.world.chunks.iter().filter(|(_, c)| c.fresh && c.lit).map(|(k, _)| *k).collect();
|
||||
for key in fresh {
|
||||
if let Some(c) = self.world.chunks.get_mut(&key) {
|
||||
Arc::make_mut(c).fresh = false;
|
||||
}
|
||||
self.spawn_chunk_creatures(key.0, key.1);
|
||||
}
|
||||
if self.ticks % 2 == 0 {
|
||||
self.spawn_monsters();
|
||||
}
|
||||
let player = self.player.as_ref().map(|p| ([p.position.x, p.position.y + 0.5, p.position.z], !p.health.dead_or_dying()));
|
||||
let daylight = self.sky_darken() < 4 && self.world.weather.levels(1.0).0 < 0.2;
|
||||
let mut events = Vec::new();
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
{
|
||||
let w = MobWorld { world: &self.world, facts: &self.res.facts, collision: self.collision, player, daylight };
|
||||
let random = &mut self.world.random.clone();
|
||||
let loaded = |m: &Mob| w.world.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32);
|
||||
let mut dead = Vec::new();
|
||||
mobs.retain_mut(|m| {
|
||||
if !loaded(m) {
|
||||
return !m.hostile() || m.persistent;
|
||||
}
|
||||
let keep = m.tick(&w, random, &mut events);
|
||||
if !keep && !m.alive() {
|
||||
dead.push((m.kind.id.clone(), [m.position.x, m.position.y, m.position.z], m.id));
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.world.random = random.clone();
|
||||
for (kind, pos, id) in dead {
|
||||
let by_player = self.last_hurt_by_player.remove(&id);
|
||||
let held = self.held().cloned();
|
||||
let drops = self.res.items.entity_drops(&kind, by_player, held.as_ref(), &mut self.world.random);
|
||||
for d in drops {
|
||||
self.spawn_item(d, [pos[0], pos[1] + 0.5, pos[2]], [0.0, 0.2, 0.0], 10);
|
||||
}
|
||||
if by_player {
|
||||
// Animal: 1 + random(3); Monster: 5.
|
||||
let hostile = self.res.mob_types.get(&kind).is_some_and(|t| t.category == "monster");
|
||||
let xp = if hostile { 5 } else { 1 + self.world.random.next_int_bound(3).unwrap_or(0) as u32 };
|
||||
self.spawn_orbs([pos[0], pos[1] + 0.5, pos[2]], xp);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.mobs = mobs;
|
||||
for e in events {
|
||||
match e {
|
||||
MobEvent::Sound(name, at, volume, pitch) => self.audio.play(&format!("minecraft:{name}"), Some(at), volume, pitch),
|
||||
MobEvent::AttackPlayer(amount, from) => {
|
||||
if self.creative {
|
||||
continue;
|
||||
}
|
||||
if let Some(player) = self.player.as_mut()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:mob_attack")
|
||||
&& player.hurt(&self.motion.health, self.world.health_rules, id, amount).unwrap_or(false)
|
||||
{
|
||||
let (dx, dz) = (player.position.x - from[0], player.position.z - from[2]);
|
||||
let l = (dx * dx + dz * dz).sqrt().max(1e-4);
|
||||
player.velocity = Vec3::new(player.velocity.x / 2.0 + dx / l * 0.4, (player.velocity.y / 2.0 + 0.4).min(0.4), player.velocity.z / 2.0 + dz / l * 0.4);
|
||||
let at = [player.position.x, player.position.y, player.position.z];
|
||||
self.audio.play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0);
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
}
|
||||
MobEvent::Shoot(from, target) => {
|
||||
// Skeleton.performRangedAttack: aim above by 20% of distance, inaccuracy 14 - 4 * difficulty(2).
|
||||
let (dx, dz) = (target[0] - from[0], target[2] - from[2]);
|
||||
let horizontal = (dx * dx + dz * dz).sqrt();
|
||||
let dy = target[1] + 0.5 - from[1] + horizontal * 0.2;
|
||||
let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4);
|
||||
let spread = 0.0075 * 6.0;
|
||||
let r = &mut self.world.random;
|
||||
let mut gauss = || f64::from(r.next_float() + r.next_float() - 1.0) * spread;
|
||||
let v = [(dx / len + gauss()) * 1.6, (dy / len + gauss()) * 1.6, (dz / len + gauss()) * 1.6];
|
||||
let p = Vec3::new(from[0], from[1] - 0.1, from[2]);
|
||||
self.arrows.push(Arrow { from_player: false, critical: false, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 });
|
||||
self.audio.play("minecraft:entity.skeleton.shoot", Some(from), 1.0, 1.0 / (self.world.random.next_float() * 0.4 + 0.8));
|
||||
}
|
||||
MobEvent::Explode(at, radius) => self.explode(at, radius)?,
|
||||
}
|
||||
}
|
||||
// Arrows.
|
||||
let bounds = self.player.as_ref().map(|p| {
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
horizon_core::geometry::Aabb::new(
|
||||
Vec3::new(p.position.x - w, p.position.y, p.position.z - w),
|
||||
Vec3::new(p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w),
|
||||
)
|
||||
});
|
||||
let mut arrows = std::mem::take(&mut self.arrows);
|
||||
let mut hits = Vec::new();
|
||||
let mobs = &mut self.mobs;
|
||||
let mut random_state = self.world.random.clone();
|
||||
let random = &mut random_state;
|
||||
let mut mob_hits = Vec::new();
|
||||
arrows.retain_mut(|a| {
|
||||
if a.from_player && !a.stuck {
|
||||
let (keep, _) = a.tick(&self.world, &self.res.facts, None);
|
||||
for m in mobs.iter_mut().filter(|m| m.alive()) {
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let p = a.position;
|
||||
if p.x > lo.x - 0.3 && p.x < hi.x + 0.3 && p.y > lo.y - 0.3 && p.y < hi.y + 0.3 && p.z > lo.z - 0.3 && p.z < hi.z + 0.3 {
|
||||
// AbstractArrow.onHitEntity: ceil(speed * base), crits add random(damage / 2 + 2).
|
||||
let speed = (a.velocity.x.powi(2) + a.velocity.y.powi(2) + a.velocity.z.powi(2)).sqrt();
|
||||
let mut damage = (speed * a.base_damage).ceil().max(0.0) as i32;
|
||||
if a.critical {
|
||||
damage += random.next_int_bound(damage / 2 + 2).unwrap_or(0);
|
||||
}
|
||||
if m.hurt(damage as f32, Some([a.previous.x, a.previous.y, a.previous.z]), random) {
|
||||
mob_hits.push((m.id, [p.x, p.y, p.z]));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return keep;
|
||||
}
|
||||
let (keep, hit) = a.tick(&self.world, &self.res.facts, if a.from_player { None } else { bounds });
|
||||
if let ArrowHit::Player(d) = hit {
|
||||
hits.push(d);
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.arrows = arrows;
|
||||
self.world.random = random_state;
|
||||
for (id, at) in mob_hits {
|
||||
self.last_hurt_by_player.insert(id);
|
||||
self.audio.play("minecraft:entity.arrow.hit", Some(at), 1.0, 1.2 / (self.world.random.next_float() * 0.2 + 0.9));
|
||||
}
|
||||
for d in hits {
|
||||
if self.creative {
|
||||
continue;
|
||||
}
|
||||
if let Some(player) = self.player.as_mut()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:arrow")
|
||||
{
|
||||
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, d);
|
||||
let at = [player.position.x, player.position.y, player.position.z];
|
||||
self.audio.play("minecraft:entity.arrow.hit_player", Some(at), 1.0, 1.0);
|
||||
self.hurt_armor(d);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
self.tick_creatures()
|
||||
}
|
||||
/// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle.
|
||||
fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec<Vertex> {
|
||||
@@ -3539,14 +3300,13 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
let Some(eye) = self.eye_position() else { return };
|
||||
let dir = view_vector(self.yaw, self.pitch);
|
||||
// Projectile.shoot: inaccuracy 1.0 as gaussian * 0.0075.
|
||||
let r = &mut self.world.random;
|
||||
let mut jitter = || f64::from(r.next_float() + r.next_float() - 1.0) * 0.0075;
|
||||
let speed = f64::from(power) * 3.0;
|
||||
let v = [(dir[0] + jitter()) * speed, (dir[1] + jitter()) * speed, (dir[2] + jitter()) * speed];
|
||||
// BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1).
|
||||
let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]);
|
||||
self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 });
|
||||
let kind = horizon_client::projectiles::ProjectileKind::Arrow { base_damage: 2.0, critical: power >= 1.0, effect: None };
|
||||
let mut arrow = horizon_client::projectiles::Projectile::new(kind, p, Some(horizon_client::mobs::Who::Player));
|
||||
let (velocity, on_ground) = self.player.as_ref().map_or((Vec3::ZERO, true), |pl| (pl.velocity, pl.ground.on_ground));
|
||||
arrow.shoot_from_rotation(&mut self.world.random, self.pitch, self.yaw, 0.0, power * 3.0, 1.0, velocity, on_ground);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5;
|
||||
self.audio.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch);
|
||||
if !self.creative
|
||||
@@ -4630,6 +4390,7 @@ pub fn run() -> Result<()> {
|
||||
})?);
|
||||
eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32());
|
||||
let facts = BlockFacts::load(&root, &assets.registry)?;
|
||||
let mob_data = horizon_client::mobs::MobData::load(&root, &facts);
|
||||
eprintln!("load facts: {:.2}s", started.elapsed().as_secs_f32());
|
||||
let items = Items::load(&root, &assets.registry, &facts)?;
|
||||
eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32());
|
||||
@@ -4699,6 +4460,7 @@ pub fn run() -> Result<()> {
|
||||
.map(|(w, h, px)| (w, h, px.chunks_exact(4).map(|p| p[3] > 0).collect()))
|
||||
.unwrap_or((1, 1, vec![false])),
|
||||
mob_types: MobTypes::load(&root)?.types.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(),
|
||||
mob_data,
|
||||
context,
|
||||
threads,
|
||||
player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main")
|
||||
@@ -4767,6 +4529,7 @@ pub fn run() -> Result<()> {
|
||||
spawn_search: 0,
|
||||
mobs: Vec::new(),
|
||||
arrows: Vec::new(),
|
||||
creatures: Default::default(),
|
||||
attack_ticks: 100,
|
||||
last_hurt_by_player: HashSet::new(),
|
||||
chest_open: HashMap::new(),
|
||||
|
||||
@@ -21,6 +21,9 @@ const HELP: &[&str] = &[
|
||||
"give ITEM [COUNT] add items to the inventory",
|
||||
"render-distance N chunks, 2..64",
|
||||
"time TICKS set the time of day",
|
||||
"summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)",
|
||||
"mobs [RADIUS] list mobs near the player with their AI state",
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks",
|
||||
"resume leave the pause menu",
|
||||
"screenshot PATH write the next frame as PNG",
|
||||
"stats [reset] frame-time summary since the last reset",
|
||||
@@ -196,6 +199,40 @@ impl Game<'_> {
|
||||
self.world.day_time = arg(1)?.parse()?;
|
||||
ok()
|
||||
}
|
||||
"summon" => {
|
||||
self.require_world()?;
|
||||
let baby = words.contains(&"baby");
|
||||
let nums: Vec<f64> = words[2..].iter().filter_map(|w| w.parse().ok()).collect();
|
||||
let at = (nums.len() >= 3).then(|| [nums[0], nums[1], nums[2]]);
|
||||
let id = self.summon(arg(1)?, at, baby)?;
|
||||
Ok(Some(json!({ "ok": true, "id": id })))
|
||||
}
|
||||
"fill" => {
|
||||
self.require_world()?;
|
||||
let c: Vec<i32> = (1..=6).map(|i| arg(i).and_then(|v| v.parse::<i32>().map_err(|e| e.to_string()))).collect::<std::result::Result<_, _>>()?;
|
||||
let name = arg(7)?;
|
||||
let name = if name.contains(':') { name.to_owned() } else { format!("minecraft:{name}") };
|
||||
let state = self.res.assets.registry.default_state(&name).ok_or_else(|| format!("unknown block {name}"))?;
|
||||
let (lo, hi) = ([c[0].min(c[3]), c[1].min(c[4]), c[2].min(c[5])], [c[0].max(c[3]), c[1].max(c[4]), c[2].max(c[5])]);
|
||||
if (hi[0] - lo[0] + 1) * (hi[1] - lo[1] + 1) * (hi[2] - lo[2] + 1) > 1 << 20 {
|
||||
return Err("fill volume too large".into());
|
||||
}
|
||||
for x in lo[0]..=hi[0] {
|
||||
for y in lo[1]..=hi[1] {
|
||||
for z in lo[2]..=hi[2] {
|
||||
if self.world.loaded(x, z) {
|
||||
self.world.set(x, y, z, state)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"mobs" => {
|
||||
self.require_world()?;
|
||||
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
|
||||
Ok(Some(self.control_mobs(radius)))
|
||||
}
|
||||
"resume" => {
|
||||
if self.screen == Screen::Paused {
|
||||
self.screen = Screen::Playing;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -54,7 +54,7 @@ pub struct Items {
|
||||
pub item_tags: HashMap<String, HashSet<String>>,
|
||||
loot: HashMap<String, Value>,
|
||||
}
|
||||
fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
|
||||
pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
|
||||
let dir = root.join(format!("data/minecraft/tags/{kind}"));
|
||||
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
|
||||
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
|
||||
@@ -184,17 +184,22 @@ impl Items {
|
||||
order.push(id);
|
||||
}
|
||||
let mut loot = HashMap::new();
|
||||
for kind in ["blocks", "entities"] {
|
||||
let dir = root.join(format!("data/minecraft/loot_table/{kind}"));
|
||||
for entry in fs::read_dir(&dir)?.flatten() {
|
||||
// Every loot table, keyed by its id (blocks/stone, entities/sheep/white,
|
||||
// gameplay/chicken_lay, shearing/sheep/red...).
|
||||
fn walk_loot(dir: &Path, base: &Path, loot: &mut HashMap<String, Value>) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)?.flatten() {
|
||||
let p = entry.path();
|
||||
if p.extension().is_some_and(|e| e == "json")
|
||||
&& let Some(stem) = p.file_stem().and_then(|s| s.to_str())
|
||||
{
|
||||
loot.insert(format!("minecraft:{kind}/{stem}"), serde_json::from_slice(&fs::read(&p)?)?);
|
||||
if p.is_dir() {
|
||||
walk_loot(&p, base, loot)?;
|
||||
} else if p.extension().is_some_and(|e| e == "json") {
|
||||
let id = p.strip_prefix(base)?.with_extension("").to_string_lossy().replace('\\', "/");
|
||||
loot.insert(format!("minecraft:{id}"), serde_json::from_slice(&fs::read(&p)?)?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let loot_root = root.join("data/minecraft/loot_table");
|
||||
walk_loot(&loot_root, &loot_root, &mut loot)?;
|
||||
Ok(Self {
|
||||
items,
|
||||
order,
|
||||
@@ -269,6 +274,13 @@ impl Items {
|
||||
ctx.evaluate(table, random)
|
||||
}
|
||||
/// Evaluate an entity's loot table (`minecraft:entities/<name>`).
|
||||
/// Evaluate any loot table by id (e.g. `minecraft:gameplay/chicken_lay`).
|
||||
pub fn loot_table(&self, id: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec<ItemStack> {
|
||||
let Some(table) = self.loot.get(id) else { return vec![] };
|
||||
let empty = BTreeMap::new();
|
||||
let ctx = LootContext { items: self, block: "", properties: &empty, held, killed_by_player };
|
||||
ctx.evaluate(table, random)
|
||||
}
|
||||
pub fn entity_drops(&self, entity: &str, killed_by_player: bool, held: Option<&ItemStack>, random: &mut LegacyRandom) -> Vec<ItemStack> {
|
||||
let name = entity.trim_start_matches("minecraft:");
|
||||
let Some(table) = self.loot.get(&format!("minecraft:entities/{name}")) else {
|
||||
|
||||
@@ -29,6 +29,7 @@ pub mod models;
|
||||
pub mod motion;
|
||||
pub mod particles;
|
||||
pub mod pose;
|
||||
pub mod projectiles;
|
||||
pub mod save;
|
||||
pub mod settings;
|
||||
pub mod sprint;
|
||||
|
||||
+474
-419
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,552 @@
|
||||
//! The per-tick mob update in vanilla order (`Entity.baseTick`,
|
||||
//! `LivingEntity.baseTick/tick/aiStep`, `Mob.serverAiStep`) and the
|
||||
//! dispatch to each species family's goals and special behaviour.
|
||||
use super::{
|
||||
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
|
||||
control::{BodyRotation, LookControl, MoveControl},
|
||||
farm,
|
||||
goals::{Cx, GoalSelector},
|
||||
hostile,
|
||||
nav::Navigation,
|
||||
path::{PATH_TYPES, Path},
|
||||
undead,
|
||||
};
|
||||
use crate::blocks::Fluid;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ai {
|
||||
pub goals: GoalSelector,
|
||||
pub targets: GoalSelector,
|
||||
pub nav: Navigation,
|
||||
pub mov: MoveControl,
|
||||
pub look: LookControl,
|
||||
pub body: BodyRotation,
|
||||
/// JumpControl.jump (requested this tick).
|
||||
pub jump: bool,
|
||||
/// LivingEntity.jumping
|
||||
pub jumping: bool,
|
||||
pub no_jump_delay: i32,
|
||||
pub xxa: f32,
|
||||
pub yya: f32,
|
||||
pub zza: f32,
|
||||
pub speed: f32,
|
||||
pub target: Option<Who>,
|
||||
pub last_hurt_by: Option<Who>,
|
||||
pub last_hurt_by_time: i32,
|
||||
/// Ticks left during which kills count as player kills.
|
||||
pub last_hurt_by_player: i32,
|
||||
pub no_action_time: i32,
|
||||
pub aggressive: bool,
|
||||
pub panicking: bool,
|
||||
pub malus: [Option<f32>; PATH_TYPES],
|
||||
/// A path computed in canUse and consumed by start.
|
||||
pub pending_path: Option<Path>,
|
||||
/// Sensing: line-of-sight results cached for one tick.
|
||||
pub seen_cache: Vec<(Who, bool)>,
|
||||
/// Swing animation progress (attackAnim) and ticks.
|
||||
pub swing_time: i32,
|
||||
pub swinging: bool,
|
||||
}
|
||||
impl Mob {
|
||||
/// LivingEntity.swing
|
||||
pub fn swing(&mut self) {
|
||||
if !self.ai.swinging || self.ai.swing_time >= 3 || self.ai.swing_time < 0 {
|
||||
self.ai.swing_time = -1;
|
||||
self.ai.swinging = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn register(m: &mut Mob) {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
S::Pig | S::Cow | S::Mooshroom | S::Sheep | S::Chicken => farm::register(m),
|
||||
S::Zombie
|
||||
| S::Husk
|
||||
| S::Drowned
|
||||
| S::ZombieVillager
|
||||
| S::Skeleton
|
||||
| S::Stray
|
||||
| S::Bogged
|
||||
| S::WitherSkeleton => undead::register(m),
|
||||
S::Creeper | S::Spider | S::CaveSpider => hostile::register(m),
|
||||
_ => generic(m),
|
||||
}
|
||||
}
|
||||
/// A fallback for species without bespoke goals yet: animals stroll and
|
||||
/// panic, monsters hunt the player in melee.
|
||||
fn generic(m: &mut Mob) {
|
||||
use super::goals::*;
|
||||
let hostile = m.hostile();
|
||||
let g = &mut m.ai.goals;
|
||||
if hostile {
|
||||
g.add(1, Float);
|
||||
g.add(2, MeleeAttack::new(1.0, false));
|
||||
g.add(5, Stroll::avoiding_water(0.8));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
g.add(6, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
m.ai.targets.add(2, NearestTarget::player(true));
|
||||
} else {
|
||||
g.add(0, Float);
|
||||
g.add(1, Panic::new(1.25));
|
||||
g.add(5, Stroll::avoiding_water(1.0));
|
||||
g.add(6, LookAtPlayer::new(6.0));
|
||||
g.add(7, RandomLookAround::default());
|
||||
}
|
||||
}
|
||||
/// One full entity tick. Returns false when the mob is gone.
|
||||
pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
if m.removed {
|
||||
return false;
|
||||
}
|
||||
m.previous = m.position;
|
||||
m.previous_yaw = m.yaw;
|
||||
m.previous_body_yaw = m.body_yaw;
|
||||
m.previous_head_yaw = m.head_yaw;
|
||||
m.previous_head_pitch = m.head_pitch;
|
||||
m.previous_swell = m.swell;
|
||||
m.anim.begin_tick();
|
||||
m.age += 1;
|
||||
m.ai.seen_cache.clear();
|
||||
if m.ai.last_hurt_by_player > 0 {
|
||||
m.ai.last_hurt_by_player -= 1;
|
||||
}
|
||||
// Mob.tick pre-update hooks (Creeper.tick swells before super.tick).
|
||||
match m.species() {
|
||||
Species::Creeper => hostile::creeper_tick(m, events),
|
||||
_ => {}
|
||||
}
|
||||
if m.removed {
|
||||
return false;
|
||||
}
|
||||
base_tick(m, w, events);
|
||||
if m.death_time >= 20 {
|
||||
return false;
|
||||
}
|
||||
ai_step(m, w, events);
|
||||
// Mob.tickHeadTurn -> BodyRotationControl.clientTick
|
||||
if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
m.update_walk_animation();
|
||||
m.anim.end_tick(m.ai.swinging);
|
||||
tick_swing(m);
|
||||
if !m.alive() {
|
||||
return true;
|
||||
}
|
||||
if !check_despawn(m, w) {
|
||||
m.removed = true;
|
||||
return false;
|
||||
}
|
||||
m.position.y > -128.0
|
||||
}
|
||||
/// LivingEntity.updateSwingTime (6-tick swing duration).
|
||||
fn tick_swing(m: &mut Mob) {
|
||||
if m.ai.swinging {
|
||||
m.ai.swing_time += 1;
|
||||
if m.ai.swing_time >= 6 {
|
||||
m.ai.swing_time = 0;
|
||||
m.ai.swinging = false;
|
||||
}
|
||||
} else {
|
||||
m.ai.swing_time = 0;
|
||||
}
|
||||
m.anim.attack_anim = m.ai.swing_time as f32 / 6.0;
|
||||
}
|
||||
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
|
||||
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.fluids = w.fluids(m.bounds(), m.eye_y());
|
||||
// Fire: water extinguishes, lava ignites, burning hurts every second.
|
||||
if m.fluids.in_water && m.fire_ticks > 0 {
|
||||
m.fire_ticks = 0;
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.generic.extinguish_fire",
|
||||
m.center(),
|
||||
0.7,
|
||||
1.6 + (m.random.next_float() - m.random.next_float()) * 0.4,
|
||||
));
|
||||
}
|
||||
if m.fluids.in_lava && !m.kind.flags.fire_immune {
|
||||
m.fire_ticks = m.fire_ticks.max(300);
|
||||
m.damage(4.0, Damage::of(DamageKind::Lava));
|
||||
}
|
||||
if m.fire_ticks > 0 {
|
||||
if m.kind.flags.fire_immune {
|
||||
m.fire_ticks = (m.fire_ticks - 4).max(0);
|
||||
} else {
|
||||
if m.fire_ticks % 20 == 0 && !m.fluids.in_lava {
|
||||
m.damage(1.0, Damage::of(DamageKind::OnFire));
|
||||
}
|
||||
m.fire_ticks -= 1;
|
||||
}
|
||||
}
|
||||
if m.alive() {
|
||||
// LivingEntity.baseTick: suffocation inside full blocks.
|
||||
let (ex, ey, ez) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.eye_y().floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
let at_eye = w.facts.get(w.world.block(ex, ey, ez));
|
||||
if at_eye.full_collision && at_eye.solid_render && m.width() < 1.0 {
|
||||
m.damage(1.0, Damage::of(DamageKind::InWall));
|
||||
}
|
||||
// Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs).
|
||||
if m.kind.flags.needs_water {
|
||||
if !m.fluids.in_water {
|
||||
m.air -= 1;
|
||||
if m.air == -20 {
|
||||
m.air = 0;
|
||||
m.damage(2.0, Damage::of(DamageKind::Drown));
|
||||
}
|
||||
} else {
|
||||
m.air = 300;
|
||||
}
|
||||
} else if m.fluids.eye_in_water && !m.kind.flags.breathes_water {
|
||||
m.air -= 1;
|
||||
if m.air == -20 {
|
||||
m.air = 0;
|
||||
m.damage(2.0, Damage::of(DamageKind::Drown));
|
||||
}
|
||||
} else if m.air < 300 {
|
||||
m.air = (m.air + 4).min(300);
|
||||
}
|
||||
if m.kind.flags.water_sensitive
|
||||
&& (m.fluids.in_water || w.raining && w.can_see_sky(ex, ey, ez))
|
||||
{
|
||||
m.damage(1.0, Damage::of(DamageKind::Drown));
|
||||
}
|
||||
}
|
||||
if m.hurt_time > 0 {
|
||||
m.hurt_time -= 1;
|
||||
}
|
||||
if m.invulnerable > 0 {
|
||||
m.invulnerable -= 1;
|
||||
}
|
||||
if !m.alive() {
|
||||
m.death_time += 1;
|
||||
}
|
||||
// Mob.baseTick: ambient sounds.
|
||||
if m.alive() {
|
||||
let roll = m.random.next_int_bound(1000).unwrap_or(999);
|
||||
let t = m.ambient_timer;
|
||||
m.ambient_timer += 1;
|
||||
if roll < t {
|
||||
m.ambient_timer = -m.kind.ambient_interval;
|
||||
play_ambient(m, w, events);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let sound = match m.species() {
|
||||
Species::Zombie | Species::Husk if m.is_baby() => m.kind.sounds[0],
|
||||
Species::Drowned if m.fluids.in_water => "entity.drowned.ambient_water",
|
||||
Species::Enderman if m.ai.target.is_some() => "entity.enderman.scream",
|
||||
Species::Wolf if m.ai.target.is_some() => "entity.wolf.growl",
|
||||
Species::Wolf if m.random.next_int_bound(3).unwrap_or(1) == 0 => {
|
||||
if m.extra.tame && m.health < m.kind.max_health / 2.0 {
|
||||
"entity.wolf.whine"
|
||||
} else {
|
||||
"entity.wolf.pant"
|
||||
}
|
||||
}
|
||||
Species::Cat if m.extra.tame && m.extra.in_love > 0 => "entity.cat.purr",
|
||||
Species::Cat if !m.extra.tame => "entity.cat.stray_ambient",
|
||||
Species::PolarBear if m.is_baby() => "entity.polar_bear.ambient_baby",
|
||||
Species::Dolphin if !m.fluids.in_water => "entity.dolphin.ambient",
|
||||
Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air",
|
||||
Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return,
|
||||
Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry",
|
||||
Species::Piglin if m.ai.target.is_some() => "entity.piglin.angry",
|
||||
Species::Hoglin if m.ai.target.is_some() => "entity.hoglin.angry",
|
||||
_ => m.kind.sounds[0],
|
||||
};
|
||||
let _ = w;
|
||||
if !sound.is_empty() {
|
||||
m.voice(sound, events);
|
||||
}
|
||||
}
|
||||
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
|
||||
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if m.ai.no_jump_delay > 0 {
|
||||
m.ai.no_jump_delay -= 1;
|
||||
}
|
||||
let v = m.velocity;
|
||||
m.velocity = Vec3::new(
|
||||
if v.x.abs() < 0.003 { 0.0 } else { v.x },
|
||||
if v.y.abs() < 0.003 { 0.0 } else { v.y },
|
||||
if v.z.abs() < 0.003 { 0.0 } else { v.z },
|
||||
);
|
||||
m.ai.xxa *= 0.98;
|
||||
m.ai.zza *= 0.98;
|
||||
if m.alive() {
|
||||
server_ai_step(m, w, events);
|
||||
} else {
|
||||
m.ai.jumping = false;
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
}
|
||||
m.handle_jumping();
|
||||
let input = Vec3::new(
|
||||
f64::from(m.ai.xxa),
|
||||
f64::from(m.ai.yya),
|
||||
f64::from(m.ai.zza),
|
||||
);
|
||||
m.travel(w, input, events);
|
||||
// Spider.tick: climbing while pressed against a wall.
|
||||
if m.kind.flags.climber {
|
||||
m.climbing = m.horizontal_collision;
|
||||
}
|
||||
// AgeableMob.aiStep
|
||||
if m.alive() {
|
||||
if m.extra.age < 0 {
|
||||
m.extra.age += 1;
|
||||
} else if m.extra.age > 0 {
|
||||
m.extra.age -= 1;
|
||||
}
|
||||
// Animal.aiStep
|
||||
if m.extra.age != 0 {
|
||||
m.extra.in_love = 0;
|
||||
}
|
||||
if m.extra.in_love > 0 {
|
||||
m.extra.in_love -= 1;
|
||||
if m.extra.in_love % 10 == 0 {
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at: [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) + 0.5,
|
||||
m.position.z,
|
||||
],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mob.aiStep: undead burn in daylight.
|
||||
if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) {
|
||||
if m.extra.head.is_none() {
|
||||
m.fire_ticks = m.fire_ticks.max(160);
|
||||
}
|
||||
}
|
||||
species_ai_step(m, w, events);
|
||||
}
|
||||
fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if !w.daylight || w.nether {
|
||||
return false;
|
||||
}
|
||||
let (x, y, z) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.eye_y().floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
let br = w.brightness(x, y, z);
|
||||
let wet = m.fluids.in_water || w.raining && w.can_see_sky(x, y, z);
|
||||
br > 0.5 && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 && !wet && w.can_see_sky(x, y, z)
|
||||
}
|
||||
/// Mob.serverAiStep
|
||||
fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.ai.no_action_time += 1;
|
||||
let tick_count = m.age as i64;
|
||||
let id_based = tick_count + i64::from(m.id);
|
||||
let mut targets = std::mem::take(&mut m.ai.targets);
|
||||
let mut goals = std::mem::take(&mut m.ai.goals);
|
||||
{
|
||||
let mut cx = Cx { w, events };
|
||||
if id_based % 2 != 0 && tick_count > 1 {
|
||||
targets.tick_running(m, &mut cx, false);
|
||||
goals.tick_running(m, &mut cx, false);
|
||||
} else {
|
||||
targets.tick(m, &mut cx);
|
||||
goals.tick(m, &mut cx);
|
||||
}
|
||||
}
|
||||
m.ai.targets = targets;
|
||||
m.ai.goals = goals;
|
||||
m.nav_tick(w);
|
||||
{
|
||||
let mut cx = Cx { w, events };
|
||||
custom_server_ai_step(m, &mut cx);
|
||||
}
|
||||
m.move_control_tick(w);
|
||||
m.look_control_tick();
|
||||
m.jump_control_tick();
|
||||
}
|
||||
fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
match m.species() {
|
||||
Species::Sheep => {}
|
||||
Species::Zombie
|
||||
| Species::Husk
|
||||
| Species::Drowned
|
||||
| Species::ZombieVillager
|
||||
| Species::Skeleton
|
||||
| Species::Stray
|
||||
| Species::Bogged
|
||||
| Species::WitherSkeleton => undead::custom_server_ai_step(m, cx),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
match m.species() {
|
||||
Species::Chicken => farm::chicken_ai_step(m, w, events),
|
||||
Species::Sheep => {
|
||||
if m.extra.anim_ticks > 0 {
|
||||
m.extra.anim_ticks -= 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Mob.checkDespawn (players are the only despawn reference).
|
||||
fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
let creature = m.kind.category == "creature";
|
||||
if m.persistent || creature && m.kind.flags.animal {
|
||||
m.ai.no_action_time = 0;
|
||||
return true;
|
||||
}
|
||||
let Some(p) = &w.player else { return true };
|
||||
let d = m.distance_sqr(p.position);
|
||||
let despawn = if m.kind.category == "water_ambient" {
|
||||
64.0
|
||||
} else {
|
||||
128.0
|
||||
};
|
||||
if d > despawn * despawn {
|
||||
return false;
|
||||
}
|
||||
if m.ai.no_action_time > 600
|
||||
&& m.random.next_int_bound(800).unwrap_or(1) == 0
|
||||
&& d > 32.0 * 32.0
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if d < 32.0 * 32.0 {
|
||||
m.ai.no_action_time = 0;
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Movement speed bonus multiplier (baby zombies are 50% faster, etc.).
|
||||
pub fn speed_bonus(m: &Mob) -> f64 {
|
||||
match m.species() {
|
||||
Species::Zombie
|
||||
| Species::Husk
|
||||
| Species::Drowned
|
||||
| Species::ZombieVillager
|
||||
| Species::ZombifiedPiglin
|
||||
| Species::Piglin
|
||||
if m.is_baby() =>
|
||||
{
|
||||
1.5
|
||||
}
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
pub fn sound_volume(m: &Mob) -> f32 {
|
||||
match m.species() {
|
||||
Species::Ghast => 5.0,
|
||||
Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32,
|
||||
Species::Cod
|
||||
| Species::Salmon
|
||||
| Species::TropicalFish
|
||||
| Species::Pufferfish
|
||||
| Species::Bat => 0.1,
|
||||
Species::Squid | Species::GlowSquid => 0.4,
|
||||
Species::Horse | Species::Donkey | Species::Mule => 0.8,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
/// PathfinderMob.getWalkTargetValue (Animal and Monster overrides).
|
||||
pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
let light = || w.brightness(p[0], p[1], p[2]) - 0.5;
|
||||
if m.hostile()
|
||||
&& !matches!(
|
||||
m.species(),
|
||||
Species::Slime | Species::MagmaCube | Species::Ghast | Species::Phantom
|
||||
)
|
||||
{
|
||||
return -light();
|
||||
}
|
||||
if m.kind.flags.animal {
|
||||
if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:grass_block" {
|
||||
return 10.0;
|
||||
}
|
||||
return light();
|
||||
}
|
||||
0.0
|
||||
}
|
||||
/// Species damage filters (LivingEntity.hurtServer overrides).
|
||||
pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
|
||||
match m.species() {
|
||||
Species::Enderman if source.is_projectile() => false,
|
||||
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
|
||||
if source.is_fire() =>
|
||||
{
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
/// Reactions after taking damage (sounds, anger).
|
||||
pub fn after_hurt(m: &mut Mob, _source: &Damage) {
|
||||
m.ai.no_action_time = 0;
|
||||
}
|
||||
/// Mob.doHurtTarget: attack damage (+ species extras) to the target.
|
||||
pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
|
||||
let mut amount = m.kind.attack_damage;
|
||||
let from = [m.position.x, m.position.y, m.position.z];
|
||||
let source = Damage::mob(m.id, from);
|
||||
match m.species() {
|
||||
// Difficulty NORMAL: cave spiders poison for 7 seconds.
|
||||
Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
|
||||
effect: "minecraft:poison",
|
||||
ticks: 7 * 20,
|
||||
amplifier: 0,
|
||||
}),
|
||||
Species::Husk if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
|
||||
effect: "minecraft:hunger",
|
||||
ticks: 140,
|
||||
amplifier: 0,
|
||||
}),
|
||||
Species::WitherSkeleton if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
|
||||
effect: "minecraft:wither",
|
||||
ticks: 200,
|
||||
amplifier: 0,
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
if amount <= 0.0 {
|
||||
amount = 1.0;
|
||||
}
|
||||
// Zombies set their target on fire while burning (Zombie.doHurtTarget).
|
||||
if m.fire_ticks > 0 && matches!(m.species(), Species::Zombie) && m.random.next_float() < 0.3 {
|
||||
cx.events.push(MobEvent::Ignite {
|
||||
target: who,
|
||||
seconds: 2,
|
||||
});
|
||||
}
|
||||
match who {
|
||||
Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)),
|
||||
Who::Mob(id) => cx.events.push(MobEvent::AttackMob {
|
||||
target: id,
|
||||
amount,
|
||||
source,
|
||||
}),
|
||||
}
|
||||
let _ = Fluid::None;
|
||||
}
|
||||
/// Mob.ate (sheep regrow wool, babies grow).
|
||||
pub fn ate(m: &mut Mob) {
|
||||
if m.species() == Species::Sheep {
|
||||
m.extra.sheared = false;
|
||||
if m.is_baby() {
|
||||
// AgeableMob.ageUp(60)
|
||||
m.extra.age = (m.extra.age + 60 * 20).min(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Species-specific travel (fish, squid, dolphins swim with their own rules).
|
||||
pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) -> bool {
|
||||
let _ = (m, w, input, events);
|
||||
false
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Model animation: ports of each vanilla `EntityModel.setupAnim` family
|
||||
//! (quadrupeds, humanoids, creepers, spiders, chickens...) applied to a map of
|
||||
//! part poses before the model is drawn.
|
||||
use super::{Mob, Part, keyframes::AnimationState, living::wrap};
|
||||
use std::collections::HashMap;
|
||||
use std::f32::consts::PI;
|
||||
|
||||
/// The setupAnim implementation a model uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Anim {
|
||||
Quadruped,
|
||||
Sheep,
|
||||
Chicken,
|
||||
Zombie,
|
||||
Drowned,
|
||||
ZombieVillager,
|
||||
Skeleton,
|
||||
Creeper,
|
||||
Spider,
|
||||
Enderman,
|
||||
Silverfish,
|
||||
Slime,
|
||||
MagmaCube,
|
||||
Witch,
|
||||
Villager,
|
||||
IronGolem,
|
||||
SnowGolem,
|
||||
Illager,
|
||||
Piglin,
|
||||
ZombifiedPiglin,
|
||||
Hoglin,
|
||||
Wolf,
|
||||
Feline,
|
||||
Fox,
|
||||
Rabbit,
|
||||
Horse,
|
||||
Llama,
|
||||
Goat,
|
||||
Panda,
|
||||
PolarBear,
|
||||
Parrot,
|
||||
Bee,
|
||||
Turtle,
|
||||
Armadillo,
|
||||
Frog,
|
||||
Axolotl,
|
||||
Squid,
|
||||
Fish,
|
||||
Pufferfish,
|
||||
Dolphin,
|
||||
Bat,
|
||||
Phantom,
|
||||
Ghast,
|
||||
Blaze,
|
||||
Strider,
|
||||
/// The humanoid model of the earlier simple renderer.
|
||||
Humanoid {
|
||||
zombie_arms: bool,
|
||||
},
|
||||
}
|
||||
/// Client-side animation clocks advanced each tick.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AnimState {
|
||||
pub attack_anim: f32,
|
||||
pub attack_anim_o: f32,
|
||||
pub flap: f32,
|
||||
pub flap_o: f32,
|
||||
pub flap_speed: f32,
|
||||
pub flap_speed_o: f32,
|
||||
pub flapping: f32,
|
||||
/// Generic per-species keyframe animation states.
|
||||
pub states: [AnimationState; 4],
|
||||
/// Smoothed values (tail wag, interest, squid tentacles...).
|
||||
pub a: f32,
|
||||
pub a_o: f32,
|
||||
pub b: f32,
|
||||
pub b_o: f32,
|
||||
pub c: f32,
|
||||
pub c_o: f32,
|
||||
}
|
||||
impl AnimState {
|
||||
pub fn begin_tick(&mut self) {
|
||||
self.attack_anim_o = self.attack_anim;
|
||||
self.a_o = self.a;
|
||||
self.b_o = self.b;
|
||||
self.c_o = self.c;
|
||||
}
|
||||
pub fn end_tick(&mut self, _swinging: bool) {}
|
||||
}
|
||||
/// Part poses for one draw, keyed by part name.
|
||||
pub struct Poses {
|
||||
map: HashMap<String, [f32; 9]>,
|
||||
dummy: [f32; 9],
|
||||
}
|
||||
impl Poses {
|
||||
pub fn new(model: &Part) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
fn walk(p: &Part, map: &mut HashMap<String, [f32; 9]>) {
|
||||
map.insert(p.name.clone(), p.pose);
|
||||
for c in &p.children {
|
||||
walk(c, map);
|
||||
}
|
||||
}
|
||||
walk(model, &mut map);
|
||||
Self {
|
||||
map,
|
||||
dummy: [0.0; 9],
|
||||
}
|
||||
}
|
||||
pub fn get(&mut self, name: &str) -> &mut [f32; 9] {
|
||||
match self.map.get_mut(name) {
|
||||
Some(p) => p,
|
||||
None => &mut self.dummy,
|
||||
}
|
||||
}
|
||||
pub fn pose(&self, part: &Part) -> [f32; 9] {
|
||||
self.map.get(&part.name).copied().unwrap_or(part.pose)
|
||||
}
|
||||
pub fn has(&self, name: &str) -> bool {
|
||||
self.map.contains_key(name)
|
||||
}
|
||||
pub fn xrot(&mut self, n: &str, v: f32) {
|
||||
self.get(n)[3] = v;
|
||||
}
|
||||
pub fn yrot(&mut self, n: &str, v: f32) {
|
||||
self.get(n)[4] = v;
|
||||
}
|
||||
pub fn zrot(&mut self, n: &str, v: f32) {
|
||||
self.get(n)[5] = v;
|
||||
}
|
||||
pub fn visible(&mut self, n: &str, v: bool) {
|
||||
if !v {
|
||||
let p = self.get(n);
|
||||
p[6] = 0.0;
|
||||
p[7] = 0.0;
|
||||
p[8] = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The LivingEntityRenderState values setupAnim reads.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct State {
|
||||
pub pos: f32,
|
||||
pub speed: f32,
|
||||
pub age: f32,
|
||||
/// Head yaw relative to the body, degrees.
|
||||
pub y_rot: f32,
|
||||
/// Head pitch, degrees.
|
||||
pub x_rot: f32,
|
||||
pub swing: f32,
|
||||
pub baby: bool,
|
||||
pub partial: f32,
|
||||
}
|
||||
pub fn state(m: &Mob, alpha: f32) -> State {
|
||||
let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha;
|
||||
let head = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha;
|
||||
let mut swing = m.anim.attack_anim - m.anim.attack_anim_o;
|
||||
if swing < 0.0 {
|
||||
swing += 1.0;
|
||||
}
|
||||
let swing = m.anim.attack_anim_o + swing * alpha;
|
||||
let alive = m.alive();
|
||||
State {
|
||||
pos: if alive {
|
||||
m.limb_position - m.limb_speed * (1.0 - alpha)
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
speed: if alive {
|
||||
(m.previous_limb_speed + (m.limb_speed - m.previous_limb_speed) * alpha).min(1.0)
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
age: m.age as f32 + alpha,
|
||||
y_rot: wrap(head - body),
|
||||
x_rot: m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha,
|
||||
swing,
|
||||
baby: m.is_baby(),
|
||||
partial: alpha,
|
||||
}
|
||||
}
|
||||
fn head(p: &mut Poses, s: &State) {
|
||||
p.xrot("head", s.x_rot.to_radians());
|
||||
p.yrot("head", s.y_rot.to_radians());
|
||||
}
|
||||
/// QuadrupedModel.setupAnim
|
||||
fn quadruped(p: &mut Poses, s: &State) {
|
||||
head(p, s);
|
||||
let (pos, sp) = (s.pos, s.speed);
|
||||
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp);
|
||||
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
|
||||
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
|
||||
p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * sp);
|
||||
}
|
||||
/// AnimationUtils.bobModelPart
|
||||
fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) {
|
||||
let q = p.get(n);
|
||||
q[5] += scale * ((age * 0.09).cos() * 0.05 + 0.05);
|
||||
q[3] += scale * ((age * 0.067).sin() * 0.05);
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ArmPose {
|
||||
Empty,
|
||||
Item,
|
||||
Bow,
|
||||
CrossbowHold,
|
||||
CrossbowCharge,
|
||||
}
|
||||
/// HumanoidModel.setupAnim up to (and including) the attack animation hook.
|
||||
fn humanoid(
|
||||
p: &mut Poses,
|
||||
s: &State,
|
||||
right: ArmPose,
|
||||
left: ArmPose,
|
||||
zombie: Option<bool>,
|
||||
holding: bool,
|
||||
) {
|
||||
head(p, s);
|
||||
let (pos, sp) = (s.pos, s.speed);
|
||||
p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5);
|
||||
p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5);
|
||||
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp);
|
||||
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
|
||||
p.yrot("right_leg", 0.005);
|
||||
p.yrot("left_leg", -0.005);
|
||||
p.zrot("right_leg", 0.005);
|
||||
p.zrot("left_leg", -0.005);
|
||||
let (hx, hy) = (p.get("head")[3], p.get("head")[4]);
|
||||
for (arm, pose) in [("right_arm", right), ("left_arm", left)] {
|
||||
match pose {
|
||||
ArmPose::Empty => p.yrot(arm, 0.0),
|
||||
ArmPose::Item => {
|
||||
let x = p.get(arm)[3];
|
||||
p.xrot(arm, x * 0.5 - PI / 10.0);
|
||||
p.yrot(arm, 0.0);
|
||||
}
|
||||
ArmPose::Bow => {
|
||||
let right_main = arm == "right_arm";
|
||||
p.yrot("right_arm", -0.1 + hy - if right_main { 0.0 } else { 0.4 });
|
||||
p.yrot("left_arm", 0.1 + hy + if right_main { 0.4 } else { 0.0 });
|
||||
p.xrot("right_arm", -PI / 2.0 + hx);
|
||||
p.xrot("left_arm", -PI / 2.0 + hx);
|
||||
}
|
||||
ArmPose::CrossbowHold => {
|
||||
let r = arm == "right_arm";
|
||||
let (hold, shoot) = if r {
|
||||
("right_arm", "left_arm")
|
||||
} else {
|
||||
("left_arm", "right_arm")
|
||||
};
|
||||
p.yrot(hold, if r { -0.3 } else { 0.3 } + hy);
|
||||
p.yrot(shoot, if r { 0.6 } else { -0.6 } + hy);
|
||||
p.xrot(hold, -PI / 2.0 + hx + 0.1);
|
||||
p.xrot(shoot, -1.5 + hx);
|
||||
}
|
||||
ArmPose::CrossbowCharge => {
|
||||
let r = arm == "right_arm";
|
||||
let (hold, pull) = if r {
|
||||
("right_arm", "left_arm")
|
||||
} else {
|
||||
("left_arm", "right_arm")
|
||||
};
|
||||
p.yrot(hold, if r { -0.8 } else { 0.8 });
|
||||
p.xrot(hold, -0.970_796_35);
|
||||
p.xrot(pull, -0.970_796_35);
|
||||
p.yrot(pull, 0.6 * if r { 1.0 } else { -1.0 });
|
||||
p.xrot(pull, -PI / 2.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// setupAttackAnimation (WHACK swing with the right arm).
|
||||
let swing = s.swing;
|
||||
if swing > 0.0 {
|
||||
let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2;
|
||||
p.yrot("body", body_y);
|
||||
let age_scale = if s.baby { 0.5 } else { 1.0 };
|
||||
{
|
||||
let r = p.get("right_arm");
|
||||
r[2] = body_y.sin() * 5.0 * age_scale;
|
||||
r[0] = -body_y.cos() * 5.0 * age_scale;
|
||||
}
|
||||
{
|
||||
let l = p.get("left_arm");
|
||||
l[2] = -body_y.sin() * 5.0 * age_scale;
|
||||
l[0] = body_y.cos() * 5.0 * age_scale;
|
||||
}
|
||||
p.get("right_arm")[4] += body_y;
|
||||
p.get("left_arm")[4] += body_y;
|
||||
p.get("left_arm")[3] += body_y;
|
||||
let eased = 1.0 - (1.0 - swing).powi(4);
|
||||
let aa = (eased * PI).sin();
|
||||
let bb = (swing * PI).sin() * -(hx - 0.7) * 0.75;
|
||||
let r = p.get("right_arm");
|
||||
r[3] -= aa * 1.2 + bb;
|
||||
r[4] += body_y * 2.0;
|
||||
r[5] += (swing * PI).sin() * -0.4;
|
||||
}
|
||||
if let Some(aggressive) = zombie {
|
||||
// AnimationUtils.animateZombieArms
|
||||
let raise = !s.baby || !holding;
|
||||
let drop = if raise {
|
||||
-PI / if aggressive { 1.5 } else { 2.25 }
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).sin();
|
||||
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
|
||||
let x = drop + ym * 1.2 - xm * 0.4;
|
||||
let y = 0.1 - ym * 0.6;
|
||||
p.xrot("right_arm", x);
|
||||
p.yrot("right_arm", if raise { -y } else { y });
|
||||
p.zrot("right_arm", 0.0);
|
||||
p.xrot("left_arm", x);
|
||||
p.yrot("left_arm", if raise { y } else { -y });
|
||||
p.zrot("left_arm", 0.0);
|
||||
}
|
||||
bob(p, "right_arm", s.age, 1.0);
|
||||
bob(p, "left_arm", s.age, -1.0);
|
||||
}
|
||||
/// Apply the mob's model animation to `p`.
|
||||
pub fn setup(
|
||||
m: &Mob,
|
||||
s: &State,
|
||||
p: &mut Poses,
|
||||
w_anims: &HashMap<String, super::keyframes::Animation>,
|
||||
) {
|
||||
let _ = w_anims;
|
||||
match m.kind.anim {
|
||||
Anim::Quadruped | Anim::PolarBear | Anim::Panda | Anim::Goat => quadruped(p, s),
|
||||
Anim::Sheep => {
|
||||
quadruped(p, s);
|
||||
// SheepModel: lower the head while eating grass.
|
||||
let t = m.extra.anim_ticks;
|
||||
let partial = s.partial;
|
||||
let pos_scale = if t <= 0 {
|
||||
0.0
|
||||
} else if (4..=36).contains(&t) {
|
||||
1.0
|
||||
} else if t < 4 {
|
||||
(t as f32 - partial) / 4.0
|
||||
} else {
|
||||
-((t - 40) as f32 - partial) / 4.0
|
||||
};
|
||||
let angle = if t > 4 && t <= 36 {
|
||||
let f = ((t - 4) as f32 - partial) / 32.0;
|
||||
PI / 5.0 + 0.219_911_49 * (f * 28.7).sin()
|
||||
} else if t > 0 {
|
||||
PI / 5.0
|
||||
} else {
|
||||
s.x_rot.to_radians()
|
||||
};
|
||||
let age_scale = if s.baby { 0.5 } else { 1.0 };
|
||||
p.get("head")[1] += pos_scale * 9.0 * age_scale;
|
||||
p.xrot("head", angle);
|
||||
}
|
||||
Anim::Chicken => {
|
||||
let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial;
|
||||
let flap_speed =
|
||||
m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial;
|
||||
let angle = (flap.sin() + 1.0) * flap_speed;
|
||||
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
|
||||
p.xrot("left_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
|
||||
p.zrot("right_wing", angle);
|
||||
p.zrot("left_wing", -angle);
|
||||
if !s.baby {
|
||||
head(p, s);
|
||||
}
|
||||
}
|
||||
Anim::Zombie
|
||||
| Anim::Drowned
|
||||
| Anim::ZombieVillager
|
||||
| Anim::ZombifiedPiglin
|
||||
| Anim::Humanoid { zombie_arms: true } => {
|
||||
let holding = m.extra.main_hand.is_some();
|
||||
let right = if holding {
|
||||
ArmPose::Item
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
humanoid(p, s, right, ArmPose::Empty, Some(m.ai.aggressive), holding);
|
||||
}
|
||||
Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => {
|
||||
let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow");
|
||||
let right = if bow && m.ai.aggressive {
|
||||
ArmPose::Bow
|
||||
} else if m.extra.main_hand.is_some() {
|
||||
ArmPose::Item
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
humanoid(
|
||||
p,
|
||||
s,
|
||||
right,
|
||||
ArmPose::Empty,
|
||||
None,
|
||||
m.extra.main_hand.is_some(),
|
||||
);
|
||||
if m.ai.aggressive && !bow {
|
||||
// SkeletonModel melee pose.
|
||||
let sw = s.swing;
|
||||
let s2 = (sw * PI).sin();
|
||||
let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).sin();
|
||||
p.zrot("right_arm", 0.0);
|
||||
p.zrot("left_arm", 0.0);
|
||||
p.yrot("right_arm", -(0.1 - s2 * 0.6));
|
||||
p.yrot("left_arm", 0.1 - s2 * 0.6);
|
||||
p.xrot("right_arm", -PI / 2.0 - (s2 * 1.2 - s1 * 0.4));
|
||||
p.xrot("left_arm", -PI / 2.0 - (s2 * 1.2 - s1 * 0.4));
|
||||
bob(p, "right_arm", s.age, 1.0);
|
||||
bob(p, "left_arm", s.age, -1.0);
|
||||
}
|
||||
}
|
||||
Anim::Creeper => {
|
||||
head(p, s);
|
||||
p.xrot("right_hind_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
|
||||
p.xrot("left_hind_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
|
||||
p.xrot(
|
||||
"right_front_leg",
|
||||
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed,
|
||||
);
|
||||
p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
|
||||
}
|
||||
Anim::Spider => {
|
||||
head(p, s);
|
||||
let pos = s.pos * 0.6662;
|
||||
let sp = s.speed;
|
||||
let swing = |o: f32| -((pos * 2.0 + o).cos() * 0.4) * sp;
|
||||
let step = |o: f32| ((pos + o).sin() * 0.4).abs() * sp;
|
||||
let legs = [
|
||||
("hind", 0.0f32, 0.0f32),
|
||||
("middle_hind", PI, PI),
|
||||
("middle_front", PI / 2.0, PI / 2.0),
|
||||
("front", PI * 3.0 / 2.0, PI * 3.0 / 2.0),
|
||||
];
|
||||
for (n, so, to) in legs {
|
||||
let (sw, st) = (swing(so), step(to));
|
||||
p.get(&format!("right_{n}_leg"))[4] += sw;
|
||||
p.get(&format!("left_{n}_leg"))[4] -= sw;
|
||||
p.get(&format!("right_{n}_leg"))[5] += st;
|
||||
p.get(&format!("left_{n}_leg"))[5] -= st;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if p.has("head") {
|
||||
head(p, s);
|
||||
}
|
||||
if p.has("right_hind_leg") {
|
||||
quadruped(p, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
//! Mob controls: `MoveControl` (with the flying and smooth-swimming
|
||||
//! variants), `LookControl`, `JumpControl` and `BodyRotationControl`.
|
||||
use super::{Mob, MobWorld, living::wrap};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Operation {
|
||||
#[default]
|
||||
Wait,
|
||||
MoveTo,
|
||||
Strafe,
|
||||
Jumping,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub enum MoveKind {
|
||||
#[default]
|
||||
Ground,
|
||||
/// FlyingMoveControl(maxTurn, hoversInPlace)
|
||||
Flying { max_turn: f32, hovers: bool },
|
||||
/// SmoothSwimmingMoveControl(maxTurnX, maxTurnY, inWater, outsideWater, applyGravity)
|
||||
SmoothSwimming {
|
||||
max_turn_x: f32,
|
||||
max_turn_y: f32,
|
||||
in_water: f32,
|
||||
outside: f32,
|
||||
gravity: bool,
|
||||
},
|
||||
/// Goals drive the mob directly (slimes, ghasts, squid, fish, bats, phantoms).
|
||||
Custom,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct MoveControl {
|
||||
pub kind: MoveKind,
|
||||
pub wanted: [f64; 3],
|
||||
pub speed_modifier: f64,
|
||||
pub strafe_forwards: f32,
|
||||
pub strafe_right: f32,
|
||||
pub operation: Operation,
|
||||
}
|
||||
impl MoveControl {
|
||||
pub fn has_wanted(&self) -> bool {
|
||||
self.operation == Operation::MoveTo
|
||||
}
|
||||
pub fn set_wanted(&mut self, x: f64, y: f64, z: f64, speed: f64) {
|
||||
self.wanted = [x, y, z];
|
||||
self.speed_modifier = speed;
|
||||
if self.operation != Operation::Jumping {
|
||||
self.operation = Operation::MoveTo;
|
||||
}
|
||||
}
|
||||
pub fn strafe(&mut self, forwards: f32, right: f32) {
|
||||
self.operation = Operation::Strafe;
|
||||
self.strafe_forwards = forwards;
|
||||
self.strafe_right = right;
|
||||
self.speed_modifier = 0.25;
|
||||
}
|
||||
}
|
||||
/// MoveControl.rotlerp: turn at most `max` degrees, result in [0, 360].
|
||||
pub fn rotlerp(a: f32, b: f32, max: f32) -> f32 {
|
||||
let diff = wrap(b - a).clamp(-max, max);
|
||||
let mut r = a + diff;
|
||||
if r < 0.0 {
|
||||
r += 360.0;
|
||||
} else if r > 360.0 {
|
||||
r -= 360.0;
|
||||
}
|
||||
r
|
||||
}
|
||||
/// Control.rotateTowards.
|
||||
pub fn rotate_towards(from: f32, to: f32, max: f32) -> f32 {
|
||||
from + wrap(to - from).clamp(-max, max)
|
||||
}
|
||||
/// Mth.rotateIfNecessary.
|
||||
pub fn rotate_if_necessary(base: f32, target: f32, max: f32) -> f32 {
|
||||
let d = wrap(target - base).clamp(-max, max);
|
||||
target - d
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Default)]
|
||||
pub enum LookKind {
|
||||
#[default]
|
||||
Default,
|
||||
/// SmoothSwimmingLookControl(maxYRotFromCenter)
|
||||
SmoothSwimming(f32),
|
||||
/// Look controls that never reset pitch (e.g. ghasts keep their own).
|
||||
Fixed,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LookControl {
|
||||
pub kind: LookKind,
|
||||
pub wanted: [f64; 3],
|
||||
pub y_max_rot_speed: f32,
|
||||
pub x_max_rot_angle: f32,
|
||||
pub cooldown: i32,
|
||||
}
|
||||
impl LookControl {
|
||||
pub fn set_look_at(&mut self, at: [f64; 3], y_speed: f32, x_max: f32) {
|
||||
self.wanted = at;
|
||||
self.y_max_rot_speed = y_speed;
|
||||
self.x_max_rot_angle = x_max;
|
||||
self.cooldown = 2;
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct BodyRotation {
|
||||
head_stable_time: i32,
|
||||
last_stable_head: f32,
|
||||
}
|
||||
impl Mob {
|
||||
pub fn look_at(&mut self, at: [f64; 3]) {
|
||||
let (y, x) = (self.kind.head_rot_speed, self.kind.max_head_x_rot);
|
||||
self.ai.look.set_look_at(at, y, x);
|
||||
}
|
||||
pub fn look_at_speed(&mut self, at: [f64; 3], y_speed: f32, x_max: f32) {
|
||||
self.ai.look.set_look_at(at, y_speed, x_max);
|
||||
}
|
||||
/// Mob.lookAt(entity, yMax, xMax): rotate the body yaw/pitch directly.
|
||||
pub fn turn_to(&mut self, at: [f64; 3], y_max: f32, x_max: f32) {
|
||||
let (dx, dz) = (at[0] - self.position.x, at[2] - self.position.z);
|
||||
let dy = at[1] - self.eye_y();
|
||||
let sd = (dx * dx + dz * dz).sqrt();
|
||||
let y_rot = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let x_rot = -(dy.atan2(sd).to_degrees() as f32);
|
||||
self.head_pitch = rotate_toward_max(self.head_pitch, x_rot, x_max);
|
||||
self.yaw = rotate_toward_max(self.yaw, y_rot, y_max);
|
||||
}
|
||||
/// MoveControl.tick (and the flying / smooth-swimming variants).
|
||||
pub fn move_control_tick(&mut self, w: &MobWorld) {
|
||||
let attr_speed = self.kind.speed * self.speed_bonus();
|
||||
match self.ai.mov.kind {
|
||||
MoveKind::Custom => {}
|
||||
MoveKind::Ground => self.ground_move_tick(w, attr_speed),
|
||||
MoveKind::Flying { max_turn, hovers } => {
|
||||
let m = &mut self.ai.mov;
|
||||
if m.operation == Operation::MoveTo {
|
||||
m.operation = Operation::Wait;
|
||||
self.no_gravity = true;
|
||||
let [wx, wy, wz] = self.ai.mov.wanted;
|
||||
let (xd, yd, zd) = (
|
||||
wx - self.position.x,
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
self.ai.yya = 0.0;
|
||||
self.ai.zza = 0.0;
|
||||
return;
|
||||
}
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, 90.0);
|
||||
let speed = (self.ai.mov.speed_modifier
|
||||
* if self.on_ground {
|
||||
attr_speed
|
||||
} else {
|
||||
self.kind.flying_speed
|
||||
}) as f32;
|
||||
self.set_speed(speed);
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 {
|
||||
let x_rot = -(yd.atan2(sd).to_degrees() as f32);
|
||||
self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn);
|
||||
self.ai.yya = if yd > 0.0 { speed } else { -speed };
|
||||
}
|
||||
} else {
|
||||
if !hovers {
|
||||
self.no_gravity = false;
|
||||
}
|
||||
self.ai.yya = 0.0;
|
||||
self.ai.zza = 0.0;
|
||||
}
|
||||
}
|
||||
MoveKind::SmoothSwimming {
|
||||
max_turn_x,
|
||||
max_turn_y,
|
||||
in_water,
|
||||
outside,
|
||||
gravity,
|
||||
} => {
|
||||
if gravity && self.fluids.in_water {
|
||||
self.velocity.y += 0.005;
|
||||
}
|
||||
if self.ai.mov.operation == Operation::MoveTo && !self.ai.nav.is_done() {
|
||||
let [wx, wy, wz] = self.ai.mov.wanted;
|
||||
let (xd, yd, zd) = (
|
||||
wx - self.position.x,
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
self.ai.zza = 0.0;
|
||||
} else {
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, max_turn_y);
|
||||
self.body_yaw = self.yaw;
|
||||
self.head_yaw = self.yaw;
|
||||
let speed = (self.ai.mov.speed_modifier * attr_speed) as f32;
|
||||
if self.fluids.in_water {
|
||||
self.ai.speed = speed * in_water;
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 {
|
||||
let x_rot = -(yd.atan2(sd).to_degrees() as f32);
|
||||
let x_rot = wrap(x_rot).clamp(-max_turn_x, max_turn_x);
|
||||
self.head_pitch = rotate_towards(self.head_pitch, x_rot, 5.0);
|
||||
}
|
||||
let (c, s) = (
|
||||
self.head_pitch.to_radians().cos(),
|
||||
self.head_pitch.to_radians().sin(),
|
||||
);
|
||||
self.ai.zza = c * speed;
|
||||
self.ai.yya = -s * speed;
|
||||
} else {
|
||||
let left = wrap(self.yaw - y_rot).abs();
|
||||
let factor = 1.0 - ((left - 10.0) / 50.0).clamp(0.0, 1.0);
|
||||
self.set_speed(speed * outside * factor);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.ai.speed = 0.0;
|
||||
self.ai.xxa = 0.0;
|
||||
self.ai.yya = 0.0;
|
||||
self.ai.zza = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mob.setSpeed also sets the forward input.
|
||||
pub fn set_speed(&mut self, speed: f32) {
|
||||
self.ai.speed = speed;
|
||||
self.ai.zza = speed;
|
||||
}
|
||||
fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) {
|
||||
match self.ai.mov.operation {
|
||||
Operation::Strafe => {
|
||||
let speed = (self.ai.mov.speed_modifier * attr_speed) as f32;
|
||||
let (mut xa, mut za) = (self.ai.mov.strafe_forwards, self.ai.mov.strafe_right);
|
||||
let mut dist = (xa * xa + za * za).sqrt();
|
||||
if dist < 1.0 {
|
||||
dist = 1.0;
|
||||
}
|
||||
dist = speed / dist;
|
||||
xa *= dist;
|
||||
za *= dist;
|
||||
let (s, c) = (self.yaw.to_radians().sin(), self.yaw.to_radians().cos());
|
||||
let dx = xa * c - za * s;
|
||||
let dz = za * c + xa * s;
|
||||
if !self.walkable(w, dx, dz) {
|
||||
self.ai.mov.strafe_forwards = 1.0;
|
||||
self.ai.mov.strafe_right = 0.0;
|
||||
}
|
||||
self.set_speed(speed);
|
||||
self.ai.zza = self.ai.mov.strafe_forwards;
|
||||
self.ai.xxa = self.ai.mov.strafe_right;
|
||||
self.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
Operation::MoveTo => {
|
||||
self.ai.mov.operation = Operation::Wait;
|
||||
let [wx, wy, wz] = self.ai.mov.wanted;
|
||||
let (xd, yd, zd) = (
|
||||
wx - self.position.x,
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
self.ai.zza = 0.0;
|
||||
return;
|
||||
}
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, 90.0);
|
||||
self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32);
|
||||
let (bx, by, bz) = (
|
||||
self.position.x.floor() as i32,
|
||||
self.position.y.floor() as i32,
|
||||
self.position.z.floor() as i32,
|
||||
);
|
||||
let state = w.world.block(bx, by, bz);
|
||||
let top = w.data.state(state).top;
|
||||
let name = &w.facts.get(state).name;
|
||||
let door_or_fence = name.ends_with("_door") || name.ends_with("fence");
|
||||
if yd > self.kind.step_height
|
||||
&& xd * xd + zd * zd < f64::from(self.width().max(1.0))
|
||||
|| top > 0.0
|
||||
&& self.position.y < f64::from(top) + f64::from(by)
|
||||
&& !door_or_fence
|
||||
{
|
||||
self.ai.jump = true;
|
||||
self.ai.mov.operation = Operation::Jumping;
|
||||
}
|
||||
}
|
||||
Operation::Jumping => {
|
||||
self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32);
|
||||
if self.on_ground || self.is_in_liquid() {
|
||||
self.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
}
|
||||
Operation::Wait => self.ai.zza = 0.0,
|
||||
}
|
||||
}
|
||||
fn walkable(&self, w: &MobWorld, dx: f32, dz: f32) -> bool {
|
||||
let x = (self.position.x + f64::from(dx)).floor() as i32;
|
||||
let z = (self.position.z + f64::from(dz)).floor() as i32;
|
||||
let y = self.position.y.floor() as i32;
|
||||
w.path_type_static(x, y, z) == super::path::PathType::Walkable
|
||||
}
|
||||
/// LookControl.tick (and SmoothSwimmingLookControl).
|
||||
pub fn look_control_tick(&mut self) {
|
||||
let look = self.ai.look.clone();
|
||||
let (x_d, y_d) = self.look_angles(look.wanted);
|
||||
match look.kind {
|
||||
LookKind::SmoothSwimming(max) => {
|
||||
if look.cooldown > 0 {
|
||||
self.ai.look.cooldown -= 1;
|
||||
if let Some(y) = y_d {
|
||||
self.head_yaw =
|
||||
rotate_towards(self.head_yaw, y + 20.0, look.y_max_rot_speed);
|
||||
}
|
||||
if let Some(x) = x_d {
|
||||
self.head_pitch =
|
||||
rotate_towards(self.head_pitch, x + 10.0, look.x_max_rot_angle);
|
||||
}
|
||||
} else {
|
||||
if self.ai.nav.is_done() {
|
||||
self.head_pitch = rotate_towards(self.head_pitch, 0.0, 5.0);
|
||||
}
|
||||
self.head_yaw =
|
||||
rotate_towards(self.head_yaw, self.body_yaw, look.y_max_rot_speed);
|
||||
}
|
||||
let diff = wrap(self.head_yaw - self.body_yaw);
|
||||
if diff < -max {
|
||||
self.body_yaw -= 4.0;
|
||||
} else if diff > max {
|
||||
self.body_yaw += 4.0;
|
||||
}
|
||||
}
|
||||
LookKind::Default | LookKind::Fixed => {
|
||||
if look.kind == LookKind::Default {
|
||||
self.head_pitch = 0.0;
|
||||
}
|
||||
if look.cooldown > 0 {
|
||||
self.ai.look.cooldown -= 1;
|
||||
if let Some(y) = y_d {
|
||||
self.head_yaw = rotate_towards(self.head_yaw, y, look.y_max_rot_speed);
|
||||
}
|
||||
if let Some(x) = x_d {
|
||||
self.head_pitch = rotate_towards(self.head_pitch, x, look.x_max_rot_angle);
|
||||
}
|
||||
} else {
|
||||
self.head_yaw = rotate_towards(self.head_yaw, self.body_yaw, 10.0);
|
||||
}
|
||||
if !self.ai.nav.is_done() {
|
||||
self.head_yaw =
|
||||
rotate_if_necessary(self.head_yaw, self.body_yaw, self.kind.max_head_y_rot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn look_angles(&self, at: [f64; 3]) -> (Option<f32>, Option<f32>) {
|
||||
let (xd, yd, zd) = (
|
||||
at[0] - self.position.x,
|
||||
at[1] - self.eye_y(),
|
||||
at[2] - self.position.z,
|
||||
);
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
let x =
|
||||
(yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5).then(|| -(yd.atan2(sd).to_degrees() as f32));
|
||||
let y = (zd.abs() > 1.0e-5 || xd.abs() > 1.0e-5)
|
||||
.then(|| (zd.atan2(xd).to_degrees() as f32) - 90.0);
|
||||
(x, y)
|
||||
}
|
||||
/// JumpControl.tick.
|
||||
pub fn jump_control_tick(&mut self) {
|
||||
self.ai.jumping = self.ai.jump;
|
||||
self.ai.jump = false;
|
||||
}
|
||||
/// BodyRotationControl.clientTick (Mob.tickHeadTurn).
|
||||
pub fn body_rotation_tick(&mut self) {
|
||||
let dx = self.position.x - self.previous.x;
|
||||
let dz = self.position.z - self.previous.z;
|
||||
let max = self.kind.max_head_y_rot;
|
||||
if dx * dx + dz * dz > 2.500_000_3e-7 {
|
||||
self.body_yaw = self.yaw;
|
||||
self.head_yaw = rotate_if_necessary(self.head_yaw, self.body_yaw, max);
|
||||
self.ai.body.last_stable_head = self.head_yaw;
|
||||
self.ai.body.head_stable_time = 0;
|
||||
} else if (self.head_yaw - self.ai.body.last_stable_head).abs() > 15.0 {
|
||||
self.ai.body.head_stable_time = 0;
|
||||
self.ai.body.last_stable_head = self.head_yaw;
|
||||
self.body_yaw = rotate_if_necessary(self.body_yaw, self.head_yaw, max);
|
||||
} else {
|
||||
self.ai.body.head_stable_time += 1;
|
||||
if self.ai.body.head_stable_time > 10 {
|
||||
let t = self.ai.body.head_stable_time - 10;
|
||||
let fraction = (t as f32 / 10.0).clamp(0.0, 1.0);
|
||||
self.body_yaw =
|
||||
rotate_if_necessary(self.body_yaw, self.head_yaw, max * (1.0 - fraction));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Entity.rotlerp used by Mob.lookAt (clamped turn, no wrap of the result).
|
||||
fn rotate_toward_max(from: f32, to: f32, max: f32) -> f32 {
|
||||
from + wrap(to - from).clamp(-max, max)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Facts the mob AI and renderer read from vanilla code, exported by
|
||||
//! `VanillaMobDataExporter` into `mob-data.json`: per-state pathfinding types
|
||||
//! (`WalkNodeEvaluator.getPathTypeFromState` with vanilla's tags bound),
|
||||
//! pathfindability, spawn-surface predicates, collision tops, each entity
|
||||
//! type's spawn placement and the client's keyframe animation definitions.
|
||||
use super::keyframes::Animation;
|
||||
use super::path::PathType;
|
||||
use crate::blocks::{BlockFacts, Fluid};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path};
|
||||
|
||||
pub const LAND: u16 = 1;
|
||||
pub const WATER: u16 = 2;
|
||||
pub const AIR: u16 = 4;
|
||||
/// `isValidSpawn` for a typical monster (zombie).
|
||||
pub const VALID_SPAWN: u16 = 8;
|
||||
/// `isValidSpawn` for ocelots/parrots (leaves allowed).
|
||||
pub const VALID_SPAWN_LEAVES: u16 = 16;
|
||||
/// `isValidSpawn` for polar bears (ice allowed).
|
||||
pub const VALID_SPAWN_ICE: u16 = 32;
|
||||
pub const REDSTONE_CONDUCTOR: u16 = 64;
|
||||
/// `NaturalSpawner.isValidEmptySpawnBlock` for a zombie.
|
||||
pub const VALID_EMPTY_SPAWN: u16 = 128;
|
||||
pub const STURDY_TOP: u16 = 256;
|
||||
/// BlockState.isSolid
|
||||
pub const SOLID: u16 = 512;
|
||||
pub const SOLID_RENDER: u16 = 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct StateData {
|
||||
pub path: PathType,
|
||||
pub flags: u16,
|
||||
/// Collision shape top (0 when the shape is empty).
|
||||
pub top: f32,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Placement {
|
||||
OnGround,
|
||||
InWater,
|
||||
InLava,
|
||||
NoRestrictions,
|
||||
}
|
||||
pub struct MobData {
|
||||
pub states: Vec<StateData>,
|
||||
pub placements: HashMap<String, Placement>,
|
||||
pub animations: HashMap<String, Animation>,
|
||||
/// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id.
|
||||
pub biome_tags: HashMap<String, std::collections::HashSet<String>>,
|
||||
}
|
||||
impl MobData {
|
||||
pub fn load(root: &Path, facts: &BlockFacts) -> Self {
|
||||
let parsed: Option<Value> = fs::read(root.join("mob-data.json"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok());
|
||||
let mut data = match parsed {
|
||||
Some(v)
|
||||
if v["states"]
|
||||
.as_array()
|
||||
.is_some_and(|a| a.len() == facts.states.len()) =>
|
||||
{
|
||||
Self::from_json(&v)
|
||||
}
|
||||
_ => Self::fallback(facts),
|
||||
};
|
||||
data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default();
|
||||
data
|
||||
}
|
||||
pub fn biome_has(&self, tag: &str, biome: &str) -> bool {
|
||||
self.biome_tags.get(tag).is_some_and(|s| s.contains(biome))
|
||||
}
|
||||
fn from_json(v: &Value) -> Self {
|
||||
let states = v["states"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|s| StateData {
|
||||
path: PathType::from_name(s[0].as_str().unwrap_or("BLOCKED")),
|
||||
flags: s[1].as_u64().unwrap_or(0) as u16,
|
||||
top: s[2].as_f64().unwrap_or(0.0) as f32,
|
||||
})
|
||||
.collect();
|
||||
let placements = v["placements"]
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|(k, p)| {
|
||||
let placement = match p["placement"].as_str() {
|
||||
Some("on_ground") => Placement::OnGround,
|
||||
Some("in_water") => Placement::InWater,
|
||||
Some("in_lava") => Placement::InLava,
|
||||
_ => Placement::NoRestrictions,
|
||||
};
|
||||
(k.clone(), placement)
|
||||
})
|
||||
.collect();
|
||||
let animations = v["animations"]
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|(k, a)| (k.clone(), Animation::parse(a)))
|
||||
.collect();
|
||||
Self {
|
||||
states,
|
||||
placements,
|
||||
animations,
|
||||
biome_tags: HashMap::new(),
|
||||
}
|
||||
}
|
||||
/// Without the export, approximate path types from the gameplay facts.
|
||||
pub fn fallback(facts: &BlockFacts) -> Self {
|
||||
let states = facts
|
||||
.states
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let name = &*f.name;
|
||||
let path = if matches!(
|
||||
name,
|
||||
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
|
||||
) {
|
||||
PathType::Open
|
||||
} else if f.fluid == Fluid::Lava && !f.waterlogged {
|
||||
PathType::Lava
|
||||
} else if name.ends_with("fence") || name.ends_with("_wall") {
|
||||
PathType::Fence
|
||||
} else if name.ends_with("leaves") {
|
||||
PathType::Leaves
|
||||
} else if name == "minecraft:fire" || name == "minecraft:magma_block" {
|
||||
PathType::Fire
|
||||
} else if f.full_collision {
|
||||
PathType::Blocked
|
||||
} else if f.fluid == Fluid::Water {
|
||||
PathType::Water
|
||||
} else {
|
||||
PathType::Open
|
||||
};
|
||||
let mut flags = 0;
|
||||
if !f.full_collision {
|
||||
flags |= LAND | AIR | VALID_EMPTY_SPAWN;
|
||||
}
|
||||
if f.fluid == Fluid::Water {
|
||||
flags |= WATER;
|
||||
}
|
||||
if f.full_collision {
|
||||
flags |=
|
||||
VALID_SPAWN | VALID_SPAWN_ICE | REDSTONE_CONDUCTOR | STURDY_TOP | SOLID;
|
||||
}
|
||||
StateData {
|
||||
path,
|
||||
flags,
|
||||
top: if f.full_collision { 1.0 } else { 0.0 },
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
states,
|
||||
placements: HashMap::new(),
|
||||
animations: HashMap::new(),
|
||||
biome_tags: HashMap::new(),
|
||||
}
|
||||
}
|
||||
pub fn state(&self, id: horizon_world::registry::BlockStateId) -> StateData {
|
||||
self.states
|
||||
.get(id.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(StateData {
|
||||
path: PathType::Blocked,
|
||||
flags: 0,
|
||||
top: 1.0,
|
||||
})
|
||||
}
|
||||
pub fn placement(&self, entity: &str) -> Placement {
|
||||
self.placements
|
||||
.get(entity)
|
||||
.cloned()
|
||||
.unwrap_or(Placement::OnGround)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Farm animals: pigs, cows, mooshrooms, sheep and chickens (`registerGoals`,
|
||||
//! chicken flapping and egg laying, sheep wool colours).
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
goals::{
|
||||
Breed, EatBlock, Float, FollowParent, LookAtPlayer, Panic, RandomLookAround, Stroll, Tempt,
|
||||
},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
let food = m.kind.food.clone();
|
||||
let tempt = m.kind.tempt.clone();
|
||||
let g = &mut m.ai.goals;
|
||||
match m.kind.species {
|
||||
Species::Pig => {
|
||||
g.add(0, Float);
|
||||
g.add(1, Panic::new(1.25));
|
||||
g.add(3, Breed::new(1.0));
|
||||
g.add(
|
||||
4,
|
||||
Tempt::new(
|
||||
1.2,
|
||||
Arc::from(vec!["minecraft:carrot_on_a_stick".to_owned()]),
|
||||
false,
|
||||
),
|
||||
);
|
||||
g.add(4, Tempt::new(1.2, tempt, false));
|
||||
g.add(5, FollowParent::new(1.1));
|
||||
g.add(6, Stroll::avoiding_water(1.0));
|
||||
g.add(7, LookAtPlayer::new(6.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
}
|
||||
Species::Cow | Species::Mooshroom => {
|
||||
g.add(0, Float);
|
||||
g.add(1, Panic::new(2.0));
|
||||
g.add(2, Breed::new(1.0));
|
||||
g.add(3, Tempt::new(1.25, food, false));
|
||||
g.add(4, FollowParent::new(1.25));
|
||||
g.add(5, Stroll::avoiding_water(1.0));
|
||||
g.add(6, LookAtPlayer::new(6.0));
|
||||
g.add(7, RandomLookAround::default());
|
||||
}
|
||||
Species::Sheep => {
|
||||
g.add(0, Float);
|
||||
g.add(1, Panic::new(1.25));
|
||||
g.add(2, Breed::new(1.0));
|
||||
g.add(3, Tempt::new(1.1, food, false));
|
||||
g.add(4, FollowParent::new(1.1));
|
||||
g.add(5, EatBlock::default());
|
||||
g.add(6, Stroll::avoiding_water(1.0));
|
||||
g.add(7, LookAtPlayer::new(6.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
}
|
||||
Species::Chicken => {
|
||||
g.add(0, Float);
|
||||
g.add(1, Panic::new(1.4));
|
||||
g.add(2, Breed::new(1.0));
|
||||
g.add(3, Tempt::new(1.0, food, false));
|
||||
g.add(4, FollowParent::new(1.1));
|
||||
g.add(5, Stroll::avoiding_water(1.0));
|
||||
g.add(6, LookAtPlayer::new(6.0));
|
||||
g.add(7, RandomLookAround::default());
|
||||
m.extra.egg_time = m.random.next_int_bound(6000).unwrap_or(0) + 6000;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Chicken.aiStep: wing flapping, slowed falling and laying eggs.
|
||||
pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let a = &mut m.anim;
|
||||
a.flap_o = a.flap;
|
||||
a.flap_speed_o = a.flap_speed;
|
||||
a.flap_speed = (a.flap_speed + if m.on_ground { -1.0 } else { 4.0 } * 0.3).clamp(0.0, 1.0);
|
||||
if !m.on_ground && a.flapping < 1.0 {
|
||||
a.flapping = 1.0;
|
||||
}
|
||||
a.flapping *= 0.9;
|
||||
if !m.on_ground && m.velocity.y < 0.0 {
|
||||
m.velocity.y *= 0.6;
|
||||
}
|
||||
a.flap += a.flapping * 2.0;
|
||||
if m.alive() && !m.is_baby() {
|
||||
m.extra.egg_time -= 1;
|
||||
if m.extra.egg_time <= 0 {
|
||||
let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0;
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch));
|
||||
events.push(MobEvent::GiftLoot {
|
||||
table: "minecraft:gameplay/chicken_lay",
|
||||
at,
|
||||
});
|
||||
m.extra.egg_time = m.random.next_int_bound(6000).unwrap_or(0) + 6000;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Farm animal climate from the biome tags (`spawns_warm/cold_variant_farm_animals`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Climate {
|
||||
#[default]
|
||||
Temperate,
|
||||
Warm,
|
||||
Cold,
|
||||
}
|
||||
/// SheepColorSpawnRules.getSheepColor: a weighted list of 100 where the
|
||||
/// climate's common colour (82) itself rolls pink 1 in 500.
|
||||
pub fn sheep_color(climate: Climate, random: &mut impl RandomSource) -> u8 {
|
||||
// DyeColor ids: white 0, pink 6, gray 7, light gray 8, brown 12, black 15.
|
||||
let (list, common): ([(u8, i32); 4], u8) = match climate {
|
||||
Climate::Temperate => ([(15, 5), (7, 5), (8, 5), (12, 3)], 0),
|
||||
Climate::Warm => ([(7, 5), (8, 5), (0, 5), (15, 3)], 12),
|
||||
Climate::Cold => ([(8, 5), (7, 5), (0, 5), (12, 3)], 15),
|
||||
};
|
||||
let mut r = random.next_int_bound(100).unwrap_or(0);
|
||||
for (color, weight) in list {
|
||||
if r < weight {
|
||||
return color;
|
||||
}
|
||||
r -= weight;
|
||||
}
|
||||
if random.next_int_bound(500).unwrap_or(1) < 499 {
|
||||
common
|
||||
} else {
|
||||
6
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,173 @@
|
||||
//! Creepers (swelling, explosions) and spiders (wall climbing, daylight
|
||||
//! neutrality, leaping).
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LeapAtTarget, LookAtPlayer, MOVE,
|
||||
MeleeAttack, NearestTarget, RandomLookAround, Stroll, goal_clone,
|
||||
},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
S::Creeper => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, Float);
|
||||
g.add(2, Swell::default());
|
||||
g.add(
|
||||
3,
|
||||
AvoidEntity::new(Avoid::Species(vec![S::Ocelot]), 6.0, 1.0, 1.2),
|
||||
);
|
||||
g.add(
|
||||
3,
|
||||
AvoidEntity::new(Avoid::Species(vec![S::Cat]), 6.0, 1.0, 1.2),
|
||||
);
|
||||
g.add(4, MeleeAttack::new(1.0, false));
|
||||
g.add(5, Stroll::avoiding_water(0.8));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
g.add(6, RandomLookAround::default());
|
||||
m.ai.targets.add(1, NearestTarget::player(true));
|
||||
m.ai.targets.add(2, HurtByTarget::new());
|
||||
// Creeper DATA_SWELL_DIR starts at -1.
|
||||
m.extra.counter = -1;
|
||||
}
|
||||
S::Spider | S::CaveSpider => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, Float);
|
||||
g.add(
|
||||
2,
|
||||
AvoidEntity::new(Avoid::Species(vec![S::Armadillo]), 6.0, 1.0, 1.2),
|
||||
);
|
||||
g.add(3, LeapAtTarget::new(0.4));
|
||||
g.add(4, SpiderAttack(MeleeAttack::new(1.0, true)));
|
||||
g.add(5, Stroll::avoiding_water(0.8));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
g.add(6, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
m.ai.targets
|
||||
.add(2, NearestTarget::player(true).when(dark_enough));
|
||||
m.ai.targets.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::IronGolem], true).when(dark_enough),
|
||||
);
|
||||
m.ai.nav.kind = super::nav::NavKind::WallClimber;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Entity.getLightLevelDependentMagicValue at the eye.
|
||||
pub fn mob_brightness(m: &Mob, w: &MobWorld) -> f32 {
|
||||
w.brightness(
|
||||
m.position.x.floor() as i32,
|
||||
m.eye_y().floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
)
|
||||
}
|
||||
fn dark_enough(m: &Mob, w: &MobWorld) -> bool {
|
||||
mob_brightness(m, w) < 0.5
|
||||
}
|
||||
/// Spider.SpiderAttackGoal: gives up in bright light 1 in 100 ticks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SpiderAttack(MeleeAttack);
|
||||
impl Goal for SpiderAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if mob_brightness(m, cx.w) >= 0.5 && m.random.next_int_bound(100).unwrap_or(1) == 0 {
|
||||
m.ai.target = None;
|
||||
return false;
|
||||
}
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// SwellGoal: fuse within 3 blocks, defuse beyond 7 or out of sight.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Swell {
|
||||
target: Option<Who>,
|
||||
}
|
||||
impl Goal for Swell {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let close = m
|
||||
.target_info(cx.w)
|
||||
.is_some_and(|t| t.alive && m.distance_sqr(t.position) < 9.0);
|
||||
m.extra.counter > 0 || close
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.nav_stop();
|
||||
self.target = m.ai.target;
|
||||
}
|
||||
fn stop(&mut self, _: &mut Mob, _: &mut Cx) {
|
||||
self.target = None;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let dir = match self
|
||||
.target
|
||||
.and_then(|t| cx.w.target_info(t).map(|i| (t, i)))
|
||||
{
|
||||
Some((who, t)) if t.alive => {
|
||||
if m.distance_sqr(t.position) > 49.0 || !m.sees(cx.w, who) {
|
||||
-1
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
_ => -1,
|
||||
};
|
||||
m.extra.counter = dir;
|
||||
}
|
||||
}
|
||||
/// Creeper.tick: advance the fuse and explode at 30.
|
||||
pub fn creeper_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
if m.extra.flag {
|
||||
// Ignited by flint and steel.
|
||||
m.extra.counter = 1;
|
||||
}
|
||||
let dir = m.extra.counter;
|
||||
if dir > 0 && m.swell == 0 {
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.creeper.primed",
|
||||
m.center(),
|
||||
1.0,
|
||||
0.5,
|
||||
));
|
||||
}
|
||||
m.swell = (m.swell + dir).max(0);
|
||||
if m.swell >= 30 {
|
||||
m.swell = 30;
|
||||
let radius = if m.extra.charged { 6.0 } else { 3.0 };
|
||||
events.push(MobEvent::Explode(
|
||||
[m.position.x, m.position.y, m.position.z],
|
||||
radius,
|
||||
));
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Vanilla keyframe animations (`AnimationDefinition`, `AnimationChannel`,
|
||||
//! `KeyframeAnimation`) exported from the client's animation definitions,
|
||||
//! applied to a pose map exactly like `KeyframeAnimation.Entry.apply`.
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
Position,
|
||||
Rotation,
|
||||
Scale,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Keyframe {
|
||||
pub time: f32,
|
||||
pub pre: [f32; 3],
|
||||
pub post: [f32; 3],
|
||||
pub catmull: bool,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Channel {
|
||||
pub target: Target,
|
||||
pub keyframes: Vec<Keyframe>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Animation {
|
||||
pub length: f32,
|
||||
pub looping: bool,
|
||||
pub bones: Vec<(String, Vec<Channel>)>,
|
||||
}
|
||||
fn v3(v: &Value) -> [f32; 3] {
|
||||
let a = |i: usize| v[i].as_f64().unwrap_or(0.0) as f32;
|
||||
[a(0), a(1), a(2)]
|
||||
}
|
||||
impl Animation {
|
||||
pub fn parse(v: &Value) -> Self {
|
||||
let bones = v["bones"]
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|(name, channels)| {
|
||||
let channels = channels
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| Channel {
|
||||
target: match c["target"].as_str() {
|
||||
Some("position") => Target::Position,
|
||||
Some("scale") => Target::Scale,
|
||||
_ => Target::Rotation,
|
||||
},
|
||||
keyframes: c["keyframes"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|k| Keyframe {
|
||||
time: k[0].as_f64().unwrap_or(0.0) as f32,
|
||||
pre: v3(&k[1]),
|
||||
post: v3(&k[2]),
|
||||
catmull: k[3].as_str() == Some("catmullrom"),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
(name.clone(), channels)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
length: v["length"].as_f64().unwrap_or(1.0) as f32,
|
||||
looping: v["looping"].as_bool().unwrap_or(false),
|
||||
bones,
|
||||
}
|
||||
}
|
||||
/// KeyframeAnimation.apply(millis, scale): offsets added to each bone's pose.
|
||||
pub fn apply(&self, millis: i64, scale: f32, poses: &mut super::anim::Poses) {
|
||||
let mut seconds = millis as f32 / 1000.0;
|
||||
if self.looping {
|
||||
seconds %= self.length;
|
||||
}
|
||||
for (bone, channels) in &self.bones {
|
||||
for c in channels {
|
||||
let v = sample(&c.keyframes, seconds, scale);
|
||||
let p = poses.get(bone);
|
||||
match c.target {
|
||||
// ModelPart.offsetPos / offsetRotation / offsetScale.
|
||||
Target::Position => {
|
||||
p[0] += v[0];
|
||||
p[1] += v[1];
|
||||
p[2] += v[2];
|
||||
}
|
||||
Target::Rotation => {
|
||||
p[3] += v[0];
|
||||
p[4] += v[1];
|
||||
p[5] += v[2];
|
||||
}
|
||||
Target::Scale => {
|
||||
p[6] += v[0];
|
||||
p[7] += v[1];
|
||||
p[8] += v[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// KeyframeAnimation.applyWalk(pos, speed, speedFactor, scaleFactor).
|
||||
pub fn apply_walk(
|
||||
&self,
|
||||
pos: f32,
|
||||
speed: f32,
|
||||
speed_factor: f32,
|
||||
scale_factor: f32,
|
||||
poses: &mut super::anim::Poses,
|
||||
) {
|
||||
let time = (pos * 50.0 * speed_factor) as i64;
|
||||
let scale = (speed * scale_factor).min(1.0);
|
||||
self.apply(time, scale, poses);
|
||||
}
|
||||
}
|
||||
fn catmullrom(t: f32, p0: f32, p1: f32, p2: f32, p3: f32) -> f32 {
|
||||
0.5 * (2.0 * p1
|
||||
+ (p2 - p0) * t
|
||||
+ (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t * t
|
||||
+ (3.0 * p1 - p0 - 3.0 * p2 + p3) * t * t * t)
|
||||
}
|
||||
/// KeyframeAnimation.Entry.apply interpolation.
|
||||
fn sample(k: &[Keyframe], seconds: f32, scale: f32) -> [f32; 3] {
|
||||
if k.is_empty() {
|
||||
return [0.0; 3];
|
||||
}
|
||||
// Mth.binarySearch(0, len, i -> seconds <= k[i].time) - 1
|
||||
let first = k.iter().position(|f| seconds <= f.time).unwrap_or(k.len());
|
||||
let prev = first.saturating_sub(1);
|
||||
let next = (prev + 1).min(k.len() - 1);
|
||||
let delta = seconds - k[prev].time;
|
||||
let alpha = if next != prev {
|
||||
(delta / (k[next].time - k[prev].time)).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if k[next].catmull {
|
||||
let p0 = k[prev.saturating_sub(1)].post;
|
||||
let p1 = k[prev].post;
|
||||
let p2 = k[next].post;
|
||||
let p3 = k[(next + 1).min(k.len() - 1)].post;
|
||||
std::array::from_fn(|i| catmullrom(alpha, p0[i], p1[i], p2[i], p3[i]) * scale)
|
||||
} else {
|
||||
let a = k[prev].post;
|
||||
let b = k[next].pre;
|
||||
std::array::from_fn(|i| (a[i] + (b[i] - a[i]) * alpha) * scale)
|
||||
}
|
||||
}
|
||||
/// AnimationState: a start time in ticks while started.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct AnimationState {
|
||||
pub started: Option<f32>,
|
||||
}
|
||||
impl AnimationState {
|
||||
pub fn start(&mut self, age: f32) {
|
||||
self.started = Some(age);
|
||||
}
|
||||
pub fn start_if_stopped(&mut self, age: f32) {
|
||||
if self.started.is_none() {
|
||||
self.started = Some(age);
|
||||
}
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.started = None;
|
||||
}
|
||||
pub fn animate_when(&mut self, condition: bool, age: f32) {
|
||||
if condition {
|
||||
self.start_if_stopped(age)
|
||||
} else {
|
||||
self.stop()
|
||||
}
|
||||
}
|
||||
/// Milliseconds since the start at render time `age` (ticks + partial).
|
||||
pub fn millis(&self, age: f32) -> Option<i64> {
|
||||
self.started.map(|s| ((age - s) * 50.0) as i64)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn linear_keyframes_interpolate_post_to_pre() {
|
||||
let k = vec![
|
||||
Keyframe {
|
||||
time: 0.0,
|
||||
pre: [0.0; 3],
|
||||
post: [0.0; 3],
|
||||
catmull: false,
|
||||
},
|
||||
Keyframe {
|
||||
time: 1.0,
|
||||
pre: [2.0, 4.0, 6.0],
|
||||
post: [2.0, 4.0, 6.0],
|
||||
catmull: false,
|
||||
},
|
||||
];
|
||||
let v = sample(&k, 0.5, 1.0);
|
||||
assert_eq!(v, [1.0, 2.0, 3.0]);
|
||||
// Past the end it holds the last value.
|
||||
assert_eq!(sample(&k, 3.0, 0.5), [1.0, 2.0, 3.0]);
|
||||
}
|
||||
#[test]
|
||||
fn catmullrom_passes_through_keyframes() {
|
||||
let k = vec![
|
||||
Keyframe {
|
||||
time: 0.0,
|
||||
pre: [0.0; 3],
|
||||
post: [0.0; 3],
|
||||
catmull: true,
|
||||
},
|
||||
Keyframe {
|
||||
time: 1.0,
|
||||
pre: [1.0; 3],
|
||||
post: [1.0; 3],
|
||||
catmull: true,
|
||||
},
|
||||
Keyframe {
|
||||
time: 2.0,
|
||||
pre: [0.0; 3],
|
||||
post: [0.0; 3],
|
||||
catmull: true,
|
||||
},
|
||||
];
|
||||
assert!((sample(&k, 1.0, 1.0)[0] - 1.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! `LivingEntity` movement for mobs: `aiStep` input decay and jumping,
|
||||
//! `travel` in air, water and lava (friction-scaled acceleration, gravity,
|
||||
//! fluid slowdown and falling adjustment), fluid immersion heights, fall
|
||||
//! damage, fire and the walk animation.
|
||||
use super::{Mob, MobEvent, MobWorld};
|
||||
use crate::{blocks::Fluid, collisions::SceneCollisions};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Fluids {
|
||||
pub water: f64,
|
||||
pub lava: f64,
|
||||
pub in_water: bool,
|
||||
pub in_lava: bool,
|
||||
pub eye_in_water: bool,
|
||||
}
|
||||
pub fn wrap(a: f32) -> f32 {
|
||||
let mut a = a % 360.0;
|
||||
if a >= 180.0 {
|
||||
a -= 360.0;
|
||||
}
|
||||
if a < -180.0 {
|
||||
a += 360.0;
|
||||
}
|
||||
a
|
||||
}
|
||||
impl MobWorld<'_> {
|
||||
/// FluidState.getHeight: a full block under the same fluid, else amount / 9.
|
||||
pub fn fluid_height(&self, x: i32, y: i32, z: i32) -> (Fluid, f64) {
|
||||
let f = self.facts.get(self.world.block(x, y, z));
|
||||
if f.fluid == Fluid::None {
|
||||
return (Fluid::None, 0.0);
|
||||
}
|
||||
let above = self.facts.get(self.world.block(x, y + 1, z));
|
||||
if above.fluid == f.fluid {
|
||||
return (f.fluid, 1.0);
|
||||
}
|
||||
(f.fluid, f64::from(f.fluid_level) / 9.0)
|
||||
}
|
||||
/// Entity.updateFluidHeightAndDoFluidPushing heights over the deflated box.
|
||||
pub fn fluids(&self, bounds: Aabb, eye_y: f64) -> Fluids {
|
||||
let b = bounds.deflate(Vec3::new(0.001, 0.001, 0.001));
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let mut out = Fluids::default();
|
||||
for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) {
|
||||
for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) {
|
||||
for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) {
|
||||
let (fluid, h) = self.fluid_height(x, y, z);
|
||||
if fluid == Fluid::None {
|
||||
continue;
|
||||
}
|
||||
let top = f64::from(y) + h;
|
||||
if top >= lo.y {
|
||||
let depth = top - lo.y;
|
||||
match fluid {
|
||||
Fluid::Water => {
|
||||
out.water = out.water.max(depth);
|
||||
out.in_water = true;
|
||||
}
|
||||
Fluid::Lava => {
|
||||
out.lava = out.lava.max(depth);
|
||||
out.in_lava = true;
|
||||
}
|
||||
Fluid::None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fx, fz) = ((lo.x + hi.x) / 2.0, (lo.z + hi.z) / 2.0);
|
||||
let ey = eye_y.floor() as i32;
|
||||
let (fluid, h) = self.fluid_height(fx.floor() as i32, ey, fz.floor() as i32);
|
||||
out.eye_in_water = fluid == Fluid::Water && eye_y < f64::from(ey) + h + 0.111_111_11;
|
||||
out
|
||||
}
|
||||
pub fn no_collision(&self, b: Aabb) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
scene.unobstructed(b).unwrap_or(false)
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
pub fn eye_y(&self) -> f64 {
|
||||
self.position.y + self.eye_height()
|
||||
}
|
||||
/// Entity dimensions: the type's, a class's BABY_DIMENSIONS, or the
|
||||
/// slime size scaling.
|
||||
pub fn dims(&self) -> (f64, f64, f64) {
|
||||
let k = &self.kind;
|
||||
let (mut w, mut h, mut e) = (k.width, k.height, k.eye_height);
|
||||
if self.is_baby() {
|
||||
match super::species::def(k.species).baby {
|
||||
super::species::Baby::Abs(bw, bh, be) => (w, h, e) = (bw, bh, be),
|
||||
super::species::Baby::Scale(s, eye) => {
|
||||
(w, h, e) = (w * s, h * s, eye.unwrap_or(e * s))
|
||||
}
|
||||
super::species::Baby::None => {}
|
||||
}
|
||||
}
|
||||
if self.extra.size > 0 {
|
||||
let s = f64::from(self.extra.size);
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
}
|
||||
(w, h, e)
|
||||
}
|
||||
pub fn eye_height(&self) -> f64 {
|
||||
self.dims().2
|
||||
}
|
||||
pub fn width(&self) -> f32 {
|
||||
self.dims().0 as f32
|
||||
}
|
||||
pub fn height(&self) -> f32 {
|
||||
self.dims().1 as f32
|
||||
}
|
||||
pub fn is_baby(&self) -> bool {
|
||||
self.extra.age < 0
|
||||
}
|
||||
pub fn fluid_jump_threshold(&self) -> f64 {
|
||||
if self.eye_height() < 0.4 { 0.0 } else { 0.4 }
|
||||
}
|
||||
pub fn is_in_liquid(&self) -> bool {
|
||||
self.fluids.in_water || self.fluids.in_lava
|
||||
}
|
||||
fn affected_by_fluids(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// Entity.moveRelative: input rotated by yaw and scaled to `speed`.
|
||||
pub fn move_relative(&mut self, speed: f32, input: Vec3) {
|
||||
let len_sq = input.x * input.x + input.y * input.y + input.z * input.z;
|
||||
if len_sq < 1.0e-7 {
|
||||
return;
|
||||
}
|
||||
let v = if len_sq > 1.0 {
|
||||
let l = len_sq.sqrt();
|
||||
Vec3::new(input.x / l, input.y / l, input.z / l)
|
||||
} else {
|
||||
input
|
||||
};
|
||||
let v = Vec3::new(
|
||||
v.x * f64::from(speed),
|
||||
v.y * f64::from(speed),
|
||||
v.z * f64::from(speed),
|
||||
);
|
||||
let (s, c) = (
|
||||
f64::from(self.yaw.to_radians().sin() as f32),
|
||||
f64::from(self.yaw.to_radians().cos() as f32),
|
||||
);
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x + (v.x * c - v.z * s),
|
||||
self.velocity.y + v.y,
|
||||
self.velocity.z + (v.z * c + v.x * s),
|
||||
);
|
||||
}
|
||||
/// Entity.move with block collisions and step-up; updates collision flags
|
||||
/// and fall distance (Entity.checkFallDamage).
|
||||
pub fn do_move(&mut self, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let wanted = self.velocity;
|
||||
let step = self.kind.step_height as f32;
|
||||
let mut scene = SceneCollisions {
|
||||
world: w.world,
|
||||
binding: w.collision,
|
||||
};
|
||||
let moved = scene
|
||||
.resolve(self.bounds(), wanted, step, self.on_ground)
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
self.position = Vec3::new(
|
||||
self.position.x + moved.x,
|
||||
self.position.y + moved.y,
|
||||
self.position.z + moved.z,
|
||||
);
|
||||
let x_hit = (moved.x - wanted.x).abs() > 1.0e-5;
|
||||
let z_hit = (moved.z - wanted.z).abs() > 1.0e-5;
|
||||
self.horizontal_collision = x_hit || z_hit;
|
||||
let vertical = (moved.y - wanted.y).abs() > 1.0e-5;
|
||||
self.vertical_collision_below = vertical && wanted.y < 0.0;
|
||||
self.on_ground = self.vertical_collision_below;
|
||||
if x_hit {
|
||||
self.velocity.x = 0.0;
|
||||
}
|
||||
if z_hit {
|
||||
self.velocity.z = 0.0;
|
||||
}
|
||||
if vertical {
|
||||
self.velocity.y = 0.0;
|
||||
}
|
||||
// Entity.checkFallDamage
|
||||
if self.on_ground {
|
||||
if self.fall_distance > 0.0 {
|
||||
self.cause_fall_damage(events);
|
||||
}
|
||||
self.fall_distance = 0.0;
|
||||
} else if moved.y < 0.0 {
|
||||
self.fall_distance -= moved.y;
|
||||
}
|
||||
if self.fluids.in_water {
|
||||
self.fall_distance = 0.0;
|
||||
}
|
||||
}
|
||||
fn cause_fall_damage(&mut self, events: &mut Vec<MobEvent>) {
|
||||
if self.kind.flags.fall_immune {
|
||||
return;
|
||||
}
|
||||
let power = self.fall_distance + 1.0e-6 - self.kind.safe_fall_distance;
|
||||
let damage = (power * self.kind.fall_damage_multiplier).floor();
|
||||
if damage > 0.0 {
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
let sound = if damage > 4.0 {
|
||||
"entity.generic.big_fall"
|
||||
} else {
|
||||
"entity.generic.small_fall"
|
||||
};
|
||||
events.push(MobEvent::Sound(sound, at, 1.0, 1.0));
|
||||
self.damage(damage as f32, super::Damage::fall());
|
||||
}
|
||||
}
|
||||
/// LivingEntity.getFrictionInfluencedSpeed.
|
||||
fn friction_speed(&self, friction: f32) -> f32 {
|
||||
if self.on_ground {
|
||||
if friction > 0.6 {
|
||||
self.ai.speed * (0.216_000_02 / (friction * friction * friction))
|
||||
} else {
|
||||
self.ai.speed
|
||||
}
|
||||
} else {
|
||||
self.flying_speed()
|
||||
}
|
||||
}
|
||||
fn flying_speed(&self) -> f32 {
|
||||
0.02
|
||||
}
|
||||
fn gravity(&self) -> f64 {
|
||||
self.kind.gravity
|
||||
}
|
||||
/// LivingEntity.travel.
|
||||
pub fn travel(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
if super::ai::custom_travel(self, w, input, events) {
|
||||
return;
|
||||
}
|
||||
if self.kind.flags.flying {
|
||||
return self.travel_flying(w, input, events);
|
||||
}
|
||||
let stands_on_fluid = self.kind.flags.lava_walker && self.fluids.in_lava;
|
||||
if self.is_in_liquid() && self.affected_by_fluids() && !stands_on_fluid {
|
||||
self.travel_in_fluid(w, input, events);
|
||||
} else {
|
||||
self.travel_in_air(w, input, events);
|
||||
}
|
||||
}
|
||||
/// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag.
|
||||
fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
let (speed, drag) = if self.fluids.in_water {
|
||||
(0.02, 0.8)
|
||||
} else if self.fluids.in_lava {
|
||||
(0.02, 0.5)
|
||||
} else {
|
||||
(self.kind.air_speed, 0.91)
|
||||
};
|
||||
self.move_relative(speed, input);
|
||||
self.do_move(w, events);
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * drag,
|
||||
self.velocity.y * drag,
|
||||
self.velocity.z * drag,
|
||||
);
|
||||
}
|
||||
fn block_friction(&self, w: &MobWorld) -> f32 {
|
||||
// Entity.getBlockPosBelowThatAffectsMyMovement: 0.500001 below.
|
||||
let x = self.position.x.floor() as i32;
|
||||
let z = self.position.z.floor() as i32;
|
||||
let y = (self.position.y - 0.500_001).floor() as i32;
|
||||
w.facts.get(w.world.block(x, y, z)).friction
|
||||
}
|
||||
fn travel_in_air(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
let friction = if self.on_ground {
|
||||
self.block_friction(w)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let speed = self.friction_speed(friction);
|
||||
self.move_relative(speed, input);
|
||||
if self.kind.flags.climber && self.horizontal_collision {
|
||||
// Spider.onClimbable: handleOnClimbable clamps and resets the fall.
|
||||
self.fall_distance = 0.0;
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x.clamp(-0.15, 0.15),
|
||||
self.velocity.y.max(-0.15),
|
||||
self.velocity.z.clamp(-0.15, 0.15),
|
||||
);
|
||||
}
|
||||
self.do_move(w, events);
|
||||
let mut movement = self.velocity;
|
||||
if self.kind.flags.climber
|
||||
&& (self.horizontal_collision || self.ai.jumping)
|
||||
&& self.climbing
|
||||
{
|
||||
movement.y = 0.2;
|
||||
}
|
||||
let mut y = movement.y;
|
||||
if self.extra.levitation > 0 {
|
||||
y += (0.05 * 1.0 - movement.y) * 0.2;
|
||||
} else {
|
||||
y -= self.gravity();
|
||||
}
|
||||
let drag = 0.91f32;
|
||||
let f = friction * drag;
|
||||
let vertical = if self.kind.flags.omnidirectional {
|
||||
drag
|
||||
} else {
|
||||
0.98
|
||||
};
|
||||
self.velocity = Vec3::new(
|
||||
movement.x * f64::from(f),
|
||||
y * f64::from(vertical),
|
||||
movement.z * f64::from(f),
|
||||
);
|
||||
}
|
||||
fn travel_in_fluid(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
let falling = self.velocity.y <= 0.0;
|
||||
let old_y = self.position.y;
|
||||
let gravity = self.gravity();
|
||||
if self.fluids.in_water {
|
||||
let mut slow = self.kind.water_slowdown;
|
||||
let mut speed = 0.02f32;
|
||||
let mut efficiency = self.kind.water_efficiency as f32;
|
||||
if !self.on_ground {
|
||||
efficiency *= 0.5;
|
||||
}
|
||||
if efficiency > 0.0 {
|
||||
slow += (0.546_000_06 - slow) * efficiency;
|
||||
speed += (self.ai.speed - speed) * efficiency;
|
||||
}
|
||||
self.move_relative(speed, input);
|
||||
self.do_move(w, events);
|
||||
let mut m = self.velocity;
|
||||
if self.horizontal_collision && self.kind.flags.climber {
|
||||
m.y = 0.2;
|
||||
}
|
||||
m = Vec3::new(m.x * f64::from(slow), m.y * 0.8, m.z * f64::from(slow));
|
||||
self.velocity = fluid_falling(gravity, falling, m);
|
||||
} else {
|
||||
self.move_relative(0.02, input);
|
||||
self.do_move(w, events);
|
||||
if self.fluids.lava <= self.fluid_jump_threshold() {
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.5,
|
||||
self.velocity.y * 0.8,
|
||||
self.velocity.z * 0.5,
|
||||
);
|
||||
self.velocity = fluid_falling(gravity, falling, self.velocity);
|
||||
} else {
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.5,
|
||||
self.velocity.y * 0.5,
|
||||
self.velocity.z * 0.5,
|
||||
);
|
||||
}
|
||||
if gravity != 0.0 {
|
||||
self.velocity.y -= gravity / 4.0;
|
||||
}
|
||||
}
|
||||
// jumpOutOfFluid
|
||||
let m = self.velocity;
|
||||
if self.horizontal_collision
|
||||
&& w.no_collision(self.bounds().move_by(Vec3::new(
|
||||
m.x,
|
||||
m.y + 0.6 - self.position.y + old_y,
|
||||
m.z,
|
||||
)))
|
||||
{
|
||||
self.velocity.y = 0.3;
|
||||
}
|
||||
}
|
||||
/// The jump part of LivingEntity.aiStep.
|
||||
pub fn handle_jumping(&mut self) {
|
||||
if self.ai.jumping && self.affected_by_fluids() {
|
||||
let (fluid_height, in_water_with_height) = if self.fluids.in_lava {
|
||||
(self.fluids.lava, false)
|
||||
} else {
|
||||
(
|
||||
self.fluids.water,
|
||||
self.fluids.in_water && self.fluids.water > 0.0,
|
||||
)
|
||||
};
|
||||
let threshold = self.fluid_jump_threshold();
|
||||
if !in_water_with_height || self.on_ground && fluid_height <= threshold {
|
||||
if !self.fluids.in_lava || self.on_ground && self.fluids.lava <= threshold {
|
||||
if (self.on_ground || in_water_with_height && fluid_height <= threshold)
|
||||
&& self.ai.no_jump_delay == 0
|
||||
{
|
||||
self.jump_from_ground();
|
||||
self.ai.no_jump_delay = 10;
|
||||
}
|
||||
} else {
|
||||
self.jump_in_liquid();
|
||||
}
|
||||
} else {
|
||||
self.jump_in_liquid();
|
||||
}
|
||||
} else {
|
||||
self.ai.no_jump_delay = 0;
|
||||
}
|
||||
}
|
||||
/// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3.
|
||||
fn jump_in_liquid(&mut self) {
|
||||
self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 };
|
||||
}
|
||||
pub fn jump_from_ground(&mut self) {
|
||||
let power = self.jump_power();
|
||||
if power > 1.0e-5 {
|
||||
self.velocity.y = f64::from(power).max(self.velocity.y);
|
||||
}
|
||||
}
|
||||
pub fn jump_power(&self) -> f32 {
|
||||
self.kind.jump_strength as f32
|
||||
}
|
||||
/// LivingEntity.updateWalkAnimation (client calculateEntityAnimation).
|
||||
pub fn update_walk_animation(&mut self) {
|
||||
let dy = if self.kind.flags.omnidirectional {
|
||||
self.position.y - self.previous.y
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let dx = self.position.x - self.previous.x;
|
||||
let dz = self.position.z - self.previous.z;
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32;
|
||||
self.previous_limb_speed = self.limb_speed;
|
||||
if self.alive() {
|
||||
let target = (distance * 4.0).min(1.0);
|
||||
self.limb_speed += (target - self.limb_speed) * 0.4;
|
||||
self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 };
|
||||
} else {
|
||||
self.limb_speed = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// LivingEntity.getFluidFallingAdjustedMovement.
|
||||
fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 {
|
||||
if gravity != 0.0 {
|
||||
let y = if falling && (m.y - 0.005).abs() >= 0.003 && (m.y - gravity / 16.0).abs() < 0.003 {
|
||||
-0.003
|
||||
} else {
|
||||
m.y - gravity / 16.0
|
||||
};
|
||||
Vec3::new(m.x, y, m.z)
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
//! `PathNavigation` and its ground, wall-climbing, water-bound, flying and
|
||||
//! amphibious variants: path creation, waypoint following, corner cutting,
|
||||
//! stuck detection and path timeouts.
|
||||
use super::{
|
||||
Mob, MobWorld,
|
||||
path::{Evaluator, Finder, Path, PathMob, PathType},
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum NavKind {
|
||||
#[default]
|
||||
Ground,
|
||||
WallClimber,
|
||||
Water {
|
||||
breach: bool,
|
||||
},
|
||||
Flying,
|
||||
Amphibious,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Navigation {
|
||||
pub kind: NavKind,
|
||||
pub path: Option<Path>,
|
||||
pub speed_modifier: f64,
|
||||
tick: i64,
|
||||
last_stuck_check: i64,
|
||||
last_stuck_pos: Vec3,
|
||||
timeout_node: [i32; 3],
|
||||
timeout_timer: i64,
|
||||
last_timeout_check: i64,
|
||||
timeout_limit: f64,
|
||||
pub max_distance_to_waypoint: f32,
|
||||
delayed_recompute: bool,
|
||||
time_last_recompute: i64,
|
||||
pub target_pos: Option<[i32; 3]>,
|
||||
reach_range: i32,
|
||||
pub max_visited_multiplier: f32,
|
||||
pub stuck: bool,
|
||||
pub required_path_length: f32,
|
||||
pub can_float: bool,
|
||||
pub can_open_doors: bool,
|
||||
pub can_pass_doors: bool,
|
||||
pub can_walk_over_fences: bool,
|
||||
pub avoid_sun: bool,
|
||||
pub below_surface: bool,
|
||||
/// WallClimberNavigation.pathToPosition
|
||||
climb_to: Option<[i32; 3]>,
|
||||
}
|
||||
impl Default for Navigation {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: NavKind::Ground,
|
||||
path: None,
|
||||
speed_modifier: 0.0,
|
||||
tick: 0,
|
||||
last_stuck_check: 0,
|
||||
last_stuck_pos: Vec3::ZERO,
|
||||
timeout_node: [0; 3],
|
||||
timeout_timer: 0,
|
||||
last_timeout_check: 0,
|
||||
timeout_limit: 0.0,
|
||||
max_distance_to_waypoint: 0.5,
|
||||
delayed_recompute: false,
|
||||
time_last_recompute: 0,
|
||||
target_pos: None,
|
||||
reach_range: 0,
|
||||
max_visited_multiplier: 1.0,
|
||||
stuck: false,
|
||||
required_path_length: 16.0,
|
||||
can_float: false,
|
||||
can_open_doors: false,
|
||||
can_pass_doors: true,
|
||||
can_walk_over_fences: false,
|
||||
avoid_sun: false,
|
||||
below_surface: false,
|
||||
climb_to: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Navigation {
|
||||
pub fn is_done(&self) -> bool {
|
||||
self.path.as_ref().is_none_or(Path::is_done)
|
||||
}
|
||||
pub fn is_in_progress(&self) -> bool {
|
||||
!self.is_done()
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.path = None;
|
||||
}
|
||||
fn reset_stuck_timeout(&mut self) {
|
||||
self.timeout_node = [0; 3];
|
||||
self.timeout_timer = 0;
|
||||
self.timeout_limit = 0.0;
|
||||
self.stuck = false;
|
||||
}
|
||||
fn evaluator(&self) -> Evaluator {
|
||||
match self.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => Evaluator::Walk,
|
||||
NavKind::Water { breach } => Evaluator::Swim { breach },
|
||||
NavKind::Flying => Evaluator::Fly,
|
||||
NavKind::Amphibious => Evaluator::Amphibious {
|
||||
prefers_shallow: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn can_cut_corner(t: PathType) -> bool {
|
||||
!matches!(
|
||||
t,
|
||||
PathType::FireInNeighbor | PathType::DamagingInNeighbor | PathType::WalkableDoor
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
pub fn path_mob(&self) -> PathMob {
|
||||
PathMob {
|
||||
position: self.position,
|
||||
width: self.width(),
|
||||
height: self.height(),
|
||||
on_ground: self.on_ground,
|
||||
in_water: self.fluids.in_water,
|
||||
max_up_step: self.kind.step_height as f32,
|
||||
max_fall_distance: self.max_fall_distance(),
|
||||
malus: self.ai.malus,
|
||||
can_float: self.ai.nav.can_float,
|
||||
can_open_doors: self.ai.nav.can_open_doors,
|
||||
can_pass_doors: self.ai.nav.can_pass_doors,
|
||||
can_walk_over_fences: self.ai.nav.can_walk_over_fences,
|
||||
stands_on_lava: self.kind.flags.lava_walker,
|
||||
}
|
||||
}
|
||||
/// Mob.getMaxFallDistance (normal difficulty).
|
||||
pub fn max_fall_distance(&self) -> i32 {
|
||||
if self.ai.target.is_none() {
|
||||
return 3;
|
||||
}
|
||||
let mut sacrifice = (self.health - self.kind.max_health * 0.33) as i32;
|
||||
sacrifice -= (3 - 2) * 4;
|
||||
sacrifice.max(0) + 3
|
||||
}
|
||||
pub fn malus(&self, t: PathType) -> f32 {
|
||||
self.ai.malus[t as usize].unwrap_or_else(|| t.malus())
|
||||
}
|
||||
pub fn set_malus(&mut self, t: PathType, v: f32) {
|
||||
self.ai.malus[t as usize] = Some(v);
|
||||
}
|
||||
fn max_path_length(&self) -> f32 {
|
||||
(self.kind.follow_range as f32).max(self.ai.nav.required_path_length)
|
||||
}
|
||||
fn can_update_path(&self) -> bool {
|
||||
match self.ai.nav.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => self.on_ground || self.is_in_liquid(),
|
||||
NavKind::Water { breach } => breach || self.is_in_liquid(),
|
||||
NavKind::Flying | NavKind::Amphibious => true,
|
||||
}
|
||||
}
|
||||
fn temp_mob_pos(&self, w: &MobWorld) -> Vec3 {
|
||||
match self.ai.nav.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => Vec3::new(
|
||||
self.position.x,
|
||||
f64::from(self.surface_y(w)),
|
||||
self.position.z,
|
||||
),
|
||||
NavKind::Water { .. } | NavKind::Amphibious => Vec3::new(
|
||||
self.position.x,
|
||||
self.position.y + f64::from(self.height()) * 0.5,
|
||||
self.position.z,
|
||||
),
|
||||
NavKind::Flying => self.position,
|
||||
}
|
||||
}
|
||||
fn surface_y(&self, w: &MobWorld) -> i32 {
|
||||
let (x, z) = (
|
||||
self.position.x.floor() as i32,
|
||||
self.position.z.floor() as i32,
|
||||
);
|
||||
if self.fluids.in_water && self.ai.nav.can_float {
|
||||
let mut y = self.position.y.floor() as i32;
|
||||
let start = y;
|
||||
let mut steps = 0;
|
||||
while w.facts.get(w.world.block(x, y, z)).fluid == crate::blocks::Fluid::Water {
|
||||
y += 1;
|
||||
steps += 1;
|
||||
if steps > 16 {
|
||||
return start;
|
||||
}
|
||||
}
|
||||
y
|
||||
} else {
|
||||
(self.position.y + 0.5).floor() as i32
|
||||
}
|
||||
}
|
||||
/// GroundPathNavigation.findSurfacePosition.
|
||||
fn surface_position(&self, w: &MobWorld, mut p: [i32; 3]) -> [i32; 3] {
|
||||
let air = |p: [i32; 3]| w.facts.is_air(w.world.block(p[0], p[1], p[2]));
|
||||
let solid = |p: [i32; 3]| w.solid(p[0], p[1], p[2]);
|
||||
if air(p) {
|
||||
let mut q = [p[0], p[1] - 1, p[2]];
|
||||
while q[1] >= crate::chunk::MIN_Y && air(q) {
|
||||
q[1] -= 1;
|
||||
}
|
||||
if q[1] >= crate::chunk::MIN_Y {
|
||||
return [q[0], q[1] + 1, q[2]];
|
||||
}
|
||||
q[1] = p[1] + 1;
|
||||
while q[1] <= 319 && air(q) {
|
||||
q[1] += 1;
|
||||
}
|
||||
p = q;
|
||||
}
|
||||
if !solid(p) {
|
||||
return p;
|
||||
}
|
||||
let mut q = [p[0], p[1] + 1, p[2]];
|
||||
while q[1] <= 319 && solid(q) {
|
||||
q[1] += 1;
|
||||
}
|
||||
q
|
||||
}
|
||||
fn create_path_raw(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
targets: &[[i32; 3]],
|
||||
reach: i32,
|
||||
max_len: f32,
|
||||
) -> Option<Path> {
|
||||
if targets.is_empty()
|
||||
|| self.position.y < f64::from(crate::chunk::MIN_Y)
|
||||
|| !self.can_update_path()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if let (Some(path), Some(tp)) = (&self.ai.nav.path, self.ai.nav.target_pos)
|
||||
&& !path.is_done()
|
||||
&& targets.contains(&tp)
|
||||
{
|
||||
return Some(path.clone());
|
||||
}
|
||||
let pm = self.path_mob();
|
||||
let max_visited = ((self.kind.follow_range * 16.0).floor() as f32
|
||||
* self.ai.nav.max_visited_multiplier) as i32;
|
||||
let finder = Finder::new(w, &pm, self.ai.nav.evaluator());
|
||||
let path = finder.find(targets, max_len, reach, max_visited);
|
||||
if let Some(p) = &path {
|
||||
self.ai.nav.target_pos = Some(p.target);
|
||||
self.ai.nav.reach_range = reach;
|
||||
self.ai.nav.reset_stuck_timeout();
|
||||
}
|
||||
path
|
||||
}
|
||||
/// PathNavigation.createPath(BlockPos, reach) with the ground surface search.
|
||||
pub fn create_path_to(&mut self, w: &MobWorld, mut p: [i32; 3], reach: i32) -> Option<Path> {
|
||||
match self.ai.nav.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => {
|
||||
if !w.world.loaded(p[0], p[2]) {
|
||||
return None;
|
||||
}
|
||||
if self.ai.nav.kind == NavKind::WallClimber {
|
||||
self.ai.nav.climb_to = Some(p);
|
||||
}
|
||||
if !self.ai.nav.below_surface {
|
||||
p = self.surface_position(w, p);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let max = self.max_path_length();
|
||||
self.create_path_raw(w, &[p], reach, max)
|
||||
}
|
||||
/// PathNavigation.createPath(Entity, reach).
|
||||
pub fn create_path_to_entity(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
at: [f64; 3],
|
||||
reach: i32,
|
||||
) -> Option<Path> {
|
||||
let p = [
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
];
|
||||
self.create_path_to(w, p, reach)
|
||||
}
|
||||
pub fn nav_move_to_path(&mut self, path: Option<Path>, speed: f64) -> bool {
|
||||
let Some(path) = path else {
|
||||
self.ai.nav.path = None;
|
||||
return false;
|
||||
};
|
||||
if !path.same_as(self.ai.nav.path.as_ref()) {
|
||||
self.ai.nav.path = Some(path);
|
||||
}
|
||||
if self.ai.nav.is_done() {
|
||||
return false;
|
||||
}
|
||||
if self.ai.nav.path.as_ref().is_none_or(|p| p.nodes.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
self.ai.nav.speed_modifier = speed;
|
||||
self.ai.nav.last_stuck_check = self.ai.nav.tick;
|
||||
// getTempMobPos needs the world for ground navigation; position is close enough
|
||||
// for the first stuck sample and is refreshed 100 ticks later.
|
||||
self.ai.nav.last_stuck_pos = self.position;
|
||||
true
|
||||
}
|
||||
/// PathNavigation.moveTo(x, y, z, speed): a path to the containing block.
|
||||
pub fn nav_move_to(&mut self, w: &MobWorld, at: [f64; 3], speed: f64) -> bool {
|
||||
let p = [
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
];
|
||||
let path = self.create_path_to(w, p, 1);
|
||||
self.nav_move_to_path(path, speed)
|
||||
}
|
||||
pub fn nav_move_to_entity(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
at: [f64; 3],
|
||||
reach: i32,
|
||||
speed: f64,
|
||||
) -> bool {
|
||||
let path = self.create_path_to_entity(w, at, reach);
|
||||
if self.ai.nav.kind == NavKind::WallClimber && path.is_none() {
|
||||
// WallClimberNavigation.moveTo(Entity): climb straight towards it.
|
||||
self.ai.nav.climb_to = Some([
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
at[2].floor() as i32,
|
||||
]);
|
||||
self.ai.nav.speed_modifier = speed;
|
||||
return true;
|
||||
}
|
||||
path.is_some() && self.nav_move_to_path(path, speed)
|
||||
}
|
||||
pub fn nav_stop(&mut self) {
|
||||
self.ai.nav.path = None;
|
||||
}
|
||||
fn recompute_path(&mut self, w: &MobWorld) {
|
||||
if w.game_time - self.ai.nav.time_last_recompute <= 20 || !self.can_update_path() {
|
||||
self.ai.nav.delayed_recompute = true;
|
||||
} else if let Some(t) = self.ai.nav.target_pos {
|
||||
self.ai.nav.path = None;
|
||||
let reach = self.ai.nav.reach_range;
|
||||
self.ai.nav.path = self.create_path_to(w, t, reach);
|
||||
self.ai.nav.time_last_recompute = w.game_time;
|
||||
self.ai.nav.delayed_recompute = false;
|
||||
}
|
||||
}
|
||||
/// PathNavigation.tick.
|
||||
pub fn nav_tick(&mut self, w: &MobWorld) {
|
||||
self.ai.nav.tick += 1;
|
||||
if self.ai.nav.delayed_recompute {
|
||||
self.recompute_path(w);
|
||||
}
|
||||
if self.ai.nav.kind == NavKind::WallClimber && self.ai.nav.is_done() {
|
||||
if let Some(t) = self.ai.nav.climb_to {
|
||||
let width = f64::from(self.width());
|
||||
let center = |p: [i32; 3]| {
|
||||
let (dx, dy, dz) = (
|
||||
f64::from(p[0]) + 0.5 - self.position.x,
|
||||
f64::from(p[1]) + 0.5 - self.position.y,
|
||||
f64::from(p[2]) + 0.5 - self.position.z,
|
||||
);
|
||||
dx * dx + dy * dy + dz * dz < width * width
|
||||
};
|
||||
let same_level = [t[0], self.position.y.floor() as i32, t[2]];
|
||||
if !center(t) && (self.position.y <= f64::from(t[1]) || !center(same_level)) {
|
||||
let speed = self.ai.nav.speed_modifier;
|
||||
self.ai.mov.set_wanted(
|
||||
f64::from(t[0]),
|
||||
f64::from(t[1]),
|
||||
f64::from(t[2]),
|
||||
speed,
|
||||
);
|
||||
} else {
|
||||
self.ai.nav.climb_to = None;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.ai.nav.is_done() {
|
||||
return;
|
||||
}
|
||||
if self.can_update_path() {
|
||||
self.follow_the_path(w);
|
||||
} else if let Some(path) = &self.ai.nav.path
|
||||
&& !path.is_done()
|
||||
{
|
||||
let mob = self.temp_mob_pos(w);
|
||||
let pos = path.entity_pos_at(path.next, self.width());
|
||||
let advance = match self.ai.nav.kind {
|
||||
NavKind::Flying => {
|
||||
self.position.x.floor() == pos.x.floor()
|
||||
&& self.position.y.floor() == pos.y.floor()
|
||||
&& self.position.z.floor() == pos.z.floor()
|
||||
}
|
||||
_ => {
|
||||
mob.y > pos.y
|
||||
&& !self.on_ground
|
||||
&& mob.x.floor() == pos.x.floor()
|
||||
&& mob.z.floor() == pos.z.floor()
|
||||
}
|
||||
};
|
||||
if advance && let Some(p) = &mut self.ai.nav.path {
|
||||
p.advance();
|
||||
}
|
||||
}
|
||||
if let Some(path) = &self.ai.nav.path
|
||||
&& !path.is_done()
|
||||
{
|
||||
let target = path.entity_pos_at(path.next, self.width());
|
||||
let y = match self.ai.nav.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => {
|
||||
let (bx, by, bz) = (
|
||||
target.x.floor() as i32,
|
||||
target.y.floor() as i32,
|
||||
target.z.floor() as i32,
|
||||
);
|
||||
if w.facts.is_air(w.world.block(bx, by - 1, bz)) {
|
||||
target.y
|
||||
} else {
|
||||
w.floor_level(bx, by, bz)
|
||||
}
|
||||
}
|
||||
_ => target.y,
|
||||
};
|
||||
let speed = self.ai.nav.speed_modifier;
|
||||
self.ai.mov.set_wanted(target.x, y, target.z, speed);
|
||||
}
|
||||
}
|
||||
fn follow_the_path(&mut self, w: &MobWorld) {
|
||||
let mob_pos = self.temp_mob_pos(w);
|
||||
let width = self.width();
|
||||
self.ai.nav.max_distance_to_waypoint = if width > 0.75 {
|
||||
width / 2.0
|
||||
} else {
|
||||
0.75 - width / 2.0
|
||||
};
|
||||
let vertical = match self.ai.nav.kind {
|
||||
NavKind::Water { .. } => 0.5,
|
||||
_ => 1.0,
|
||||
};
|
||||
let Some(path) = &self.ai.nav.path else {
|
||||
return;
|
||||
};
|
||||
let n = path.next_node();
|
||||
let xd = (self.position.x - (f64::from(n.x) + 0.5)).abs();
|
||||
let yd = (self.position.y - f64::from(n.y)).abs();
|
||||
let zd = (self.position.z - (f64::from(n.z) + 0.5)).abs();
|
||||
let max = f64::from(self.ai.nav.max_distance_to_waypoint);
|
||||
let close = xd < max && zd < max && yd < vertical;
|
||||
if close || Navigation::can_cut_corner(n.kind) && self.should_target_next_node(w, mob_pos) {
|
||||
if let Some(p) = &mut self.ai.nav.path {
|
||||
p.advance();
|
||||
}
|
||||
}
|
||||
self.do_stuck_detection(w, mob_pos);
|
||||
}
|
||||
fn should_target_next_node(&self, w: &MobWorld, mob: Vec3) -> bool {
|
||||
let Some(path) = &self.ai.nav.path else {
|
||||
return false;
|
||||
};
|
||||
if path.next + 1 >= path.nodes.len() {
|
||||
return false;
|
||||
}
|
||||
let n = path.nodes[path.next];
|
||||
let current = Vec3::new(f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5);
|
||||
let d = |a: Vec3, b: Vec3| (a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2);
|
||||
if d(mob, current) >= 4.0 {
|
||||
return false;
|
||||
}
|
||||
if self.can_move_directly(w, mob, path.entity_pos_at(path.next, self.width())) {
|
||||
return true;
|
||||
}
|
||||
let m = path.nodes[path.next + 1];
|
||||
let next = Vec3::new(f64::from(m.x) + 0.5, f64::from(m.y), f64::from(m.z) + 0.5);
|
||||
let to_current = Vec3::new(current.x - mob.x, current.y - mob.y, current.z - mob.z);
|
||||
let to_next = Vec3::new(next.x - mob.x, next.y - mob.y, next.z - mob.z);
|
||||
let (cs, ns) = (to_current.length_squared(), to_next.length_squared());
|
||||
if !(ns < cs) && !(cs < 0.5) {
|
||||
return false;
|
||||
}
|
||||
let a = to_current.normalize();
|
||||
let b = to_next.normalize();
|
||||
a.x * b.x + a.y * b.y + a.z * b.z < 0.0
|
||||
}
|
||||
fn can_move_directly(&self, w: &MobWorld, from: Vec3, to: Vec3) -> bool {
|
||||
match self.ai.nav.kind {
|
||||
NavKind::Flying => w.clear_between(
|
||||
from,
|
||||
Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z),
|
||||
true,
|
||||
),
|
||||
NavKind::Water { .. } => w.clear_between(
|
||||
from,
|
||||
Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z),
|
||||
false,
|
||||
),
|
||||
NavKind::Amphibious if self.is_in_liquid() => w.clear_between(
|
||||
from,
|
||||
Vec3::new(to.x, to.y + f64::from(self.height()) * 0.5, to.z),
|
||||
false,
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn do_stuck_detection(&mut self, w: &MobWorld, mob: Vec3) {
|
||||
let speed = self.ai.speed;
|
||||
let nav = &mut self.ai.nav;
|
||||
if nav.tick - nav.last_stuck_check > 100 {
|
||||
let effective = if speed >= 1.0 { speed } else { speed * speed };
|
||||
let threshold = f64::from(effective * 100.0 * 0.25);
|
||||
let d = (mob.x - nav.last_stuck_pos.x).powi(2)
|
||||
+ (mob.y - nav.last_stuck_pos.y).powi(2)
|
||||
+ (mob.z - nav.last_stuck_pos.z).powi(2);
|
||||
if d < threshold * threshold {
|
||||
nav.stuck = true;
|
||||
nav.path = None;
|
||||
} else {
|
||||
nav.stuck = false;
|
||||
}
|
||||
nav.last_stuck_check = nav.tick;
|
||||
nav.last_stuck_pos = mob;
|
||||
}
|
||||
if let Some(path) = &nav.path
|
||||
&& !path.is_done()
|
||||
{
|
||||
let n = path.next_node();
|
||||
let pos = [n.x, n.y, n.z];
|
||||
if pos == nav.timeout_node {
|
||||
nav.timeout_timer += w.game_time - nav.last_timeout_check;
|
||||
} else {
|
||||
nav.timeout_node = pos;
|
||||
let c = Vec3::new(f64::from(n.x) + 0.5, f64::from(n.y), f64::from(n.z) + 0.5);
|
||||
let dist =
|
||||
((mob.x - c.x).powi(2) + (mob.y - c.y).powi(2) + (mob.z - c.z).powi(2)).sqrt();
|
||||
nav.timeout_limit = if speed > 0.0 {
|
||||
dist / f64::from(speed) * 20.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
}
|
||||
if nav.timeout_limit > 0.0 && nav.timeout_timer as f64 > nav.timeout_limit * 3.0 {
|
||||
nav.reset_stuck_timeout();
|
||||
nav.path = None;
|
||||
}
|
||||
nav.last_timeout_check = w.game_time;
|
||||
}
|
||||
}
|
||||
/// PathNavigation.isStableDestination for the mob's navigation.
|
||||
pub fn stable_destination(&self, w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
match self.ai.nav.kind {
|
||||
NavKind::Ground | NavKind::WallClimber => {
|
||||
w.facts
|
||||
.get(w.world.block(p[0], p[1] - 1, p[2]))
|
||||
.solid_render
|
||||
}
|
||||
NavKind::Water { .. } => !w.facts.get(w.world.block(p[0], p[1], p[2])).solid_render,
|
||||
NavKind::Flying => {
|
||||
w.data.state(w.world.block(p[0], p[1], p[2])).flags & super::data::STURDY_TOP != 0
|
||||
}
|
||||
NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])),
|
||||
}
|
||||
}
|
||||
pub fn should_recompute_path(&self, p: [i32; 3]) -> bool {
|
||||
if self.ai.nav.delayed_recompute {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = &self.ai.nav.path else {
|
||||
return false;
|
||||
};
|
||||
if path.is_done() || path.nodes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(end) = path.end() else { return false };
|
||||
let mid = [
|
||||
(f64::from(end.x) + self.position.x) / 2.0,
|
||||
(f64::from(end.y) + self.position.y) / 2.0,
|
||||
(f64::from(end.z) + self.position.z) / 2.0,
|
||||
];
|
||||
let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2)
|
||||
+ (f64::from(p[1]) + 0.5 - mid[1]).powi(2)
|
||||
+ (f64::from(p[2]) + 0.5 - mid[2]).powi(2);
|
||||
let r = (path.nodes.len() - path.next) as f64;
|
||||
d < r * r
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,507 @@
|
||||
//! Mob rendering (`LivingEntityRenderer.submit` and the render layers):
|
||||
//! variant/baby model and texture selection, setupRotations, per-species
|
||||
//! scale, and extra layers (sheep wool, spider eyes, drowned/stray outer
|
||||
//! layers, villager overlays, collars...).
|
||||
use super::{
|
||||
Mob, MobData, Part, Species,
|
||||
anim::{self, Poses},
|
||||
living::wrap,
|
||||
};
|
||||
use crate::mesher::Vertex;
|
||||
use std::f32::consts::PI;
|
||||
|
||||
/// A texture lookup into the shared atlas (name without namespace -> uv rect).
|
||||
pub type Atlas<'a> = &'a dyn Fn(&str) -> Option<[f32; 4]>;
|
||||
|
||||
/// One draw of a model with a texture.
|
||||
pub struct Layer {
|
||||
pub model: String,
|
||||
pub texture: String,
|
||||
pub color: u32,
|
||||
pub full_bright: bool,
|
||||
}
|
||||
/// DyeColor.getTextureDiffuseColor (RGB).
|
||||
pub const DYE: [u32; 16] = [
|
||||
0xF9FFFE, 0xF9801D, 0xC74EBD, 0x3AB3DA, 0xFED83D, 0x80C71F, 0xF38BAA, 0x474F52, 0x9D9D97,
|
||||
0x169C9C, 0x8932B8, 0x3C44AA, 0x835432, 0x5E7C16, 0xB02E26, 0x1D1D21,
|
||||
];
|
||||
pub const DYE_NAMES: [&str; 16] = [
|
||||
"white",
|
||||
"orange",
|
||||
"magenta",
|
||||
"light_blue",
|
||||
"yellow",
|
||||
"lime",
|
||||
"pink",
|
||||
"gray",
|
||||
"light_gray",
|
||||
"cyan",
|
||||
"purple",
|
||||
"blue",
|
||||
"brown",
|
||||
"green",
|
||||
"red",
|
||||
"black",
|
||||
];
|
||||
/// ABGR vertex colour from an RGB value.
|
||||
pub fn abgr(rgb: u32) -> u32 {
|
||||
let (r, g, b) = ((rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255);
|
||||
0xFF00_0000 | b << 16 | g << 8 | r
|
||||
}
|
||||
/// ColorLerper.Type.SHEEP colour: white is 0xE6E6E6, others 75% of the dye.
|
||||
pub fn sheep_wool_rgb(color: u8) -> u32 {
|
||||
if color == 0 {
|
||||
return 0xE6E6E6;
|
||||
}
|
||||
let src = DYE[color as usize & 15];
|
||||
let f = |c: u32| ((c as f32 * 0.75).floor() as u32).min(255);
|
||||
f(src >> 16 & 255) << 16 | f(src >> 8 & 255) << 8 | f(src & 255)
|
||||
}
|
||||
const VILLAGER_TYPES: [&str; 7] = [
|
||||
"plains", "desert", "jungle", "savanna", "snow", "swamp", "taiga",
|
||||
];
|
||||
pub const PROFESSIONS: [&str; 15] = [
|
||||
"none",
|
||||
"armorer",
|
||||
"butcher",
|
||||
"cartographer",
|
||||
"cleric",
|
||||
"farmer",
|
||||
"fisherman",
|
||||
"fletcher",
|
||||
"leatherworker",
|
||||
"librarian",
|
||||
"mason",
|
||||
"nitwit",
|
||||
"shepherd",
|
||||
"toolsmith",
|
||||
"weaponsmith",
|
||||
];
|
||||
fn baby_or(m: &Mob, adult: &str, baby: &str) -> String {
|
||||
if m.is_baby() && m.kind.layer(baby).is_some() {
|
||||
baby.to_owned()
|
||||
} else {
|
||||
adult.to_owned()
|
||||
}
|
||||
}
|
||||
fn climate(m: &Mob) -> &'static str {
|
||||
match m.extra.variant {
|
||||
1 => "warm",
|
||||
2 => "cold",
|
||||
_ => "temperate",
|
||||
}
|
||||
}
|
||||
/// The model layer key and texture for the mob's body.
|
||||
pub fn body(m: &Mob) -> (String, String) {
|
||||
use Species as S;
|
||||
let baby = m.is_baby();
|
||||
let b = |s: &str| {
|
||||
if baby {
|
||||
format!("{s}_baby")
|
||||
} else {
|
||||
s.to_owned()
|
||||
}
|
||||
};
|
||||
match m.species() {
|
||||
S::Pig => {
|
||||
let model = if baby {
|
||||
"pig_baby#main".into()
|
||||
} else if m.extra.variant == 2 {
|
||||
"cold_pig#main".into()
|
||||
} else {
|
||||
"pig#main".into()
|
||||
};
|
||||
(model, b(&format!("entity/pig/pig_{}", climate(m))))
|
||||
}
|
||||
S::Cow => {
|
||||
let model = match (m.extra.variant, baby) {
|
||||
(1, false) => "warm_cow#main",
|
||||
(1, true) => "warm_cow_baby#main",
|
||||
(2, false) => "cold_cow#main",
|
||||
(2, true) => "cold_cow_baby#main",
|
||||
(_, true) => "cow_baby#main",
|
||||
_ => "cow#main",
|
||||
};
|
||||
(model.into(), b(&format!("entity/cow/cow_{}", climate(m))))
|
||||
}
|
||||
S::Mooshroom => (
|
||||
baby_or(m, "mooshroom#main", "mooshroom_baby#main"),
|
||||
b(if m.extra.variant == 1 {
|
||||
"entity/cow/mooshroom_brown"
|
||||
} else {
|
||||
"entity/cow/mooshroom_red"
|
||||
}),
|
||||
),
|
||||
S::Chicken => {
|
||||
let model = if baby {
|
||||
"chicken_baby#main"
|
||||
} else if m.extra.variant == 2 {
|
||||
"cold_chicken#main"
|
||||
} else {
|
||||
"chicken#main"
|
||||
};
|
||||
(
|
||||
model.into(),
|
||||
b(&format!("entity/chicken/chicken_{}", climate(m))),
|
||||
)
|
||||
}
|
||||
S::Sheep => (
|
||||
baby_or(m, "sheep#main", "sheep_baby#main"),
|
||||
b("entity/sheep/sheep"),
|
||||
),
|
||||
S::Zombie => (
|
||||
baby_or(m, "zombie#main", "zombie_baby#main"),
|
||||
b("entity/zombie/zombie"),
|
||||
),
|
||||
S::Husk => (
|
||||
baby_or(m, "husk#main", "husk_baby#main"),
|
||||
b("entity/zombie/husk"),
|
||||
),
|
||||
S::Drowned => (
|
||||
baby_or(m, "drowned#main", "drowned_baby#main"),
|
||||
b("entity/zombie/drowned"),
|
||||
),
|
||||
S::ZombieVillager => (
|
||||
baby_or(m, "zombie_villager#main", "zombie_villager_baby#main"),
|
||||
"entity/zombie_villager/zombie_villager".into(),
|
||||
),
|
||||
S::Villager => (
|
||||
baby_or(m, "villager#main", "villager_baby#main"),
|
||||
b("entity/villager/villager"),
|
||||
),
|
||||
S::Piglin => (
|
||||
baby_or(m, "piglin#main", "piglin_baby#main"),
|
||||
b("entity/piglin/piglin"),
|
||||
),
|
||||
S::ZombifiedPiglin => (
|
||||
baby_or(m, "zombified_piglin#main", "zombified_piglin_baby#main"),
|
||||
b("entity/piglin/zombified_piglin"),
|
||||
),
|
||||
S::Hoglin => (
|
||||
baby_or(m, "hoglin#main", "hoglin_baby#main"),
|
||||
b("entity/hoglin/hoglin"),
|
||||
),
|
||||
S::Zoglin => (
|
||||
baby_or(m, "zoglin#main", "zoglin_baby#main"),
|
||||
b("entity/hoglin/zoglin"),
|
||||
),
|
||||
S::Strider => (
|
||||
baby_or(m, "strider#main", "strider_baby#main"),
|
||||
b(if m.extra.flag {
|
||||
"entity/strider/strider_cold"
|
||||
} else {
|
||||
"entity/strider/strider"
|
||||
}),
|
||||
),
|
||||
_ => (m.kind.model_key(), m.kind.texture.clone()),
|
||||
}
|
||||
}
|
||||
/// Extra render layers drawn over the body with the same pose.
|
||||
pub fn layers(m: &Mob) -> Vec<Layer> {
|
||||
use Species as S;
|
||||
let mut v = Vec::new();
|
||||
let white = 0xFFFF_FFFF;
|
||||
let push = |v: &mut Vec<Layer>, model: &str, texture: &str, color: u32, full_bright: bool| {
|
||||
v.push(Layer {
|
||||
model: model.into(),
|
||||
texture: texture.into(),
|
||||
color,
|
||||
full_bright,
|
||||
})
|
||||
};
|
||||
match m.species() {
|
||||
S::Sheep if !m.extra.sheared => {
|
||||
let color = abgr(sheep_wool_rgb(m.extra.color));
|
||||
if !m.is_baby() && m.extra.color != 0 {
|
||||
push(
|
||||
&mut v,
|
||||
"sheep#wool_undercoat",
|
||||
"entity/sheep/sheep_wool_undercoat",
|
||||
color,
|
||||
false,
|
||||
);
|
||||
}
|
||||
if m.is_baby() {
|
||||
push(
|
||||
&mut v,
|
||||
"sheep_baby#wool",
|
||||
"entity/sheep/sheep_wool_baby",
|
||||
color,
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
push(
|
||||
&mut v,
|
||||
"sheep#wool",
|
||||
"entity/sheep/sheep_wool",
|
||||
color,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
S::Spider | S::CaveSpider => push(
|
||||
&mut v,
|
||||
&m.kind.model_key(),
|
||||
"entity/spider/spider_eyes",
|
||||
white,
|
||||
true,
|
||||
),
|
||||
S::Enderman => push(
|
||||
&mut v,
|
||||
"enderman#main",
|
||||
"entity/enderman/enderman_eyes",
|
||||
white,
|
||||
true,
|
||||
),
|
||||
S::Phantom => push(
|
||||
&mut v,
|
||||
"phantom#main",
|
||||
"entity/phantom/phantom_eyes",
|
||||
white,
|
||||
true,
|
||||
),
|
||||
S::Drowned => {
|
||||
if m.is_baby() {
|
||||
push(
|
||||
&mut v,
|
||||
"drowned_baby#outer",
|
||||
"entity/zombie/drowned_outer_layer_baby",
|
||||
white,
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
push(
|
||||
&mut v,
|
||||
"drowned#outer",
|
||||
"entity/zombie/drowned_outer_layer",
|
||||
white,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
S::Stray => push(
|
||||
&mut v,
|
||||
"stray#outer",
|
||||
"entity/skeleton/stray_overlay",
|
||||
white,
|
||||
false,
|
||||
),
|
||||
S::Bogged if !m.extra.sheared => push(
|
||||
&mut v,
|
||||
"bogged#outer",
|
||||
"entity/skeleton/bogged_overlay",
|
||||
white,
|
||||
false,
|
||||
),
|
||||
S::Creeper if m.extra.charged => {}
|
||||
S::Villager | S::ZombieVillager => {
|
||||
let base = if m.species() == S::Villager {
|
||||
"villager"
|
||||
} else {
|
||||
"zombie_villager"
|
||||
};
|
||||
let model = if m.is_baby() {
|
||||
format!("{base}_baby#main")
|
||||
} else {
|
||||
format!("{base}#main")
|
||||
};
|
||||
let t = VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()];
|
||||
let folder = if m.species() == S::Villager {
|
||||
"entity/villager"
|
||||
} else {
|
||||
"entity/zombie_villager"
|
||||
};
|
||||
let baby = if m.is_baby() && m.species() == S::Villager {
|
||||
"baby/"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
push(
|
||||
&mut v,
|
||||
&model,
|
||||
&format!("{folder}/type/{baby}{t}"),
|
||||
white,
|
||||
false,
|
||||
);
|
||||
let prof = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()];
|
||||
if !m.is_baby() && prof != "none" {
|
||||
push(
|
||||
&mut v,
|
||||
&model,
|
||||
&format!("{folder}/profession/{prof}"),
|
||||
white,
|
||||
false,
|
||||
);
|
||||
if m.species() == S::Villager && prof != "nitwit" {
|
||||
let level = ["stone", "iron", "gold", "emerald", "diamond"]
|
||||
[(m.extra.variant3 as usize).min(4)];
|
||||
push(
|
||||
&mut v,
|
||||
&model,
|
||||
&format!("{folder}/profession_level/{level}"),
|
||||
white,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
v
|
||||
}
|
||||
impl super::MobType {
|
||||
/// The main model layer key without the namespace.
|
||||
pub fn model_key(&self) -> String {
|
||||
super::species::def(self.species).model.to_owned()
|
||||
}
|
||||
}
|
||||
/// The mob's root transform (LivingEntityRenderer.submit + setupRotations).
|
||||
pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
|
||||
let a = f64::from(alpha);
|
||||
let p = glam::DVec3::new(
|
||||
m.previous.x + (m.position.x - m.previous.x) * a,
|
||||
m.previous.y + (m.position.y - m.previous.y) * a,
|
||||
m.previous.z + (m.position.z - m.previous.z) * a,
|
||||
) - camera;
|
||||
let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha;
|
||||
let mut base = glam::Mat4::from_translation(p.as_vec3())
|
||||
* glam::Mat4::from_rotation_y((180.0 - body).to_radians());
|
||||
if m.death_time > 0 {
|
||||
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
|
||||
.sqrt()
|
||||
.min(1.0);
|
||||
base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians());
|
||||
}
|
||||
base *= species_rotations(m, alpha);
|
||||
base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0));
|
||||
base *= species_scale(m, alpha);
|
||||
base * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0))
|
||||
}
|
||||
fn flip_degrees(m: &Mob) -> f32 {
|
||||
match m.species() {
|
||||
Species::Spider | Species::CaveSpider | Species::Silverfish | Species::Endermite => 180.0,
|
||||
_ => 90.0,
|
||||
}
|
||||
}
|
||||
fn species_rotations(_m: &Mob, _alpha: f32) -> glam::Mat4 {
|
||||
let _ = PI;
|
||||
glam::Mat4::IDENTITY
|
||||
}
|
||||
fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
|
||||
match m.species() {
|
||||
Species::Creeper => {
|
||||
// CreeperRenderer.scale: swelling with a wobble.
|
||||
let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha)
|
||||
/ 28.0)
|
||||
.clamp(0.0, 1.0);
|
||||
let wobble = 1.0 + (s * 100.0).sin() * s * 0.01;
|
||||
let s4 = s * s * s * s;
|
||||
let xz = (1.0 + s4 * 0.4) * wobble;
|
||||
let y = (1.0 + s4 * 0.1) / wobble;
|
||||
glam::Mat4::from_scale(glam::Vec3::new(xz, y, xz))
|
||||
}
|
||||
_ => glam::Mat4::IDENTITY,
|
||||
}
|
||||
}
|
||||
/// Draw a part tree with a pose map, texture rect, colour and light.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn draw(
|
||||
part: &Part,
|
||||
base: glam::Mat4,
|
||||
poses: &Poses,
|
||||
uv: [f32; 4],
|
||||
color: u32,
|
||||
light: u32,
|
||||
overlay: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let p = poses.pose(part);
|
||||
let m = base
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(p[0], p[1], p[2]) / 16.0)
|
||||
* glam::Mat4::from_quat(glam::Quat::from_euler(
|
||||
glam::EulerRot::ZYX,
|
||||
p[5],
|
||||
p[4],
|
||||
p[3],
|
||||
))
|
||||
* glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8]));
|
||||
if p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
|
||||
return;
|
||||
}
|
||||
for poly in &part.polygons {
|
||||
for v in poly.vertices {
|
||||
let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0);
|
||||
out.push(Vertex {
|
||||
pos: pos.to_array(),
|
||||
uv: [
|
||||
uv[0] + (uv[2] - uv[0]) * v[3],
|
||||
uv[1] + (uv[3] - uv[1]) * v[4],
|
||||
],
|
||||
layer: overlay,
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
}
|
||||
for c in &part.children {
|
||||
draw(c, m, poses, uv, color, light, overlay, out);
|
||||
}
|
||||
}
|
||||
/// Render a mob with its variant model, texture and layers.
|
||||
pub fn render(
|
||||
m: &Mob,
|
||||
alpha: f32,
|
||||
camera: glam::DVec3,
|
||||
atlas: Atlas,
|
||||
light: u32,
|
||||
data: &MobData,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let base = base_transform(m, alpha, camera);
|
||||
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
|
||||
let s = anim::state(m, alpha);
|
||||
let (model_key, texture) = body(m);
|
||||
let model = m
|
||||
.kind
|
||||
.layer(&model_key)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| m.kind.model.clone());
|
||||
if let Some(uv) = atlas(&texture) {
|
||||
let mut poses = Poses::new(&model);
|
||||
anim::setup(m, &s, &mut poses, &data.animations);
|
||||
draw(&model, base, &poses, uv, 0xFFFF_FFFF, light, overlay, out);
|
||||
}
|
||||
for layer in layers(m) {
|
||||
let Some(part) = m.kind.layer(&layer.model).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let Some(uv) = atlas(&layer.texture) else {
|
||||
continue;
|
||||
};
|
||||
let mut poses = Poses::new(&part);
|
||||
anim::setup(m, &s, &mut poses, &data.animations);
|
||||
let light = if layer.full_bright {
|
||||
240 | 240 << 8
|
||||
} else {
|
||||
light
|
||||
};
|
||||
draw(&part, base, &poses, uv, layer.color, light, overlay, out);
|
||||
}
|
||||
}
|
||||
/// Render with a fixed texture rect (the earlier API).
|
||||
pub fn render_single(
|
||||
m: &Mob,
|
||||
alpha: f32,
|
||||
camera: glam::DVec3,
|
||||
uv: [f32; 4],
|
||||
light: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let base = base_transform(m, alpha, camera);
|
||||
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
|
||||
let s = anim::state(m, alpha);
|
||||
let model = m.kind.model.clone();
|
||||
let mut poses = Poses::new(&model);
|
||||
anim::setup(m, &s, &mut poses, &std::collections::HashMap::new());
|
||||
draw(&model, base, &poses, uv, 0xFFFF_FFFF, light, overlay, out);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Natural spawning rules: `SpawnPlacements` placement types and each
|
||||
//! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`,
|
||||
//! water animals, bats...), and `finalizeSpawn` (variants, colours, babies,
|
||||
//! equipment).
|
||||
use super::{Mob, MobWorld, Species, data, farm::Climate};
|
||||
use crate::blocks::Fluid;
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
/// Biome facts finalizeSpawn and the spawn rules read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct BiomeFacts {
|
||||
pub climate: Climate,
|
||||
/// Biome temperature at the position (strays in cold biomes, snow foxes).
|
||||
pub temperature: f32,
|
||||
pub snowy: bool,
|
||||
pub swamp: bool,
|
||||
pub ocean: bool,
|
||||
pub mushroom: bool,
|
||||
pub desert: bool,
|
||||
pub jungle: bool,
|
||||
}
|
||||
/// SpawnPlacementTypes for the species.
|
||||
pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
|
||||
let id = format!("minecraft:{}", super::species::def(species).name);
|
||||
match w.data.placement(&id) {
|
||||
data::Placement::OnGround => {
|
||||
let below = w.data.state(w.world.block(x, y - 1, z));
|
||||
let valid = match species {
|
||||
Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0,
|
||||
Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0,
|
||||
_ => below.flags & data::VALID_SPAWN != 0,
|
||||
};
|
||||
valid && empty(w, x, y, z) && empty(w, x, y + 1, z)
|
||||
}
|
||||
data::Placement::InWater => {
|
||||
w.fluid(x, y, z) == Fluid::Water
|
||||
&& w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0
|
||||
}
|
||||
data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava,
|
||||
data::Placement::NoRestrictions => true,
|
||||
}
|
||||
}
|
||||
fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
|
||||
w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0
|
||||
}
|
||||
/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0).
|
||||
pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool {
|
||||
let light = w.world.light(x, y, z);
|
||||
let (sky, block) = (i32::from(light >> 4), i32::from(light & 15));
|
||||
if sky > random.next_int_bound(32).unwrap_or(0) {
|
||||
return false;
|
||||
}
|
||||
if block > 0 {
|
||||
return false;
|
||||
}
|
||||
let darken = if w.thundering { 10 } else { w.sky_darken() };
|
||||
(sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0)
|
||||
}
|
||||
/// The species' checkSpawnRules for natural spawns.
|
||||
pub fn spawn_rules_ok(
|
||||
species: Species,
|
||||
w: &MobWorld,
|
||||
random: &mut impl RandomSource,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> bool {
|
||||
use Species as S;
|
||||
let below = w.block_name(x, y - 1, z).to_owned();
|
||||
let light = w.world.light(x, y, z);
|
||||
let raw = i32::from(light >> 4).max(i32::from(light & 15));
|
||||
match species {
|
||||
// Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright.
|
||||
S::Pig
|
||||
| S::Cow
|
||||
| S::Sheep
|
||||
| S::Chicken
|
||||
| S::Horse
|
||||
| S::Donkey
|
||||
| S::Llama
|
||||
| S::Wolf
|
||||
| S::Cat
|
||||
| S::Fox
|
||||
| S::Rabbit
|
||||
| S::Goat
|
||||
| S::Panda
|
||||
| S::Armadillo
|
||||
| S::Mooshroom
|
||||
| S::Turtle
|
||||
| S::Frog
|
||||
| S::Bee => {
|
||||
let tag = match species {
|
||||
S::Mooshroom => "minecraft:mooshrooms_spawnable_on",
|
||||
S::Wolf => "minecraft:wolves_spawnable_on",
|
||||
S::Fox => "minecraft:foxes_spawnable_on",
|
||||
S::Rabbit => "minecraft:rabbits_spawnable_on",
|
||||
S::Goat => "minecraft:goats_spawnable_on",
|
||||
S::Armadillo => "minecraft:armadillo_spawnable_on",
|
||||
S::Turtle => "minecraft:turtles_spawnable_on",
|
||||
S::Frog => "minecraft:frogs_spawnable_on",
|
||||
_ => "minecraft:animals_spawnable_on",
|
||||
};
|
||||
w.has_tag(tag, &below) && raw > 8
|
||||
}
|
||||
S::PolarBear => {
|
||||
w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below)
|
||||
|| w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8
|
||||
}
|
||||
S::Ocelot | S::Parrot => {
|
||||
(w.has_tag("minecraft:parrots_spawnable_on", &below)
|
||||
|| below.contains("leaves")
|
||||
|| below == "minecraft:grass_block")
|
||||
&& raw > 8
|
||||
}
|
||||
S::Bat => {
|
||||
// Bat.checkBatSpawnRules: below sea level, dark.
|
||||
if y >= 63 {
|
||||
return false;
|
||||
}
|
||||
let block = i32::from(light & 15).max(i32::from(light >> 4));
|
||||
block <= random.next_int_bound(4).unwrap_or(0)
|
||||
}
|
||||
S::Slime => {
|
||||
// Swamp at night by moon brightness, or slime chunks below y 40.
|
||||
y < 40 && random.next_int_bound(10).unwrap_or(1) == 0
|
||||
}
|
||||
S::Squid
|
||||
| S::GlowSquid
|
||||
| S::Cod
|
||||
| S::Salmon
|
||||
| S::TropicalFish
|
||||
| S::Pufferfish
|
||||
| S::Dolphin => {
|
||||
// WaterAnimal.checkSurfaceWaterAnimalSpawnRules: between sea level - 13 and sea level.
|
||||
let in_band = (50..=62).contains(&y);
|
||||
in_band && w.fluid(x, y - 1, z) == Fluid::Water && w.fluid(x, y + 1, z) == Fluid::Water
|
||||
|| matches!(species, S::GlowSquid) && y < 30
|
||||
}
|
||||
S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay",
|
||||
S::Strider => w.fluid(x, y, z) == Fluid::Lava,
|
||||
S::Ghast
|
||||
| S::MagmaCube
|
||||
| S::ZombifiedPiglin
|
||||
| S::Piglin
|
||||
| S::Hoglin
|
||||
| S::Blaze
|
||||
| S::WitherSkeleton
|
||||
| S::Enderman
|
||||
if w.nether =>
|
||||
{
|
||||
!w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast
|
||||
}
|
||||
S::Husk | S::Stray => dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z),
|
||||
S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z),
|
||||
_ => {
|
||||
// Monster.checkMonsterSpawnRules
|
||||
!w.nether && dark_enough(w, random, x, y, z) || w.nether
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
|
||||
pub fn finalize(m: &mut Mob, biome: &BiomeFacts) {
|
||||
use Species as S;
|
||||
let climate_index = match biome.climate {
|
||||
Climate::Temperate => 0,
|
||||
Climate::Warm => 1,
|
||||
Climate::Cold => 2,
|
||||
};
|
||||
match m.species() {
|
||||
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
|
||||
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
|
||||
S::Mooshroom => m.extra.variant = 0,
|
||||
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => {
|
||||
// Zombie.finalizeSpawn: 5% babies (normal difficulty).
|
||||
if m.random.next_float() < 0.05 {
|
||||
m.extra.age = i32::MIN / 2;
|
||||
}
|
||||
if m.species() != S::Drowned && m.random.next_float() < 0.01 {
|
||||
let r = m.random.next_int_bound(3).unwrap_or(0);
|
||||
m.extra.main_hand = Some(
|
||||
if r == 0 {
|
||||
"minecraft:iron_sword"
|
||||
} else {
|
||||
"minecraft:iron_shovel"
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if m.species() == S::Drowned && m.random.next_float() < 0.0625 {
|
||||
m.extra.main_hand = Some(
|
||||
if m.random.next_int_bound(16).unwrap_or(1) < 10 {
|
||||
"minecraft:trident"
|
||||
} else {
|
||||
"minecraft:fishing_rod"
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if m.species() == S::ZombieVillager {
|
||||
m.extra.variant = villager_type(biome);
|
||||
m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8;
|
||||
}
|
||||
}
|
||||
S::Villager => {
|
||||
m.extra.variant = villager_type(biome);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// VillagerType.byBiome
|
||||
pub fn villager_type(b: &BiomeFacts) -> u8 {
|
||||
if b.desert {
|
||||
1
|
||||
} else if b.jungle {
|
||||
2
|
||||
} else if b.snowy {
|
||||
4
|
||||
} else if b.swamp {
|
||||
5
|
||||
} else if b.climate == Climate::Warm {
|
||||
3
|
||||
} else if b.climate == Climate::Cold && b.temperature < 0.4 {
|
||||
6
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,384 @@
|
||||
//! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton,
|
||||
//! stray, bogged, wither skeleton): goals, bow attacks, water conversion.
|
||||
use super::{
|
||||
Mob, MobEvent, Species, Who,
|
||||
goals::{
|
||||
Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack,
|
||||
NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone,
|
||||
},
|
||||
};
|
||||
use crate::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
S::Zombie | S::Husk | S::ZombieVillager => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(8, LookAtPlayer::new(8.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
g.add(3, MeleeAttack::new(1.0, false).zombie());
|
||||
g.add(7, Stroll::avoiding_water(1.0));
|
||||
let t = &mut m.ai.targets;
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
hurt.alert_except = vec![S::ZombifiedPiglin];
|
||||
t.add(1, hurt);
|
||||
t.add(2, NearestTarget::player(true));
|
||||
t.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::Villager, S::WanderingTrader], false),
|
||||
);
|
||||
t.add(3, NearestTarget::species(&[S::IronGolem], true));
|
||||
t.add(
|
||||
5,
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby),
|
||||
true,
|
||||
)
|
||||
.interval(10),
|
||||
);
|
||||
}
|
||||
S::Drowned => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, DrownedGoToWater::default());
|
||||
g.add(2, MeleeAttack::new(1.0, false).zombie());
|
||||
g.add(5, Stroll::new(1.0));
|
||||
g.add(8, LookAtPlayer::new(8.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
let t = &mut m.ai.targets;
|
||||
let mut hurt = HurtByTarget::new().alert();
|
||||
hurt.alert_except = vec![S::ZombifiedPiglin];
|
||||
t.add(1, hurt);
|
||||
t.add(
|
||||
2,
|
||||
NearestTarget::player(false).when(|m, w| drowned_can_attack(m, w)),
|
||||
);
|
||||
t.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::Villager, S::WanderingTrader], false),
|
||||
);
|
||||
t.add(3, NearestTarget::species(&[S::IronGolem], true));
|
||||
t.add(3, NearestTarget::species(&[S::Axolotl], true).interval(10));
|
||||
m.ai.nav.can_float = false;
|
||||
}
|
||||
S::Skeleton | S::Stray | S::Bogged | S::WitherSkeleton => {
|
||||
let species = m.species();
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(2, RestrictSun);
|
||||
g.add(3, FleeSun::new(1.0));
|
||||
g.add(
|
||||
3,
|
||||
AvoidEntity::new(Avoid::Species(vec![S::Wolf]), 6.0, 1.0, 1.2),
|
||||
);
|
||||
g.add(5, Stroll::avoiding_water(1.0));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
g.add(6, RandomLookAround::default());
|
||||
let t = &mut m.ai.targets;
|
||||
t.add(1, HurtByTarget::new());
|
||||
t.add(2, NearestTarget::player(true));
|
||||
t.add(3, NearestTarget::species(&[S::IronGolem], true));
|
||||
t.add(
|
||||
3,
|
||||
NearestTarget::new(
|
||||
super::goals::Prey::Filter(|s| s.species == Species::Turtle && s.baby),
|
||||
true,
|
||||
)
|
||||
.interval(10),
|
||||
);
|
||||
if species == S::WitherSkeleton {
|
||||
t.add(
|
||||
3,
|
||||
NearestTarget::species(&[S::Piglin, S::PiglinBrute], true),
|
||||
);
|
||||
m.extra.main_hand = Some("minecraft:stone_sword".into());
|
||||
m.ai.goals.add(4, MeleeAttack::new(1.2, false));
|
||||
} else {
|
||||
m.extra.main_hand = Some("minecraft:bow".into());
|
||||
let interval = if m.species() == S::Bogged { 70 } else { 40 };
|
||||
m.ai.goals.add(4, BowAttack::new(1.0, interval, 15.0));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn drowned_can_attack(m: &Mob, w: &super::MobWorld) -> bool {
|
||||
// Drowned.okTarget: at night or when the target is in water.
|
||||
let Some(p) = &w.player else { return false };
|
||||
let (x, y, z) = (
|
||||
p.position.x.floor() as i32,
|
||||
p.position.y.floor() as i32,
|
||||
p.position.z.floor() as i32,
|
||||
);
|
||||
!w.daylight || w.fluid(x, y, z) == crate::blocks::Fluid::Water || m.fluids.in_water
|
||||
}
|
||||
/// Zombie drowning conversion (Zombie.DrowningTracker) and husk -> zombie.
|
||||
pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
if matches!(m.species(), Species::Zombie | Species::Husk) && m.alive() {
|
||||
if m.extra.counter2 > 0 {
|
||||
m.extra.counter2 -= 1;
|
||||
if m.extra.counter2 == 0 {
|
||||
let (kind, sound) = if m.species() == Species::Husk {
|
||||
("minecraft:zombie", "entity.husk.converted_to_zombie")
|
||||
} else {
|
||||
("minecraft:drowned", "entity.zombie.converted_to_drowned")
|
||||
};
|
||||
cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
|
||||
cx.events.push(MobEvent::SpawnKind {
|
||||
kind: kind.into(),
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
setup: super::SpawnSetup {
|
||||
baby: m.is_baby(),
|
||||
yaw: m.yaw,
|
||||
persistent: m.persistent,
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
m.removed = true;
|
||||
}
|
||||
} else if m.fluids.eye_in_water {
|
||||
m.extra.counter += 1;
|
||||
if m.extra.counter >= 600 {
|
||||
m.extra.counter2 = 300;
|
||||
}
|
||||
} else {
|
||||
m.extra.counter = -1;
|
||||
}
|
||||
}
|
||||
if m.species() == Species::Drowned {
|
||||
// Drowned.updateSwimming / travel: swim when the target is in water.
|
||||
let wants =
|
||||
m.ai.target
|
||||
.and_then(|t| cx.w.target_info(t))
|
||||
.is_some_and(|t| {
|
||||
let (x, y, z) = (
|
||||
t.position.x.floor() as i32,
|
||||
t.position.y.floor() as i32,
|
||||
t.position.z.floor() as i32,
|
||||
);
|
||||
cx.w.fluid(x, y, z) == crate::blocks::Fluid::Water
|
||||
});
|
||||
m.extra.flag = wants;
|
||||
if m.fluids.in_water && wants {
|
||||
m.ai.nav.kind = super::nav::NavKind::Water { breach: false };
|
||||
} else if m.ai.nav.kind != super::nav::NavKind::Ground {
|
||||
m.ai.nav.kind = super::nav::NavKind::Ground;
|
||||
m.ai.nav.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// RangedBowAttackGoal for skeletons.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BowAttack {
|
||||
speed: f64,
|
||||
interval_min: i32,
|
||||
radius_sqr: f32,
|
||||
attack_time: i32,
|
||||
see_time: i32,
|
||||
strafe_clockwise: bool,
|
||||
strafe_back: bool,
|
||||
strafe_time: i32,
|
||||
}
|
||||
impl BowAttack {
|
||||
pub fn new(speed: f64, interval_min: i32, radius: f32) -> Self {
|
||||
Self {
|
||||
speed,
|
||||
interval_min,
|
||||
radius_sqr: radius * radius,
|
||||
attack_time: -1,
|
||||
see_time: 0,
|
||||
strafe_clockwise: false,
|
||||
strafe_back: false,
|
||||
strafe_time: -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn holding_bow(m: &Mob) -> bool {
|
||||
m.extra.main_hand.as_deref() == Some("minecraft:bow")
|
||||
}
|
||||
impl Goal for BowAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
m.ai.target.is_some() && holding_bow(m)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
(self.can_use(m, cx) || !m.ai.nav.is_done()) && holding_bow(m)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.ai.aggressive = true;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.ai.aggressive = false;
|
||||
self.see_time = 0;
|
||||
self.attack_time = -1;
|
||||
m.extra.using_item = 0;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(who) = m.ai.target else { return };
|
||||
let Some(t) = cx.w.target_info(who) else {
|
||||
return;
|
||||
};
|
||||
let d = m.distance_sqr(t.position);
|
||||
let sees = m.sees(cx.w, who);
|
||||
if sees != (self.see_time > 0) {
|
||||
self.see_time = 0;
|
||||
}
|
||||
if sees {
|
||||
self.see_time += 1;
|
||||
} else {
|
||||
self.see_time -= 1;
|
||||
}
|
||||
if d <= f64::from(self.radius_sqr) && self.see_time >= 20 {
|
||||
m.nav_stop();
|
||||
self.strafe_time += 1;
|
||||
} else {
|
||||
m.nav_move_to_entity(
|
||||
cx.w,
|
||||
[t.position.x, t.position.y, t.position.z],
|
||||
1,
|
||||
self.speed,
|
||||
);
|
||||
self.strafe_time = -1;
|
||||
}
|
||||
if self.strafe_time >= 20 {
|
||||
if m.random.next_float() < 0.3 {
|
||||
self.strafe_clockwise = !self.strafe_clockwise;
|
||||
}
|
||||
if m.random.next_float() < 0.3 {
|
||||
self.strafe_back = !self.strafe_back;
|
||||
}
|
||||
self.strafe_time = 0;
|
||||
}
|
||||
let eye = [t.position.x, t.eye_y, t.position.z];
|
||||
if self.strafe_time > -1 {
|
||||
if d > f64::from(self.radius_sqr * 0.75) {
|
||||
self.strafe_back = false;
|
||||
} else if d < f64::from(self.radius_sqr * 0.25) {
|
||||
self.strafe_back = true;
|
||||
}
|
||||
m.ai.mov.strafe(
|
||||
if self.strafe_back { -0.5 } else { 0.5 },
|
||||
if self.strafe_clockwise { 0.5 } else { -0.5 },
|
||||
);
|
||||
m.turn_to(eye, 30.0, 30.0);
|
||||
} else {
|
||||
m.look_at_speed(eye, 30.0, 30.0);
|
||||
}
|
||||
if m.extra.using_item > 0 {
|
||||
if !sees && self.see_time < -60 {
|
||||
m.extra.using_item = 0;
|
||||
} else if sees {
|
||||
let pull = m.extra.using_item;
|
||||
if pull >= 20 {
|
||||
m.extra.using_item = 0;
|
||||
perform_ranged_attack(m, who, cx, bow_power(pull));
|
||||
self.attack_time = self.interval_min;
|
||||
}
|
||||
}
|
||||
if m.extra.using_item > 0 {
|
||||
m.extra.using_item += 1;
|
||||
}
|
||||
} else {
|
||||
self.attack_time -= 1;
|
||||
if self.attack_time <= 0 && self.see_time >= -60 {
|
||||
m.extra.using_item = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// BowItem.getPowerForTime
|
||||
pub fn bow_power(ticks: i32) -> f32 {
|
||||
let t = ticks as f32 / 20.0;
|
||||
((t * t + t * 2.0) / 3.0).min(1.0)
|
||||
}
|
||||
/// AbstractSkeleton.performRangedAttack: aim 20% above the target's lower
|
||||
/// third, speed 1.6, uncertainty 14 - 4 * difficulty.
|
||||
pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) {
|
||||
let Some(t) = cx.w.target_info(who) else {
|
||||
return;
|
||||
};
|
||||
let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z);
|
||||
let height = t.bounds.max_position().y - t.bounds.min_position().y;
|
||||
let xd = t.position.x - m.position.x;
|
||||
let yd = t.position.y + height / 3.0 - start.y;
|
||||
let zd = t.position.z - m.position.z;
|
||||
let dist = (xd * xd + zd * zd).sqrt();
|
||||
// AbstractArrow.setBaseDamageFromMob: power * 2 + triangle(difficulty * 0.11, 0.57425).
|
||||
let base = f64::from(power) * 2.0 + m.random.triangle(2.0 * 0.11, 0.574_25);
|
||||
let effect = match m.species() {
|
||||
Species::Stray => Some(("minecraft:slowness", 600)),
|
||||
Species::Bogged => Some(("minecraft:poison", 100)),
|
||||
_ => None,
|
||||
};
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: base,
|
||||
critical: false,
|
||||
effect,
|
||||
},
|
||||
start,
|
||||
Some(Who::Mob(m.id)),
|
||||
);
|
||||
p.shoot(
|
||||
&mut m.random,
|
||||
[xd, yd + dist * 0.2, zd],
|
||||
1.6,
|
||||
(14 - 2 * 4) as f32,
|
||||
);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 1.0 / (m.random.next_float() * 0.4 + 0.8);
|
||||
cx.events.push(MobEvent::Sound(
|
||||
"entity.skeleton.shoot",
|
||||
m.center(),
|
||||
1.0,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
/// Drowned.DrownedGoToWaterGoal (simplified to "head for water by day").
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DrownedGoToWater {
|
||||
wanted: [f64; 3],
|
||||
}
|
||||
impl Goal for DrownedGoToWater {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !cx.w.daylight || m.fluids.in_water {
|
||||
return false;
|
||||
}
|
||||
let (bx, by, bz) = (
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
);
|
||||
for _ in 0..10 {
|
||||
let p = [
|
||||
bx + m.random.next_int_bound(20).unwrap_or(0) - 10,
|
||||
by + 2 - m.random.next_int_bound(8).unwrap_or(0),
|
||||
bz + m.random.next_int_bound(20).unwrap_or(0) - 10,
|
||||
];
|
||||
if cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water {
|
||||
self.wanted = [
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]),
|
||||
f64::from(p[2]) + 0.5,
|
||||
];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
!m.ai.nav.is_done()
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.nav_move_to(cx.w, self.wanted, 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! What mobs read from the level: block solidity, ray clipping for line of
|
||||
//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent
|
||||
//! values and the positions of other entities.
|
||||
use super::{MobWorld, Seen, Species, Who, data};
|
||||
use crate::{blocks::Fluid, collisions::SceneCollisions};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
};
|
||||
|
||||
/// Where a target entity is this tick.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TargetInfo {
|
||||
pub position: Vec3,
|
||||
pub eye_y: f64,
|
||||
pub bounds: Aabb,
|
||||
pub alive: bool,
|
||||
pub is_player: bool,
|
||||
pub creative: bool,
|
||||
}
|
||||
impl MobWorld<'_> {
|
||||
/// BlockState.isSolid (the legacy solid flag).
|
||||
pub fn solid(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
self.data.state(self.world.block(x, y, z)).flags & data::SOLID != 0
|
||||
}
|
||||
pub fn fluid(&self, x: i32, y: i32, z: i32) -> Fluid {
|
||||
self.facts.get(self.world.block(x, y, z)).fluid
|
||||
}
|
||||
pub fn block_name(&self, x: i32, y: i32, z: i32) -> &str {
|
||||
&self.facts.get(self.world.block(x, y, z)).name
|
||||
}
|
||||
pub fn has_tag(&self, tag: &str, block: &str) -> bool {
|
||||
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
|
||||
}
|
||||
/// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss.
|
||||
pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if fluids_block && self.facts.get(state).fluid != Fluid::None {
|
||||
return Some(());
|
||||
}
|
||||
if self.facts.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|_| ())
|
||||
});
|
||||
matches!(result, Ok(None))
|
||||
}
|
||||
/// LivingEntity.hasLineOfSight: eye to eye within 128 blocks.
|
||||
pub fn line_of_sight(&self, from_eye: Vec3, to: Vec3) -> bool {
|
||||
let d =
|
||||
(to.x - from_eye.x).powi(2) + (to.y - from_eye.y).powi(2) + (to.z - from_eye.z).powi(2);
|
||||
if d > 128.0 * 128.0 {
|
||||
return false;
|
||||
}
|
||||
self.clear_between(from_eye, to, false)
|
||||
}
|
||||
/// Level.canSeeSky: sky light 15 at the position (no roof above).
|
||||
pub fn can_see_sky(&self, x: i32, y: i32, z: i32) -> bool {
|
||||
if self.nether {
|
||||
return false;
|
||||
}
|
||||
self.world.light(x, y, z) >> 4 == 15
|
||||
}
|
||||
/// Level.getLightLevelDependentMagicValue: the dimension's brightness curve
|
||||
/// at the raw (sky darkened) light level.
|
||||
pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 {
|
||||
let light = self.world.light(x, y, z);
|
||||
let sky = i32::from(light >> 4) - self.sky_darken();
|
||||
let level = sky.max(i32::from(light & 15)).clamp(0, 15) as f32;
|
||||
// DimensionType.getBrightness with ambient light 0 (overworld) / 0.1 (nether).
|
||||
let f = level / 15.0;
|
||||
let base = f / (4.0 - 3.0 * f);
|
||||
if self.nether { 0.1 + base * 0.9 } else { base }
|
||||
}
|
||||
pub fn sky_darken(&self) -> i32 {
|
||||
if self.daylight { 0 } else { 11 }
|
||||
}
|
||||
pub fn target_info(&self, who: Who) -> Option<TargetInfo> {
|
||||
match who {
|
||||
Who::Player => self.player.as_ref().map(|p| TargetInfo {
|
||||
position: p.position,
|
||||
eye_y: p.eye[1],
|
||||
bounds: p.bounds,
|
||||
alive: p.alive,
|
||||
is_player: true,
|
||||
creative: p.creative,
|
||||
}),
|
||||
Who::Mob(id) => self.seen(id).map(|s| TargetInfo {
|
||||
position: s.position,
|
||||
eye_y: s.eye_y,
|
||||
bounds: s.bounds,
|
||||
alive: s.alive,
|
||||
is_player: false,
|
||||
creative: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
pub fn seen(&self, id: u32) -> Option<&Seen> {
|
||||
self.others.iter().find(|s| s.id == id)
|
||||
}
|
||||
/// Living mobs of the given species within `range` of `from`, nearest first.
|
||||
pub fn nearby<'s>(
|
||||
&'s self,
|
||||
from: Vec3,
|
||||
range: f64,
|
||||
pred: impl Fn(&Seen) -> bool + 's,
|
||||
) -> impl Iterator<Item = &'s Seen> + 's {
|
||||
let mut v: Vec<&Seen> = self
|
||||
.others
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
s.alive
|
||||
&& (s.position.x - from.x).abs() <= range
|
||||
&& (s.position.y - from.y).abs() <= range
|
||||
&& (s.position.z - from.z).abs() <= range
|
||||
})
|
||||
.filter(move |s| pred(s))
|
||||
.collect();
|
||||
v.sort_by(|a, b| {
|
||||
let da = (a.position.x - from.x).powi(2)
|
||||
+ (a.position.y - from.y).powi(2)
|
||||
+ (a.position.z - from.z).powi(2);
|
||||
let db = (b.position.x - from.x).powi(2)
|
||||
+ (b.position.y - from.y).powi(2)
|
||||
+ (b.position.z - from.z).powi(2);
|
||||
da.total_cmp(&db)
|
||||
});
|
||||
v.into_iter()
|
||||
}
|
||||
pub fn count_species(&self, species: Species) -> usize {
|
||||
self.others
|
||||
.iter()
|
||||
.filter(|s| s.species == species && s.alive)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Projectiles fired by mobs and thrown by the player: arrows
|
||||
//! (`AbstractArrow`, gravity 0.05), throwables (`ThrowableProjectile`:
|
||||
//! snowballs, eggs, ender pearls, gravity 0.03) and fireballs
|
||||
//! (`AbstractHurtingProjectile`: no gravity, 0.1 acceleration, 0.95 inertia).
|
||||
//! The game applies the effects of a hit.
|
||||
use crate::mobs::Who;
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
random::RandomSource,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ProjectileKind {
|
||||
/// Arrow with its base damage, critical flag and tipped/stray/bogged effect.
|
||||
Arrow {
|
||||
base_damage: f64,
|
||||
critical: bool,
|
||||
effect: Option<(&'static str, i32)>,
|
||||
},
|
||||
Snowball,
|
||||
Egg,
|
||||
EnderPearl,
|
||||
SmallFireball,
|
||||
LargeFireball {
|
||||
power: i32,
|
||||
},
|
||||
LlamaSpit,
|
||||
/// Splash potion thrown by witches: effect id, duration.
|
||||
Potion {
|
||||
effect: &'static str,
|
||||
ticks: i32,
|
||||
amplifier: i32,
|
||||
color: u32,
|
||||
},
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Projectile {
|
||||
pub kind: ProjectileKind,
|
||||
pub owner: Option<Who>,
|
||||
pub position: Vec3,
|
||||
pub previous: Vec3,
|
||||
pub velocity: Vec3,
|
||||
pub yaw: f32,
|
||||
pub pitch: f32,
|
||||
pub age: u32,
|
||||
pub stuck: bool,
|
||||
/// Whether the projectile has left its owner's box (Projectile.leftOwner).
|
||||
pub left_owner: bool,
|
||||
}
|
||||
/// What a projectile struck this tick.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Hit {
|
||||
None,
|
||||
Block {
|
||||
pos: [i32; 3],
|
||||
at: Vec3,
|
||||
face: [i32; 3],
|
||||
},
|
||||
Entity {
|
||||
who: Who,
|
||||
at: Vec3,
|
||||
},
|
||||
}
|
||||
/// The world a projectile flies through: block ray clipping, water, and
|
||||
/// the boxes of entities it could hit.
|
||||
pub trait ProjectileWorld {
|
||||
fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])>;
|
||||
fn in_water(&self, at: Vec3) -> bool;
|
||||
fn targets(&self) -> &[(Who, Aabb)];
|
||||
}
|
||||
impl Projectile {
|
||||
pub fn new(kind: ProjectileKind, position: Vec3, owner: Option<Who>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
owner,
|
||||
position,
|
||||
previous: position,
|
||||
velocity: Vec3::ZERO,
|
||||
yaw: 0.0,
|
||||
pitch: 0.0,
|
||||
age: 0,
|
||||
stuck: false,
|
||||
left_owner: false,
|
||||
}
|
||||
}
|
||||
pub fn is_arrow(&self) -> bool {
|
||||
matches!(self.kind, ProjectileKind::Arrow { .. })
|
||||
}
|
||||
pub fn is_fireball(&self) -> bool {
|
||||
matches!(
|
||||
self.kind,
|
||||
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. }
|
||||
)
|
||||
}
|
||||
fn gravity(&self) -> f64 {
|
||||
match self.kind {
|
||||
ProjectileKind::Arrow { .. } => 0.05,
|
||||
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 0.0,
|
||||
ProjectileKind::LlamaSpit => 0.06,
|
||||
ProjectileKind::Potion { .. } => 0.05,
|
||||
_ => 0.03,
|
||||
}
|
||||
}
|
||||
/// Projectile.shoot: normalized direction plus triangular noise, times speed.
|
||||
pub fn shoot(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
dir: [f64; 3],
|
||||
speed: f32,
|
||||
uncertainty: f32,
|
||||
) {
|
||||
let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2])
|
||||
.sqrt()
|
||||
.max(1.0e-9);
|
||||
let spread = 0.017_227_5 * f64::from(uncertainty);
|
||||
let v = [
|
||||
(dir[0] / len + random.triangle(0.0, spread)) * f64::from(speed),
|
||||
(dir[1] / len + random.triangle(0.0, spread)) * f64::from(speed),
|
||||
(dir[2] / len + random.triangle(0.0, spread)) * f64::from(speed),
|
||||
];
|
||||
self.velocity = Vec3::new(v[0], v[1], v[2]);
|
||||
self.update_rotation();
|
||||
}
|
||||
/// Projectile.shootFromRotation for player throws.
|
||||
pub fn shoot_from_rotation(
|
||||
&mut self,
|
||||
random: &mut impl RandomSource,
|
||||
pitch: f32,
|
||||
yaw: f32,
|
||||
offset: f32,
|
||||
speed: f32,
|
||||
uncertainty: f32,
|
||||
source_velocity: Vec3,
|
||||
source_on_ground: bool,
|
||||
) {
|
||||
let (p, y, o) = (
|
||||
pitch.to_radians(),
|
||||
yaw.to_radians(),
|
||||
(pitch + offset).to_radians(),
|
||||
);
|
||||
let dir = [
|
||||
f64::from(-y.sin() * p.cos()),
|
||||
f64::from(-o.sin()),
|
||||
f64::from(y.cos() * p.cos()),
|
||||
];
|
||||
self.shoot(random, dir, speed, uncertainty);
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x + source_velocity.x,
|
||||
self.velocity.y
|
||||
+ if source_on_ground {
|
||||
0.0
|
||||
} else {
|
||||
source_velocity.y
|
||||
},
|
||||
self.velocity.z + source_velocity.z,
|
||||
);
|
||||
}
|
||||
/// AbstractHurtingProjectile: movement along the direction at the acceleration power.
|
||||
pub fn fireball(
|
||||
kind: ProjectileKind,
|
||||
position: Vec3,
|
||||
owner: Option<Who>,
|
||||
dir: [f64; 3],
|
||||
) -> Self {
|
||||
let mut p = Self::new(kind, position, owner);
|
||||
let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2])
|
||||
.sqrt()
|
||||
.max(1.0e-9);
|
||||
p.velocity = Vec3::new(dir[0] / len * 0.1, dir[1] / len * 0.1, dir[2] / len * 0.1);
|
||||
p.update_rotation();
|
||||
p
|
||||
}
|
||||
fn update_rotation(&mut self) {
|
||||
let v = self.velocity;
|
||||
let sd = (v.x * v.x + v.z * v.z).sqrt();
|
||||
self.yaw = v.x.atan2(v.z).to_degrees() as f32;
|
||||
self.pitch = v.y.atan2(sd).to_degrees() as f32;
|
||||
}
|
||||
/// One tick: returns whether to keep the projectile and what it hit.
|
||||
pub fn tick(&mut self, w: &impl ProjectileWorld) -> (bool, Hit) {
|
||||
self.previous = self.position;
|
||||
self.age += 1;
|
||||
if self.stuck {
|
||||
// AbstractArrow despawns 1200 ticks after sticking.
|
||||
return (self.age < 1200, Hit::None);
|
||||
}
|
||||
let water = w.in_water(self.position);
|
||||
match self.kind {
|
||||
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => {
|
||||
let inertia = if water { 0.8 } else { 0.95 };
|
||||
let v = self.velocity;
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9);
|
||||
self.velocity = Vec3::new(
|
||||
(v.x + v.x / len * 0.1) * inertia,
|
||||
(v.y + v.y / len * 0.1) * inertia,
|
||||
(v.z + v.z / len * 0.1) * inertia,
|
||||
);
|
||||
}
|
||||
ProjectileKind::Arrow { .. } => {}
|
||||
_ => {
|
||||
// ThrowableProjectile: gravity, then inertia.
|
||||
self.velocity.y -= self.gravity();
|
||||
let inertia = if water { 0.8 } else { 0.99 };
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * inertia,
|
||||
self.velocity.y * inertia,
|
||||
self.velocity.z * inertia,
|
||||
);
|
||||
}
|
||||
}
|
||||
let from = self.position;
|
||||
let to = Vec3::new(
|
||||
from.x + self.velocity.x,
|
||||
from.y + self.velocity.y,
|
||||
from.z + self.velocity.z,
|
||||
);
|
||||
let block = w.clip(from, to);
|
||||
let end = block.map_or(to, |b| b.0);
|
||||
// ProjectileUtil.getEntityHitResult: boxes inflated by 0.3 along the path.
|
||||
let mut best: Option<(Who, Vec3, f64)> = None;
|
||||
for (who, b) in w.targets() {
|
||||
if Some(*who) == self.owner && !self.left_owner {
|
||||
continue;
|
||||
}
|
||||
let inflated = b.inflate(Vec3::new(0.3, 0.3, 0.3));
|
||||
if let Some(at) = inflated.clip(from, end) {
|
||||
let d = (at.x - from.x).powi(2) + (at.y - from.y).powi(2) + (at.z - from.z).powi(2);
|
||||
if best.is_none_or(|bb| d < bb.2) {
|
||||
best = Some((*who, at, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.left_owner {
|
||||
// Leave the owner once no target box (the owner's) contains us.
|
||||
let owner_box = w
|
||||
.targets()
|
||||
.iter()
|
||||
.find(|(who, _)| Some(*who) == self.owner)
|
||||
.map(|(_, b)| *b);
|
||||
self.left_owner = owner_box
|
||||
.is_none_or(|b| !b.inflate(Vec3::new(1.0, 1.0, 1.0)).contains(self.position));
|
||||
}
|
||||
if let Some((who, at, _)) = best {
|
||||
self.position = at;
|
||||
return (false, Hit::Entity { who, at });
|
||||
}
|
||||
if let Some((at, pos, face)) = block {
|
||||
self.position = at;
|
||||
if self.is_arrow() {
|
||||
// AbstractArrow.onHitBlock: stick, nudged back out of the face.
|
||||
let v = self.velocity;
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9);
|
||||
self.position = Vec3::new(
|
||||
at.x - v.x / len * 0.05,
|
||||
at.y - v.y / len * 0.05,
|
||||
at.z - v.z / len * 0.05,
|
||||
);
|
||||
self.stuck = true;
|
||||
self.age = 0;
|
||||
return (true, Hit::Block { pos, at, face });
|
||||
}
|
||||
return (false, Hit::Block { pos, at, face });
|
||||
}
|
||||
self.position = to;
|
||||
if self.is_arrow() {
|
||||
// AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity.
|
||||
let inertia = if water { 0.6 } else { 0.99 };
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * inertia,
|
||||
self.velocity.y * inertia - self.gravity(),
|
||||
self.velocity.z * inertia,
|
||||
);
|
||||
self.update_rotation();
|
||||
} else if !self.is_fireball() {
|
||||
self.update_rotation();
|
||||
}
|
||||
let alive =
|
||||
self.position.y > -128.0 && self.age < if self.is_fireball() { 1200 } else { 6000 };
|
||||
(alive, Hit::None)
|
||||
}
|
||||
/// AbstractArrow.onHitEntity damage: ceil(speed * base) plus crit bonus.
|
||||
pub fn arrow_damage(&self, random: &mut impl RandomSource) -> f32 {
|
||||
let ProjectileKind::Arrow {
|
||||
base_damage,
|
||||
critical,
|
||||
..
|
||||
} = self.kind
|
||||
else {
|
||||
return 0.0;
|
||||
};
|
||||
let v = self.velocity;
|
||||
let speed = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt();
|
||||
let mut damage = (speed * base_damage).clamp(0.0, f64::from(i32::MAX)).ceil() as i32;
|
||||
if critical {
|
||||
let bonus = random.next_int_bound(damage / 2 + 2).unwrap_or(0);
|
||||
damage = damage.saturating_add(bonus);
|
||||
}
|
||||
damage as f32
|
||||
}
|
||||
/// The item sprite drawn for thrown projectiles (ThrownItemRenderer).
|
||||
pub fn item_sprite(&self) -> Option<&'static str> {
|
||||
Some(match self.kind {
|
||||
ProjectileKind::Snowball => "item/snowball",
|
||||
ProjectileKind::Egg => "item/egg",
|
||||
ProjectileKind::EnderPearl => "item/ender_pearl",
|
||||
ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => {
|
||||
"item/fire_charge"
|
||||
}
|
||||
ProjectileKind::Potion { .. } => "item/splash_potion",
|
||||
ProjectileKind::LlamaSpit => "entity/llama/llama_spit",
|
||||
ProjectileKind::Arrow { .. } => return None,
|
||||
})
|
||||
}
|
||||
/// Render scale of the item billboard (fireball renderers).
|
||||
pub fn sprite_scale(&self) -> f32 {
|
||||
match self.kind {
|
||||
ProjectileKind::LargeFireball { .. } => 3.0,
|
||||
ProjectileKind::SmallFireball => 0.75,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::LegacyRandom;
|
||||
|
||||
struct Empty(Vec<(Who, Aabb)>);
|
||||
impl ProjectileWorld for Empty {
|
||||
fn clip(&self, _: Vec3, _: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> {
|
||||
None
|
||||
}
|
||||
fn in_water(&self, _: Vec3) -> bool {
|
||||
false
|
||||
}
|
||||
fn targets(&self) -> &[(Who, Aabb)] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn snowball_falls_with_throwable_gravity_and_drag() {
|
||||
let mut p = Projectile::new(ProjectileKind::Snowball, Vec3::new(0.0, 100.0, 0.0), None);
|
||||
p.velocity = Vec3::new(1.0, 0.0, 0.0);
|
||||
let w = Empty(vec![]);
|
||||
p.tick(&w);
|
||||
// ThrowableProjectile: gravity before inertia, then move.
|
||||
assert!((p.velocity.y - (-0.03 * 0.99)).abs() < 1e-9);
|
||||
assert!((p.position.x - 0.99).abs() < 1e-9);
|
||||
}
|
||||
#[test]
|
||||
fn arrow_applies_drag_then_gravity_after_moving() {
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: false,
|
||||
effect: None,
|
||||
},
|
||||
Vec3::new(0.0, 100.0, 0.0),
|
||||
None,
|
||||
);
|
||||
p.velocity = Vec3::new(3.0, 0.0, 0.0);
|
||||
let w = Empty(vec![]);
|
||||
p.tick(&w);
|
||||
assert!((p.position.x - 3.0).abs() < 1e-9);
|
||||
assert!((p.velocity.x - 2.97).abs() < 1e-9);
|
||||
assert!((p.velocity.y + 0.05).abs() < 1e-9);
|
||||
}
|
||||
#[test]
|
||||
fn arrow_hits_entity_box_inflated_by_margin() {
|
||||
let target = Aabb::new(Vec3::new(2.0, 99.0, -0.3), Vec3::new(2.6, 100.8, 0.3));
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: false,
|
||||
effect: None,
|
||||
},
|
||||
Vec3::new(0.0, 100.0, 0.0),
|
||||
None,
|
||||
);
|
||||
p.velocity = Vec3::new(3.0, 0.0, 0.0);
|
||||
let w = Empty(vec![(Who::Mob(7), target)]);
|
||||
let (keep, hit) = p.tick(&w);
|
||||
assert!(!keep);
|
||||
assert!(matches!(
|
||||
hit,
|
||||
Hit::Entity {
|
||||
who: Who::Mob(7),
|
||||
..
|
||||
}
|
||||
));
|
||||
let mut r = LegacyRandom::new(1);
|
||||
// ceil(3 * 2) = 6 for a non-critical arrow.
|
||||
assert_eq!(p.arrow_damage(&mut r), 6.0);
|
||||
}
|
||||
#[test]
|
||||
fn fireball_accelerates_along_its_direction() {
|
||||
let mut p = Projectile::fireball(
|
||||
ProjectileKind::SmallFireball,
|
||||
Vec3::new(0.0, 100.0, 0.0),
|
||||
None,
|
||||
[1.0, 0.0, 0.0],
|
||||
);
|
||||
let w = Empty(vec![]);
|
||||
p.tick(&w);
|
||||
// (0.1 + 0.1) * 0.95
|
||||
assert!((p.velocity.x - 0.19).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipFile;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagFile;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.client.animation.AnimationChannel;
|
||||
import net.minecraft.client.animation.AnimationDefinition;
|
||||
import net.minecraft.client.animation.Keyframe;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.entity.SpawnPlacementTypes;
|
||||
import net.minecraft.world.entity.SpawnPlacements;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.EmptyBlockGetter;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.pathfinder.PathComputationType;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.world.level.pathfinder.WalkNodeEvaluator;
|
||||
|
||||
/**
|
||||
* Original exporter of the facts the client's mob AI and renderer read from vanilla code:
|
||||
* per-state pathfinding types (WalkNodeEvaluator.getPathTypeFromState), pathfindability,
|
||||
* spawn-surface predicates, each entity type's spawn placement, and every keyframe
|
||||
* animation definition of the client's entity models.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class VanillaMobDataExporter {
|
||||
/** A level holding one block state at the origin and air elsewhere. */
|
||||
private record OneBlock(BlockState state) implements BlockGetter {
|
||||
public BlockEntity getBlockEntity(BlockPos pos) { return null; }
|
||||
public BlockState getBlockState(BlockPos pos) { return pos.equals(BlockPos.ZERO) ? state : Blocks.AIR.defaultBlockState(); }
|
||||
public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
public int getHeight() { return 384; }
|
||||
public int getMinY() { return -64; }
|
||||
}
|
||||
|
||||
private static JsonArray states() throws Exception {
|
||||
Method pathType = WalkNodeEvaluator.class.getDeclaredMethod("getPathTypeFromState", BlockGetter.class, BlockPos.class);
|
||||
pathType.setAccessible(true);
|
||||
var out = new JsonArray();
|
||||
var empty = EmptyBlockGetter.INSTANCE;
|
||||
for (var state : Block.BLOCK_STATE_REGISTRY) {
|
||||
var level = new OneBlock(state);
|
||||
var type = (PathType) pathType.invoke(null, level, BlockPos.ZERO);
|
||||
var shape = state.getCollisionShape(empty, BlockPos.ZERO);
|
||||
var o = new JsonArray();
|
||||
o.add(type.name());
|
||||
int flags = 0;
|
||||
if (state.isPathfindable(PathComputationType.LAND)) flags |= 1;
|
||||
if (state.isPathfindable(PathComputationType.WATER)) flags |= 2;
|
||||
if (state.isPathfindable(PathComputationType.AIR)) flags |= 4;
|
||||
if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.ZOMBIE)) flags |= 8;
|
||||
if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.OCELOT)) flags |= 16;
|
||||
if (state.isValidSpawn(empty, BlockPos.ZERO, EntityTypes.POLAR_BEAR)) flags |= 32;
|
||||
if (state.isRedstoneConductor(empty, BlockPos.ZERO)) flags |= 64;
|
||||
if (net.minecraft.world.level.NaturalSpawner.isValidEmptySpawnBlock(level, BlockPos.ZERO, state, state.getFluidState(), EntityTypes.ZOMBIE)) flags |= 128;
|
||||
if (state.isFaceSturdy(empty, BlockPos.ZERO, Direction.UP)) flags |= 256;
|
||||
if (state.isSolid()) flags |= 512;
|
||||
if (state.isSolidRender()) flags |= 1024;
|
||||
o.add(flags);
|
||||
o.add(shape.isEmpty() ? 0.0 : shape.max(Direction.Axis.Y));
|
||||
out.add(o);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static JsonObject placements() {
|
||||
var out = new JsonObject();
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE) {
|
||||
var placement = SpawnPlacements.getPlacementType(type);
|
||||
String name = placement == SpawnPlacementTypes.ON_GROUND ? "on_ground"
|
||||
: placement == SpawnPlacementTypes.IN_WATER ? "in_water"
|
||||
: placement == SpawnPlacementTypes.IN_LAVA ? "in_lava" : "no_restrictions";
|
||||
var o = new JsonObject();
|
||||
o.addProperty("placement", name);
|
||||
o.addProperty("heightmap", SpawnPlacements.getHeightmapType(type).getSerializedName());
|
||||
out.add(BuiltInRegistries.ENTITY_TYPE.getKey(type).toString(), o);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static JsonArray vector(org.joml.Vector3fc v) {
|
||||
var a = new JsonArray();
|
||||
a.add(v.x()); a.add(v.y()); a.add(v.z());
|
||||
return a;
|
||||
}
|
||||
|
||||
private static JsonObject definition(AnimationDefinition d) {
|
||||
var o = new JsonObject();
|
||||
o.addProperty("length", d.lengthInSeconds());
|
||||
o.addProperty("looping", d.looping());
|
||||
var bones = new JsonObject();
|
||||
for (var entry : new TreeMap<>(d.boneAnimations()).entrySet()) {
|
||||
var channels = new JsonArray();
|
||||
for (AnimationChannel channel : entry.getValue()) {
|
||||
var c = new JsonObject();
|
||||
var target = channel.target();
|
||||
c.addProperty("target", target == AnimationChannel.Targets.POSITION ? "position"
|
||||
: target == AnimationChannel.Targets.ROTATION ? "rotation" : "scale");
|
||||
var frames = new JsonArray();
|
||||
for (Keyframe k : channel.keyframes()) {
|
||||
var f = new JsonArray();
|
||||
f.add(k.timestamp());
|
||||
f.add(vector(k.preTarget()));
|
||||
f.add(vector(k.postTarget()));
|
||||
f.add(k.interpolation() == AnimationChannel.Interpolations.CATMULLROM ? "catmullrom" : "linear");
|
||||
frames.add(f);
|
||||
}
|
||||
c.add("keyframes", frames);
|
||||
channels.add(c);
|
||||
}
|
||||
bones.add(entry.getKey(), channels);
|
||||
}
|
||||
o.add("bones", bones);
|
||||
return o;
|
||||
}
|
||||
|
||||
private static JsonObject animations(String clientJar) throws Exception {
|
||||
var out = new JsonObject();
|
||||
var names = new TreeSet<String>();
|
||||
try (var zip = new ZipFile(clientJar)) {
|
||||
var entries = zip.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
var name = entries.nextElement().getName();
|
||||
if (name.startsWith("net/minecraft/client/animation/definitions/") && name.endsWith(".class") && !name.contains("$"))
|
||||
names.add(name.substring(0, name.length() - 6).replace('/', '.'));
|
||||
}
|
||||
}
|
||||
for (var name : names) {
|
||||
var cls = Class.forName(name);
|
||||
for (var field : cls.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) && field.getType() == AnimationDefinition.class) {
|
||||
field.setAccessible(true);
|
||||
out.add(cls.getSimpleName() + "." + field.getName(), definition((AnimationDefinition) field.get(null)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Binds one registry's vanilla tags from the jar's data pack, as a server reload would. */
|
||||
private static <T> void bindTags(ZipFile jar, Registry<T> registry, ResourceKey<? extends Registry<T>> key, String folder) throws Exception {
|
||||
var loader = new TagLoader<Holder<T>>((id, required) -> registry.get(id).map(value -> (Holder<T>) value), "tags/" + folder);
|
||||
var definitions = new HashMap<Identifier, List<TagLoader.EntryWithSource>>();
|
||||
var prefix = "data/minecraft/tags/" + folder + "/";
|
||||
var entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
var entry = entries.nextElement();
|
||||
var name = entry.getName();
|
||||
if (!name.startsWith(prefix) || !name.endsWith(".json")) continue;
|
||||
var text = new String(jar.getInputStream(entry).readAllBytes(), StandardCharsets.UTF_8);
|
||||
var file = TagFile.CODEC.parse(JsonOps.INSTANCE, JsonParser.parseString(text)).getOrThrow();
|
||||
var list = new ArrayList<TagLoader.EntryWithSource>();
|
||||
for (var e : file.entries()) list.add(new TagLoader.EntryWithSource(e, "vanilla"));
|
||||
definitions.put(Identifier.parse("minecraft:" + name.substring(prefix.length(), name.length() - 5)), list);
|
||||
}
|
||||
var tags = new HashMap<TagKey<T>, List<Holder<T>>>();
|
||||
loader.build(definitions).forEach((id, values) -> tags.put(TagKey.create(key, id), List.copyOf(values)));
|
||||
registry.prepareTagReload(new TagLoader.LoadResult<>(key, tags)).apply();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
try (var jar = new ZipFile(args[1])) {
|
||||
bindTags(jar, BuiltInRegistries.BLOCK, Registries.BLOCK, "block");
|
||||
bindTags(jar, BuiltInRegistries.FLUID, Registries.FLUID, "fluid");
|
||||
}
|
||||
var result = new JsonObject();
|
||||
result.add("states", states());
|
||||
result.add("placements", placements());
|
||||
result.add("animations", animations(args[1]));
|
||||
Files.writeString(Path.of(args[0]), new Gson().toJson(result), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -343,6 +343,22 @@ def main():
|
||||
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaEntityModelExporter', str(entity_models)],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
# Mob AI and animation facts: per-state path types, spawn placements and the
|
||||
# client's keyframe animation definitions (needs the client jar).
|
||||
mob_data = root / 'mob-data.json'
|
||||
mob_oracle = oracle.with_name('VanillaMobDataExporter.java')
|
||||
mob_sources = base.source_hashes([mob_oracle])
|
||||
if not (previous.get('mob_data_exporters_sha256') == mob_sources and mob_data.exists()
|
||||
and previous.get('client_sha256') == origin['client_sha256']):
|
||||
classes = lab.LOCAL / 'mob-data' / 'classes'; classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
|
||||
with (root / 'mob-data-export.log').open('w') as log:
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
|
||||
'-cp', dependencies, '-d', str(classes), str(mob_oracle)],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaMobDataExporter', str(mob_data), str(jars['client'])],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
creative = root / 'creative-tabs.json'
|
||||
creative_oracle = oracle.with_name('VanillaCreativeTabsExporter.java')
|
||||
creative_sources = base.source_hashes([creative_oracle])
|
||||
@@ -371,6 +387,7 @@ def main():
|
||||
'gameplay_exporters_sha256': gameplay_sources,
|
||||
'entity_model_exporters_sha256': entity_sources,
|
||||
'creative_exporters_sha256': creative_sources,
|
||||
'mob_data_exporters_sha256': mob_sources,
|
||||
'entity_types_exporters_sha256': entity_types_sources,
|
||||
'behaviour_exporters_sha256': behaviour_sources,
|
||||
'model_states_sha256': lab.digest(model_states, 'sha256'), 'data_version': version['world_version'],
|
||||
|
||||
Reference in New Issue
Block a user