Merge remote-tracking branch 'origin/wip/parity-mobs' into t3/minecraft-parity
# Conflicts: # crates/horizon-client/src/game.rs
This commit is contained in:
+102
-119
@@ -21,6 +21,7 @@ mod control;
|
||||
mod options;
|
||||
mod packs;
|
||||
mod screens;
|
||||
mod creatures;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -29,8 +30,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},
|
||||
@@ -334,6 +335,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,
|
||||
@@ -409,6 +411,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)>,
|
||||
@@ -1036,6 +1039,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())
|
||||
@@ -1067,6 +1073,7 @@ 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.use_potion_item(&stack)? {
|
||||
if self.throw_item(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
if &*stack.item == "minecraft:bow" {
|
||||
@@ -2228,17 +2235,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 {
|
||||
@@ -2432,106 +2430,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);
|
||||
@@ -2632,6 +2530,87 @@ impl Game<'_> {
|
||||
/// default mobGriefing rule).
|
||||
fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> {
|
||||
self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false)
|
||||
let mut destroyed = HashSet::new();
|
||||
for j in 0..16 {
|
||||
for k in 0..16 {
|
||||
for l in 0..16 {
|
||||
if !(j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) {
|
||||
continue;
|
||||
}
|
||||
let mut d = [f64::from(j) / 15.0 * 2.0 - 1.0, f64::from(k) / 15.0 * 2.0 - 1.0, f64::from(l) / 15.0 * 2.0 - 1.0];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
d = d.map(|v| v / len);
|
||||
let mut h = radius * (0.7 + self.world.random.next_float() * 0.6);
|
||||
let mut p = center;
|
||||
while h > 0.0 {
|
||||
let b = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
|
||||
let state = self.world.block(b[0], b[1], b[2]);
|
||||
if !self.res.facts.is_air(state) {
|
||||
let f = self.res.facts.get(state);
|
||||
let resistance = if f.fluid != Fluid::None && !f.waterlogged { 100.0 } else { f.explosion_resistance };
|
||||
h -= (resistance + 0.3) * 0.3;
|
||||
if h > 0.0 && f.hardness >= 0.0 {
|
||||
destroyed.insert(b);
|
||||
}
|
||||
}
|
||||
p = [p[0] + d[0] * 0.3, p[1] + d[1] * 0.3, p[2] + d[2] * 0.3];
|
||||
h -= 0.225_000_01;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for b in destroyed {
|
||||
let state = self.world.block(b[0], b[1], b[2]);
|
||||
if self.res.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
// Explosion decay: each drop survives with probability 1 / radius.
|
||||
if self.world.random.next_float() < 1.0 / radius {
|
||||
let drops = self.res.items.block_drops(&self.res.assets.registry, state, None, &mut self.world.random);
|
||||
for d in drops {
|
||||
self.pop_resource(b, d);
|
||||
}
|
||||
}
|
||||
self.world.set(b[0], b[1], b[2], self.world.air)?;
|
||||
}
|
||||
self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7);
|
||||
// Entity damage by distance (exposure approximated as unobstructed).
|
||||
let diameter = f64::from(radius) * 2.0;
|
||||
let mut armor_damage = None;
|
||||
if let Some(player) = self.player.as_mut() {
|
||||
let p = [player.position.x, player.position.y, player.position.z];
|
||||
let dist = ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)).sqrt() / diameter;
|
||||
if dist <= 1.0 {
|
||||
let impact = 1.0 - dist;
|
||||
let damage = ((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32;
|
||||
if let Some(id) = self.motion.health.damage.id("minecraft:explosion") {
|
||||
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, damage);
|
||||
armor_damage = Some(damage);
|
||||
}
|
||||
let (dx, dy, dz) = (p[0] - center[0], p[1] - center[1], p[2] - center[2]);
|
||||
let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4);
|
||||
player.velocity = Vec3::new(player.velocity.x + dx / l * impact, player.velocity.y + dy / l * impact, player.velocity.z + dz / l * impact);
|
||||
}
|
||||
}
|
||||
if let Some(d) = armor_damage
|
||||
&& !self.creative
|
||||
{
|
||||
self.hurt_armor(d);
|
||||
}
|
||||
for m in &mut self.mobs {
|
||||
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;
|
||||
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(())
|
||||
}
|
||||
fn tick_block_entities(&mut self) -> Result<()> {
|
||||
self.tick_hoppers()?;
|
||||
@@ -2827,6 +2806,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
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> {
|
||||
@@ -3654,15 +3634,15 @@ 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]);
|
||||
let (power_bonus, infinity) = self.bow_enchantments();
|
||||
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 + power_bonus });
|
||||
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
|
||||
@@ -4848,6 +4828,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());
|
||||
@@ -4922,6 +4903,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")
|
||||
@@ -4992,6 +4974,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",
|
||||
"chat TEXT send a chat line or /command as if typed",
|
||||
@@ -230,6 +233,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
@@ -58,7 +58,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<()> {
|
||||
@@ -189,17 +189,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,
|
||||
@@ -283,6 +288,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 {
|
||||
|
||||
@@ -45,6 +45,7 @@ pub mod options_ui;
|
||||
pub mod packs;
|
||||
pub mod particles;
|
||||
pub mod pose;
|
||||
pub mod projectiles;
|
||||
pub mod save;
|
||||
pub mod settings;
|
||||
pub mod sprint;
|
||||
|
||||
+509
-417
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,608 @@
|
||||
//! 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, aquatic,
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The module implementing a species' behaviour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Family {
|
||||
Farm,
|
||||
Undead,
|
||||
Hostile,
|
||||
Aquatic,
|
||||
Generic,
|
||||
}
|
||||
pub fn family(s: Species) -> Family {
|
||||
use Species as S;
|
||||
match s {
|
||||
S::Pig | S::Cow | S::Mooshroom | S::Sheep | S::Chicken => Family::Farm,
|
||||
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::Skeleton | S::Stray | S::Bogged | S::WitherSkeleton => Family::Undead,
|
||||
S::Creeper | S::Spider | S::CaveSpider => Family::Hostile,
|
||||
S::Squid | S::GlowSquid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => Family::Aquatic,
|
||||
_ => Family::Generic,
|
||||
}
|
||||
}
|
||||
pub fn register(m: &mut Mob) {
|
||||
match family(m.species()) {
|
||||
Family::Farm => farm::register(m),
|
||||
Family::Undead => undead::register(m),
|
||||
Family::Hostile => hostile::register(m),
|
||||
Family::Aquatic => aquatic::register(m),
|
||||
Family::Generic => generic(m),
|
||||
}
|
||||
}
|
||||
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
|
||||
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
match family(m.species()) {
|
||||
Family::Hostile => {
|
||||
if m.species() == Species::Creeper {
|
||||
hostile::creeper_tick(m, events)
|
||||
}
|
||||
}
|
||||
Family::Aquatic => aquatic::tick(m, events),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Move controls implemented by the species (MoveKind::Custom).
|
||||
pub fn custom_move_control(m: &mut Mob) {
|
||||
if family(m.species()) == Family::Aquatic {
|
||||
aquatic::fish_move_control(m)
|
||||
}
|
||||
}
|
||||
/// A fallback for species without bespoke goals yet: animals stroll and
|
||||
/// 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).
|
||||
pre_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));
|
||||
}
|
||||
}
|
||||
tick_effects(m);
|
||||
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.attrs.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>) {
|
||||
if family(m.species()) == Family::Aquatic {
|
||||
aquatic::ai_step(m, w, events);
|
||||
}
|
||||
match m.species() {
|
||||
Species::Chicken => farm::chicken_ai_step(m, w, events),
|
||||
Species::Sheep => {
|
||||
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.attrs.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 {
|
||||
match family(m.species()) {
|
||||
Family::Aquatic => aquatic::travel(m, w, input, events),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// MobEffect ticking for the effects mobs receive (poison, wither, regeneration).
|
||||
fn tick_effects(m: &mut Mob) {
|
||||
let mut effects = std::mem::take(&mut m.extra.effects);
|
||||
for (effect, ticks, amp) in &mut effects {
|
||||
let interval = |base: i32| (base >> (*amp).max(0)).max(1);
|
||||
match *effect {
|
||||
"minecraft:poison" if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => {
|
||||
m.damage(1.0, Damage::of(DamageKind::Magic));
|
||||
}
|
||||
"minecraft:wither" if *ticks % interval(40) == 0 => {
|
||||
m.damage(1.0, Damage::of(DamageKind::Magic));
|
||||
}
|
||||
"minecraft:regeneration" if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => {
|
||||
m.health = (m.health + 1.0).min(m.attrs.max_health);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
*ticks -= 1;
|
||||
}
|
||||
effects.retain(|e| e.1 > 0);
|
||||
m.extra.effects = effects;
|
||||
}
|
||||
@@ -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],
|
||||
/// Per-species animation values (tail wag, squid tentacles, squish...)
|
||||
/// with their previous-tick copies for interpolation.
|
||||
pub v: [f32; 8],
|
||||
pub vo: [f32; 8],
|
||||
}
|
||||
impl AnimState {
|
||||
pub fn begin_tick(&mut self) {
|
||||
self.attack_anim_o = self.attack_anim;
|
||||
self.vo = self.v;
|
||||
}
|
||||
/// Interpolated value `i` at the render partial tick.
|
||||
pub fn lerp(&self, i: usize, partial: f32) -> f32 {
|
||||
self.vo[i] + (self.v[i] - self.vo[i]) * partial
|
||||
}
|
||||
pub fn end_tick(&mut self, _swinging: bool) {}
|
||||
}
|
||||
/// 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::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => super::aquatic::anim(m, s, p),
|
||||
Anim::Quadruped | Anim::PolarBear | Anim::Panda | Anim::Goat => quadruped(p, s),
|
||||
Anim::Sheep => {
|
||||
quadruped(p, s);
|
||||
// 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,427 @@
|
||||
//! Water mobs: squid and glow squid (tentacle propulsion), cod, salmon,
|
||||
//! tropical fish and pufferfish (`AbstractFish`, puffing), and dolphins
|
||||
//! (breathing, smooth swimming).
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
anim::{Poses, State},
|
||||
control::MoveKind,
|
||||
goals::{
|
||||
Avoid, AvoidEntity, BreathAir, Cx, Goal, HurtByTarget, LookAtPlayer, MeleeAttack, Panic,
|
||||
RandomLookAround, Stroll, TryFindWater, goal_clone,
|
||||
},
|
||||
nav::NavKind,
|
||||
};
|
||||
use crate::blocks::Fluid;
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
// Squid animation slots in AnimState.v.
|
||||
const TENTACLE_MOVEMENT: usize = 0;
|
||||
const TENTACLE_ANGLE: usize = 1;
|
||||
const X_BODY_ROT: usize = 2;
|
||||
const Z_BODY_ROT: usize = 3;
|
||||
const TENTACLE_SPEED: usize = 4;
|
||||
const ROTATE_SPEED: usize = 5;
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
S::Squid | S::GlowSquid => {
|
||||
m.ai.goals.add(0, SquidRandomMovement);
|
||||
m.ai.goals.add(1, SquidFlee { ticks: 0 });
|
||||
m.ai.mov.kind = MoveKind::Custom;
|
||||
m.ai.nav.kind = NavKind::Water { breach: false };
|
||||
let speed = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
m.anim.v[TENTACLE_SPEED] = speed;
|
||||
}
|
||||
S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish => {
|
||||
let puffer = m.species() == S::Pufferfish;
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Panic::new(1.25));
|
||||
g.add(2, AvoidEntity::new(Avoid::Player, 8.0, 1.6, 1.4));
|
||||
g.add(4, Stroll::swimming(1.0, 40));
|
||||
if puffer {
|
||||
g.add(1, PufferfishPuff);
|
||||
}
|
||||
m.ai.mov.kind = MoveKind::Custom;
|
||||
m.ai.nav.kind = NavKind::Water { breach: false };
|
||||
}
|
||||
S::Dolphin => {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, BreathAir);
|
||||
g.add(0, TryFindWater::default());
|
||||
g.add(4, Stroll::swimming(1.0, 10));
|
||||
g.add(4, RandomLookAround::default());
|
||||
g.add(5, LookAtPlayer::new(6.0));
|
||||
g.add(6, MeleeAttack::new(1.2, true));
|
||||
m.ai.targets.add(1, HurtByTarget::new().alert());
|
||||
m.ai.mov.kind = MoveKind::SmoothSwimming { max_turn_x: 85.0, max_turn_y: 10.0, in_water: 0.02, outside: 0.1, gravity: true };
|
||||
m.ai.look.kind = super::control::LookKind::SmoothSwimming(10.0);
|
||||
m.ai.nav.kind = NavKind::Water { breach: true };
|
||||
m.air = 4800;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Pre-tick updates (Pufferfish.tick puff state).
|
||||
pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
if m.species() != Species::Pufferfish || !m.alive() {
|
||||
return;
|
||||
}
|
||||
let puff = m.extra.size;
|
||||
if m.extra.counter > 0 {
|
||||
if puff == 0 {
|
||||
m.sound("entity.puffer_fish.blow_up", events);
|
||||
m.extra.size = 1;
|
||||
} else if m.extra.counter > 40 && puff == 1 {
|
||||
m.sound("entity.puffer_fish.blow_up", events);
|
||||
m.extra.size = 2;
|
||||
}
|
||||
m.extra.counter += 1;
|
||||
} else if puff != 0 {
|
||||
if m.extra.counter2 > 60 && puff == 2 {
|
||||
m.sound("entity.puffer_fish.blow_out", events);
|
||||
m.extra.size = 1;
|
||||
} else if m.extra.counter2 > 100 && puff == 1 {
|
||||
m.sound("entity.puffer_fish.blow_out", events);
|
||||
m.extra.size = 0;
|
||||
}
|
||||
m.extra.counter2 += 1;
|
||||
}
|
||||
}
|
||||
/// Pufferfish.getScale by puff state (the dimensions scale with it).
|
||||
pub fn puff_scale(state: i32) -> f64 {
|
||||
match state {
|
||||
0 => 0.5,
|
||||
1 => 0.7,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
/// Species aiStep additions.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
S::Squid | S::GlowSquid => squid_ai_step(m),
|
||||
S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish => {
|
||||
// AbstractFish.aiStep flops on land (applied before travel next tick).
|
||||
if !m.fluids.in_water && m.on_ground && m.vertical_collision_below {
|
||||
let (a, b) = (m.random.next_float(), m.random.next_float());
|
||||
m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.05), m.velocity.y + 0.4, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.05));
|
||||
m.on_ground = false;
|
||||
let flop = match m.species() {
|
||||
S::Cod => "entity.cod.flop",
|
||||
S::Salmon => "entity.salmon.flop",
|
||||
S::TropicalFish => "entity.tropical_fish.flop",
|
||||
_ => "entity.puffer_fish.flop",
|
||||
};
|
||||
m.sound(flop, events);
|
||||
}
|
||||
if m.species() == S::Pufferfish && m.alive() && m.extra.size > 0 {
|
||||
// Pufferfish.playerTouch / touch: sting with poison.
|
||||
if let Some(p) = &w.player
|
||||
&& p.alive
|
||||
&& !p.creative
|
||||
&& m.bounds().inflate(Vec3::new(0.3, 0.3, 0.3)).intersects(p.bounds)
|
||||
&& m.ai.no_action_time % 10 == 0
|
||||
{
|
||||
let amount = 1.0 + m.extra.size as f32;
|
||||
events.push(MobEvent::AttackPlayer(amount, [m.position.x, m.position.y, m.position.z]));
|
||||
events.push(MobEvent::EffectPlayer { effect: "minecraft:poison", ticks: 60 * m.extra.size, amplifier: 0 });
|
||||
m.sound("entity.puffer_fish.sting", events);
|
||||
}
|
||||
}
|
||||
}
|
||||
S::Dolphin => {
|
||||
// Dolphin.tick: moisture out of water, hop on land.
|
||||
if m.fluids.in_water || w.raining {
|
||||
m.extra.counter = 2400;
|
||||
} else {
|
||||
m.extra.counter -= 1;
|
||||
if m.extra.counter <= 0 {
|
||||
m.damage(1.0, super::Damage::of(super::DamageKind::Drown));
|
||||
}
|
||||
if m.on_ground {
|
||||
let (a, b) = (m.random.next_float(), m.random.next_float());
|
||||
m.velocity = Vec3::new(m.velocity.x + f64::from((a * 2.0 - 1.0) * 0.2), m.velocity.y + 0.5, m.velocity.z + f64::from((b * 2.0 - 1.0) * 0.2));
|
||||
m.yaw = m.random.next_float() * 360.0;
|
||||
m.on_ground = false;
|
||||
}
|
||||
}
|
||||
// LivingEntity air: dolphins drown underwater and refill instantly in air.
|
||||
if !m.fluids.eye_in_water {
|
||||
m.air = 4800;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Squid.aiStep: tentacle cycle, propulsion and body rotation.
|
||||
fn squid_ai_step(m: &mut Mob) {
|
||||
let v = &mut m.anim.v;
|
||||
v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED];
|
||||
if v[TENTACLE_MOVEMENT] > PI * 2.0 {
|
||||
v[TENTACLE_MOVEMENT] -= PI * 2.0;
|
||||
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
}
|
||||
}
|
||||
let v = &mut m.anim.v;
|
||||
if m.fluids.in_water {
|
||||
if v[TENTACLE_MOVEMENT] < PI {
|
||||
let scale = v[TENTACLE_MOVEMENT] / PI;
|
||||
v[TENTACLE_ANGLE] = (scale * scale * PI).sin() * PI * 0.25;
|
||||
if scale > 0.75 {
|
||||
let mv = m.extra.vector;
|
||||
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
|
||||
m.anim.v[ROTATE_SPEED] = 1.0;
|
||||
} else {
|
||||
m.anim.v[ROTATE_SPEED] *= 0.8;
|
||||
}
|
||||
} else {
|
||||
v[TENTACLE_ANGLE] = 0.0;
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
m.anim.v[ROTATE_SPEED] *= 0.99;
|
||||
}
|
||||
let mv = m.velocity;
|
||||
let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt();
|
||||
m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1;
|
||||
m.yaw = m.body_yaw;
|
||||
let v = &mut m.anim.v;
|
||||
v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5;
|
||||
v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1;
|
||||
} else {
|
||||
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].sin().abs() * PI * 0.25;
|
||||
let yd = m.velocity.y - m.kind.gravity;
|
||||
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
|
||||
let v = &mut m.anim.v;
|
||||
v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02;
|
||||
}
|
||||
}
|
||||
/// Species travel overrides. Returns true when handled.
|
||||
pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) -> bool {
|
||||
use Species as S;
|
||||
match m.species() {
|
||||
// Squid.travel: move by the current velocity only.
|
||||
S::Squid | S::GlowSquid => {
|
||||
m.do_move(w, events);
|
||||
true
|
||||
}
|
||||
// AbstractFish.travelInWater / Dolphin.travelInWater.
|
||||
S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin if m.fluids.in_water => {
|
||||
let speed = if m.species() == S::Dolphin { m.ai.speed } else { 0.01 };
|
||||
m.move_relative(speed, input);
|
||||
m.do_move(w, events);
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
if m.ai.target.is_none() {
|
||||
m.velocity.y -= 0.005;
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
/// FishMoveControl.tick (fish use it instead of the default move control).
|
||||
pub fn fish_move_control(m: &mut Mob) {
|
||||
if !matches!(m.species(), Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish) {
|
||||
return;
|
||||
}
|
||||
if m.fluids.eye_in_water {
|
||||
m.velocity.y += 0.005;
|
||||
}
|
||||
if m.ai.mov.operation == super::control::Operation::MoveTo && !m.ai.nav.is_done() {
|
||||
let target = (m.ai.mov.speed_modifier * m.movement_speed()) as f32;
|
||||
let speed = m.ai.speed + (target - m.ai.speed) * 0.125;
|
||||
m.set_speed(speed);
|
||||
let [wx, wy, wz] = m.ai.mov.wanted;
|
||||
let (xd, yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z);
|
||||
if yd != 0.0 {
|
||||
let dd = (xd * xd + yd * yd + zd * zd).sqrt();
|
||||
m.velocity.y += f64::from(m.ai.speed) * (yd / dd) * 0.1;
|
||||
}
|
||||
if xd != 0.0 || zd != 0.0 {
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
m.yaw = super::control::rotlerp(m.yaw, y_rot, 90.0);
|
||||
m.body_yaw = m.yaw;
|
||||
}
|
||||
} else {
|
||||
m.set_speed(0.0);
|
||||
}
|
||||
}
|
||||
/// Squid.SquidRandomMovementGoal
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SquidRandomMovement;
|
||||
impl Goal for SquidRandomMovement {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
if m.ai.no_action_time > 100 {
|
||||
m.extra.vector = [0.0; 3];
|
||||
} else if m.random.next_int_bound(super::goals::reduced(50)).unwrap_or(1) == 0 || !m.fluids.in_water || m.extra.vector == [0.0; 3] {
|
||||
let angle = m.random.next_float() * PI * 2.0;
|
||||
let y = -0.1 + m.random.next_float() * 0.2;
|
||||
m.extra.vector = [f64::from(angle.cos() * 0.2), f64::from(y), f64::from(angle.sin() * 0.2)];
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Squid.SquidFleeGoal (keeps vanilla's discarded normalize()).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SquidFlee {
|
||||
ticks: i32,
|
||||
}
|
||||
impl Goal for SquidFlee {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return false };
|
||||
m.fluids.in_water && m.distance_sqr(by.position) < 100.0
|
||||
}
|
||||
fn start(&mut self, _: &mut Mob, _: &mut Cx) {
|
||||
self.ticks = 0;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.ticks += 1;
|
||||
let Some(by) = m.ai.last_hurt_by.and_then(|w| cx.w.target_info(w)) else { return };
|
||||
let mut f = [m.position.x - by.position.x, m.position.y - by.position.y, m.position.z - by.position.z];
|
||||
let at = [(m.position.x + f[0]).floor() as i32, (m.position.y + f[1]).floor() as i32, (m.position.z + f[2]).floor() as i32];
|
||||
let air = cx.w.facts.is_air(cx.w.world.block(at[0], at[1], at[2]));
|
||||
if cx.w.fluid(at[0], at[1], at[2]) == Fluid::Water || air {
|
||||
let length = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt();
|
||||
if length > 0.0 {
|
||||
let mut avoid = 3.0;
|
||||
if length > 5.0 {
|
||||
avoid -= (length - 5.0) / 5.0;
|
||||
}
|
||||
if avoid > 0.0 {
|
||||
f = f.map(|c| c * avoid);
|
||||
}
|
||||
}
|
||||
if air {
|
||||
f[1] = 0.0;
|
||||
}
|
||||
m.extra.vector = [f[0] / 20.0, f[1] / 20.0, f[2] / 20.0];
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Pufferfish.PufferfishPuffGoal: inflate when a mob or player is within 2.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PufferfishPuff;
|
||||
impl Goal for PufferfishPuff {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let area = m.bounds().inflate(Vec3::new(2.0, 2.0, 2.0));
|
||||
let player = cx.w.player.as_ref().is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds));
|
||||
// TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive.
|
||||
let mob = cx.w.others.iter().any(|s| {
|
||||
s.id != m.id && s.alive && !matches!(s.species, Species::Cod | Species::Salmon | Species::TropicalFish | Species::Pufferfish | Species::Squid | Species::GlowSquid | Species::Dolphin | Species::Axolotl) && area.intersects(s.bounds)
|
||||
});
|
||||
player || mob
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.extra.counter = 1;
|
||||
m.extra.counter2 = 0;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.extra.counter = 0;
|
||||
}
|
||||
}
|
||||
/// finalizeSpawn variants (tropical fish patterns and colours).
|
||||
pub fn finalize(m: &mut Mob) {
|
||||
if m.species() == Species::TropicalFish {
|
||||
// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
|
||||
const COMMON: [(u8, u8, u8); 22] = [
|
||||
(7, 1, 7), (6, 7, 7), (6, 7, 11), (11, 0, 7), (1, 11, 7), (0, 1, 0), (5, 6, 3), (9, 10, 4), (11, 0, 14), (5, 0, 4), (8, 0, 7),
|
||||
(11, 0, 1), (3, 9, 6), (4, 5, 3), (10, 14, 0), (2, 7, 14), (9, 14, 0), (6, 0, 4), (0, 14, 0), (1, 7, 0), (3, 9, 4), (6, 4, 4),
|
||||
];
|
||||
let (p, b, c) = if m.random.next_float() < 0.9 {
|
||||
COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize]
|
||||
} else {
|
||||
(m.random.next_int_bound(12).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8, m.random.next_int_bound(16).unwrap_or(0) as u8)
|
||||
};
|
||||
m.extra.variant = p;
|
||||
m.extra.variant2 = b;
|
||||
m.extra.variant3 = c;
|
||||
}
|
||||
}
|
||||
/// Model animation for the water mobs.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
use Species as S;
|
||||
let amp = if m.fluids.in_water { 1.0 } else { 1.5 };
|
||||
match m.species() {
|
||||
S::Squid | S::GlowSquid => {
|
||||
let angle = m.anim.lerp(TENTACLE_ANGLE, s.partial);
|
||||
for i in 0..8 {
|
||||
p.xrot(&format!("tentacle{i}"), angle);
|
||||
}
|
||||
}
|
||||
S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()),
|
||||
S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()),
|
||||
S::Salmon => {
|
||||
let (a, k) = if m.fluids.in_water { (1.0, 1.0) } else { (1.3, 1.7) };
|
||||
p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin());
|
||||
}
|
||||
S::Pufferfish => {
|
||||
let fin = 0.2 - 0.4 * (s.age * 0.2).sin();
|
||||
if p.has("right_blue_fin") {
|
||||
p.zrot("right_blue_fin", -fin);
|
||||
p.zrot("left_blue_fin", fin);
|
||||
} else {
|
||||
p.zrot("right_fin", -fin);
|
||||
p.zrot("left_fin", fin);
|
||||
}
|
||||
}
|
||||
S::Dolphin => {
|
||||
p.xrot("body", s.x_rot.to_radians());
|
||||
p.yrot("body", s.y_rot.to_radians());
|
||||
let moving = m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z > 1.0e-7;
|
||||
if moving {
|
||||
p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).cos();
|
||||
p.xrot("tail", -0.1 * (s.age * 0.3).cos());
|
||||
p.xrot("tail_fin", -0.2 * (s.age * 0.3).cos());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Renderer setupRotations for the water mobs (replacing or extending the default).
|
||||
pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option<glam::Mat4> {
|
||||
use Species as S;
|
||||
let age = m.age as f32 + alpha;
|
||||
match m.species() {
|
||||
S::Squid | S::GlowSquid => {
|
||||
let baby = m.is_baby();
|
||||
let x = m.anim.lerp(X_BODY_ROT, alpha);
|
||||
let z = m.anim.lerp(Z_BODY_ROT, alpha);
|
||||
Some(
|
||||
glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { 0.25 } else { 0.5 }, 0.0))
|
||||
* glam::Mat4::from_rotation_y((180.0 - body).to_radians())
|
||||
* glam::Mat4::from_rotation_x(x.to_radians())
|
||||
* glam::Mat4::from_rotation_y(z.to_radians())
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.0, if baby { -0.6 } else { -1.2 }, 0.0)),
|
||||
)
|
||||
}
|
||||
S::Cod | S::Salmon | S::TropicalFish => {
|
||||
let (a, k) = if m.species() == S::Salmon && !m.fluids.in_water { (1.3, 1.7) } else { (1.0, 1.0) };
|
||||
let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians()) * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians());
|
||||
if !m.fluids.in_water {
|
||||
let off = if m.species() == S::Cod { glam::Vec3::new(0.1, 0.1, -0.1) } else { glam::Vec3::new(0.2, 0.1, 0.0) };
|
||||
t *= glam::Mat4::from_translation(off) * glam::Mat4::from_rotation_z(PI / 2.0);
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
S::Pufferfish => Some(glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0)) * glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -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.movement_speed();
|
||||
match self.ai.mov.kind {
|
||||
MoveKind::Custom => super::ai::custom_move_control(self),
|
||||
MoveKind::Ground => self.ground_move_tick(w, attr_speed),
|
||||
MoveKind::Flying { max_turn, hovers } => {
|
||||
let m = &mut self.ai.mov;
|
||||
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,260 @@
|
||||
//! Slimes and magma cubes (`AbstractCubeMob`): sized bodies, hopping
|
||||
//! movement (`CubeMobMoveControl`), random directions, contact damage,
|
||||
//! squish animation and splitting.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
anim::{Poses, State},
|
||||
control::{MoveKind, Operation, rotlerp},
|
||||
goals::{Cx, Goal, JUMP, LOOK, MOVE, NearestTarget, Prey, goal_clone, reduced},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
// AnimState slots.
|
||||
const SQUISH: usize = 0;
|
||||
const TARGET_SQUISH: usize = 1;
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
m.ai.goals.add(1, CubeFloat);
|
||||
m.ai.goals.add(2, CubeAttack { tired: 0 });
|
||||
m.ai.goals.add(4, CubeRandomDirection { degrees: 0.0, next: 0 });
|
||||
m.ai.goals.add(5, CubeKeepJumping);
|
||||
m.ai.targets.add(1, NearestTarget::new(Prey::Player, true).interval(10).when(|m, w| w.player.as_ref().is_some_and(|p| (p.position.y - m.position.y).abs() <= 4.0)));
|
||||
m.ai.targets.add(3, NearestTarget::species(&[Species::IronGolem], true));
|
||||
m.ai.mov.kind = MoveKind::Custom;
|
||||
m.ai.nav.can_float = true;
|
||||
m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI);
|
||||
set_size(m, 1);
|
||||
}
|
||||
/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size.
|
||||
pub fn set_size(m: &mut Mob, size: i32) {
|
||||
let size = size.clamp(1, 127);
|
||||
m.extra.size = size;
|
||||
m.attrs.max_health = (size * size) as f32;
|
||||
m.attrs.speed = 0.2 + 0.1 * f64::from(size);
|
||||
m.attrs.attack_damage = size as f32;
|
||||
m.health = m.attrs.max_health;
|
||||
}
|
||||
/// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0).
|
||||
pub fn finalize(m: &mut Mob) {
|
||||
let scale = m.random.next_int_bound(3).unwrap_or(0);
|
||||
set_size(m, 1 << scale);
|
||||
}
|
||||
fn tiny(m: &Mob) -> bool {
|
||||
m.extra.size <= 1
|
||||
}
|
||||
fn can_deal_damage(m: &Mob) -> bool {
|
||||
m.species() == Species::MagmaCube || !tiny(m)
|
||||
}
|
||||
fn jump_delay(m: &mut Mob) -> i32 {
|
||||
let base = m.random.next_int_bound(20).unwrap_or(0) + 10;
|
||||
if m.species() == Species::MagmaCube { base * 4 } else { base }
|
||||
}
|
||||
fn sound_pitch(m: &mut Mob) -> f32 {
|
||||
let adjust = if tiny(m) { 1.4 } else { 0.8 };
|
||||
((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) * adjust
|
||||
}
|
||||
/// CubeMobMoveControl.tick
|
||||
pub fn move_control(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
let want = m.extra.vector[0] as f32;
|
||||
m.yaw = rotlerp(m.yaw, want, 90.0);
|
||||
m.head_yaw = m.yaw;
|
||||
m.body_yaw = m.yaw;
|
||||
if m.ai.mov.operation != Operation::MoveTo {
|
||||
m.ai.zza = 0.0;
|
||||
return;
|
||||
}
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
let speed = (m.ai.mov.speed_modifier * m.movement_speed()) as f32;
|
||||
if m.on_ground {
|
||||
m.set_speed(speed);
|
||||
let delay = m.extra.counter;
|
||||
m.extra.counter -= 1;
|
||||
if delay <= 0 {
|
||||
m.extra.counter = jump_delay(m);
|
||||
if m.extra.flag {
|
||||
m.extra.counter /= 3;
|
||||
}
|
||||
m.ai.jump = true;
|
||||
let jump = match (m.species(), tiny(m)) {
|
||||
(Species::MagmaCube, _) => "entity.magma_cube.jump",
|
||||
(_, true) => "entity.slime.jump_small",
|
||||
_ => "entity.slime.jump",
|
||||
};
|
||||
let pitch = sound_pitch(m);
|
||||
let vol = super::ai::sound_volume(m);
|
||||
events.push(MobEvent::Sound(jump, m.center(), vol, pitch));
|
||||
} else {
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
m.set_speed(0.0);
|
||||
}
|
||||
} else {
|
||||
m.set_speed(speed);
|
||||
}
|
||||
}
|
||||
fn set_direction(m: &mut Mob, y_rot: f32, aggressive: bool) {
|
||||
m.extra.vector[0] = f64::from(y_rot);
|
||||
m.extra.flag = aggressive;
|
||||
}
|
||||
fn set_wanted(m: &mut Mob, speed: f64) {
|
||||
m.ai.mov.speed_modifier = speed;
|
||||
m.ai.mov.operation = Operation::MoveTo;
|
||||
}
|
||||
/// AbstractCubeMob.jumpFromGround (and MagmaCube's size boost).
|
||||
pub fn jump(m: &mut Mob) {
|
||||
let boost = if m.species() == Species::MagmaCube { m.extra.size as f32 * 0.1 } else { 0.0 };
|
||||
m.velocity.y = f64::from(m.jump_power() + boost);
|
||||
}
|
||||
/// AbstractCubeMob.tick squish and landing sounds, plus contact damage.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
let v = &mut m.anim.v;
|
||||
v[SQUISH] += (v[TARGET_SQUISH] - v[SQUISH]) * 0.5;
|
||||
let was = m.extra.flag2;
|
||||
if m.on_ground && !was {
|
||||
let squish = match (m.species(), tiny(m)) {
|
||||
(Species::MagmaCube, true) => "entity.magma_cube.squish_small",
|
||||
(Species::MagmaCube, false) => "entity.magma_cube.squish",
|
||||
(_, true) => "entity.slime.squish_small",
|
||||
_ => "entity.slime.squish",
|
||||
};
|
||||
let pitch = ((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) / 0.8;
|
||||
let vol = super::ai::sound_volume(m);
|
||||
events.push(MobEvent::Sound(squish, m.center(), vol, pitch));
|
||||
m.anim.v[TARGET_SQUISH] = -0.5;
|
||||
} else if !m.on_ground && was {
|
||||
m.anim.v[TARGET_SQUISH] = 1.0;
|
||||
}
|
||||
m.extra.flag2 = m.on_ground;
|
||||
m.anim.v[TARGET_SQUISH] *= if m.species() == Species::MagmaCube { 0.9 } else { 0.6 };
|
||||
// playerTouch -> dealDamage
|
||||
if can_deal_damage(m)
|
||||
&& m.alive()
|
||||
&& let Some(p) = &w.player
|
||||
&& p.alive
|
||||
&& !p.creative
|
||||
&& m.bounds().intersects(p.bounds)
|
||||
{
|
||||
let reach = 2.04f32.sqrt() as f64 - 0.6;
|
||||
if m.bounds().inflate(Vec3::new(reach, 0.0, reach)).intersects(p.bounds) {
|
||||
let damage = m.attrs.attack_damage + if m.species() == Species::MagmaCube { 2.0 } else { 0.0 };
|
||||
events.push(MobEvent::AttackPlayer(damage, [m.position.x, m.position.y, m.position.z]));
|
||||
if m.species() == Species::Slime {
|
||||
let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0;
|
||||
events.push(MobEvent::Sound("entity.slime.attack", m.center(), 1.0, pitch));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// MagmaCubeModel.setupAnim (slimes have no animation).
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
if m.species() == Species::MagmaCube {
|
||||
let squish = m.anim.lerp(SQUISH, s.partial).max(0.0);
|
||||
for i in 0..8 {
|
||||
p.get(&format!("cube{i}"))[1] = -((4 - i) as f32) * squish * 1.7;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// AbstractCubeMobRenderer.scale: size with squash and stretch.
|
||||
pub fn scale(m: &Mob, alpha: f32) -> glam::Mat4 {
|
||||
let size = m.extra.size.max(1) as f32;
|
||||
let squish = m.anim.lerp(SQUISH, alpha) / (size * 0.5 + 1.0);
|
||||
let w = 1.0 / (squish + 1.0);
|
||||
let mut t = glam::Mat4::IDENTITY;
|
||||
if m.species() == Species::Slime {
|
||||
t = glam::Mat4::from_scale(glam::Vec3::splat(0.999)) * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.001, 0.0));
|
||||
}
|
||||
t * glam::Mat4::from_scale(glam::Vec3::new(w * size, 1.0 / w * size, w * size))
|
||||
}
|
||||
/// CubeMobFloatGoal
|
||||
#[derive(Clone, Debug)]
|
||||
struct CubeFloat;
|
||||
impl Goal for CubeFloat {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
JUMP | MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
m.is_in_liquid()
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
if m.random.next_float() < 0.8 {
|
||||
m.ai.jump = true;
|
||||
}
|
||||
set_wanted(m, 1.2);
|
||||
}
|
||||
}
|
||||
/// CubeMobAttackGoal: face the target and hop at it for up to 300 ticks.
|
||||
#[derive(Clone, Debug)]
|
||||
struct CubeAttack {
|
||||
tired: i32,
|
||||
}
|
||||
impl Goal for CubeAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
m.target_info(cx.w).is_some_and(|t| t.alive && !(t.is_player && t.creative))
|
||||
}
|
||||
fn start(&mut self, _: &mut Mob, _: &mut Cx) {
|
||||
self.tired = reduced(300);
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if !m.target_info(cx.w).is_some_and(|t| t.alive && !(t.is_player && t.creative)) {
|
||||
return false;
|
||||
}
|
||||
self.tired -= 1;
|
||||
self.tired > 0
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(t) = m.target_info(cx.w) {
|
||||
m.turn_to([t.position.x, t.eye_y, t.position.z], 10.0, 10.0);
|
||||
}
|
||||
let (yaw, aggressive) = (m.yaw, can_deal_damage(m));
|
||||
set_direction(m, yaw, aggressive);
|
||||
}
|
||||
}
|
||||
/// CubeMobRandomDirectionGoal
|
||||
#[derive(Clone, Debug)]
|
||||
struct CubeRandomDirection {
|
||||
degrees: f32,
|
||||
next: i32,
|
||||
}
|
||||
impl Goal for CubeRandomDirection {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
m.ai.target.is_none() && (m.on_ground || m.is_in_liquid() || m.has_effect("minecraft:levitation"))
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
self.next -= 1;
|
||||
if self.next <= 0 {
|
||||
self.next = reduced(40 + m.random.next_int_bound(60).unwrap_or(0));
|
||||
self.degrees = m.random.next_int_bound(360).unwrap_or(0) as f32;
|
||||
}
|
||||
set_direction(m, self.degrees, false);
|
||||
}
|
||||
}
|
||||
/// CubeMobKeepOnJumpingGoal
|
||||
#[derive(Clone, Debug)]
|
||||
struct CubeKeepJumping;
|
||||
impl Goal for CubeKeepJumping {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
JUMP | MOVE
|
||||
}
|
||||
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
set_wanted(m, 1.0);
|
||||
}
|
||||
}
|
||||
@@ -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,306 @@
|
||||
//! Endermen: anger from being stared at, teleporting (randomly in daylight,
|
||||
//! when hit by projectiles or water, and towards a distant target), freezing
|
||||
//! while looked at, and picking up / placing `enderman_holdable` blocks.
|
||||
use super::{
|
||||
Damage, Mob, MobEvent, MobWorld, Species, Who,
|
||||
anim::{Poses, State},
|
||||
goals::{Cx, Float, Goal, HurtByTarget, JUMP, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, Stroll, TARGET, goal_clone, reduced},
|
||||
};
|
||||
use crate::blocks::Fluid;
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
random::RandomSource,
|
||||
};
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(1, FreezeWhenLookedAt);
|
||||
g.add(2, MeleeAttack::new(1.0, false));
|
||||
let mut stroll = Stroll::avoiding_water(1.0);
|
||||
stroll.water_avoiding = Some(0.0);
|
||||
g.add(7, stroll);
|
||||
g.add(8, LookAtPlayer::new(8.0));
|
||||
g.add(8, RandomLookAround::default());
|
||||
g.add(10, LeaveBlock);
|
||||
g.add(11, TakeBlock);
|
||||
m.ai.targets.add(1, LookForPlayer { pending: false, aggro: 0, teleport: 0 });
|
||||
m.ai.targets.add(2, HurtByTarget::new());
|
||||
m.ai.targets.add(3, NearestTarget::species(&[Species::Endermite], true).reach());
|
||||
m.set_malus(super::path::PathType::Water, -1.0);
|
||||
}
|
||||
/// Enderman.isBeingStaredBy: the player's look within a cone of 0.025 / distance
|
||||
/// of the eyes, with line of sight, and no carved pumpkin.
|
||||
pub fn stared_at(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(p) = &w.player else { return false };
|
||||
if !p.alive || p.head.as_deref() == Some("minecraft:carved_pumpkin") {
|
||||
return false;
|
||||
}
|
||||
let look = p.look;
|
||||
let dir = [m.position.x - p.position.x, m.eye_y() - p.eye[1], m.position.z - p.position.z];
|
||||
let dist = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
|
||||
if dist < 1.0e-6 {
|
||||
return false;
|
||||
}
|
||||
let dot = (look[0] * dir[0] + look[1] * dir[1] + look[2] * dir[2]) / dist;
|
||||
dot > 1.0 - 0.025 / dist && w.line_of_sight(Vec3::new(p.eye[0], p.eye[1], p.eye[2]), Vec3::new(m.position.x, m.eye_y(), m.position.z))
|
||||
}
|
||||
/// Enderman.teleport(x, y, z): drop to standing ground, require free space without liquid.
|
||||
pub fn teleport_to(m: &mut Mob, w: &MobWorld, x: f64, y: f64, z: f64, events: &mut Vec<MobEvent>) -> bool {
|
||||
let (bx, bz) = (x.floor() as i32, z.floor() as i32);
|
||||
if !w.world.loaded(bx, bz) {
|
||||
return false;
|
||||
}
|
||||
let mut by = y.floor() as i32;
|
||||
while by > crate::chunk::MIN_Y && !w.facts.get(w.world.block(bx, by, bz)).full_collision {
|
||||
by -= 1;
|
||||
}
|
||||
let ground = w.facts.get(w.world.block(bx, by, bz));
|
||||
if !ground.full_collision || ground.fluid == Fluid::Water {
|
||||
return false;
|
||||
}
|
||||
let ny = f64::from(by + 1);
|
||||
let half = f64::from(m.width()) / 2.0;
|
||||
let b = Aabb::new(Vec3::new(x - half, ny, z - half), Vec3::new(x + half, ny + f64::from(m.height()), z + half));
|
||||
if !w.no_collision(b) || w.fluids(b, ny + m.eye_height()).in_water || w.fluids(b, ny).in_lava {
|
||||
return false;
|
||||
}
|
||||
let old = m.center();
|
||||
m.position = Vec3::new(x, ny, z);
|
||||
m.previous = m.position;
|
||||
m.velocity = Vec3::ZERO;
|
||||
m.ai.nav.stop();
|
||||
events.push(MobEvent::Sound("entity.enderman.teleport", old, 1.0, 1.0));
|
||||
events.push(MobEvent::Sound("entity.enderman.teleport", m.center(), 1.0, 1.0));
|
||||
true
|
||||
}
|
||||
pub fn teleport_random(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
if !m.alive() {
|
||||
return false;
|
||||
}
|
||||
let x = m.position.x + (m.random.next_double() - 0.5) * 64.0;
|
||||
let y = m.position.y + f64::from(m.random.next_int_bound(64).unwrap_or(32) - 32);
|
||||
let z = m.position.z + (m.random.next_double() - 0.5) * 64.0;
|
||||
teleport_to(m, w, x, y, z, events)
|
||||
}
|
||||
fn teleport_towards(m: &mut Mob, w: &MobWorld, at: Vec3, eye_y: f64, events: &mut Vec<MobEvent>) -> bool {
|
||||
let mut d = [m.position.x - at.x, m.position.y + f64::from(m.height()) * 0.5 - eye_y, m.position.z - at.z];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1.0e-9);
|
||||
d = d.map(|c| c / len);
|
||||
let x = m.position.x + (m.random.next_double() - 0.5) * 8.0 - d[0] * 16.0;
|
||||
let y = m.position.y + f64::from(m.random.next_int_bound(16).unwrap_or(8) - 8) - d[1] * 16.0;
|
||||
let z = m.position.z + (m.random.next_double() - 0.5) * 8.0 - d[2] * 16.0;
|
||||
teleport_to(m, w, x, y, z, events)
|
||||
}
|
||||
/// Enderman.customServerAiStep: in daylight, flee by teleporting.
|
||||
pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
if cx.w.daylight && m.age as i32 >= m.extra.counter + 600 {
|
||||
let br = super::hostile::mob_brightness(m, cx.w);
|
||||
let (x, y, z) = (m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32);
|
||||
if br > 0.5 && cx.w.can_see_sky(x, y, z) && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 {
|
||||
m.ai.target = None;
|
||||
teleport_random(m, cx.w, cx.events);
|
||||
}
|
||||
}
|
||||
// Being angry (target set) makes the head "creepy" (render).
|
||||
m.extra.flag = m.ai.target.is_some();
|
||||
}
|
||||
/// Enderman.hurtServer: projectiles miss (teleport away), others may teleport.
|
||||
pub fn on_damage(m: &mut Mob, source: &Damage) -> bool {
|
||||
if source.is_projectile() {
|
||||
// repeatedlyTryToTeleport is applied by the next AI step.
|
||||
m.extra.counter2 = 64;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
pub fn after_hurt(m: &mut Mob, source: &Damage) {
|
||||
if source.attacker.is_none() && m.random.next_int_bound(10).unwrap_or(0) != 0 {
|
||||
m.extra.counter2 = 1;
|
||||
}
|
||||
}
|
||||
/// Pending teleports (repeatedlyTryToTeleport: up to 64 tries).
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
// Enderman.aiStep: never jumps.
|
||||
m.ai.jumping = false;
|
||||
if m.extra.counter2 > 0 {
|
||||
let tries = m.extra.counter2;
|
||||
m.extra.counter2 = 0;
|
||||
for _ in 0..tries {
|
||||
if teleport_random(m, w, events) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (m.fluids.in_water || w.raining && w.can_see_sky(m.position.x.floor() as i32, m.eye_y().floor() as i32, m.position.z.floor() as i32)) && m.alive() {
|
||||
// Hurt by water: teleport away.
|
||||
m.extra.counter2 = m.extra.counter2.max(1);
|
||||
}
|
||||
}
|
||||
/// EndermanModel.setupAnim: half-speed clamped limbs, held-block arms, creepy head.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
super::anim::humanoid_pub(p, s, m);
|
||||
for part in ["right_arm", "left_arm", "right_leg", "left_leg"] {
|
||||
let x = p.get(part)[3] * 0.5;
|
||||
p.xrot(part, x.clamp(-0.4, 0.4));
|
||||
}
|
||||
if m.extra.carried.is_some() {
|
||||
p.xrot("right_arm", -0.5);
|
||||
p.xrot("left_arm", -0.5);
|
||||
p.zrot("right_arm", 0.05);
|
||||
p.zrot("left_arm", -0.05);
|
||||
}
|
||||
if m.extra.flag {
|
||||
p.get("head")[1] -= 5.0;
|
||||
p.get("hat")[1] += 5.0;
|
||||
}
|
||||
}
|
||||
/// EndermanFreezeWhenLookedAt
|
||||
#[derive(Clone, Debug)]
|
||||
struct FreezeWhenLookedAt;
|
||||
impl Goal for FreezeWhenLookedAt {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
JUMP | MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.ai.target != Some(Who::Player) {
|
||||
return false;
|
||||
}
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
m.distance_sqr(p.position) <= 256.0 && stared_at(m, cx.w)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.nav_stop();
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(p) = &cx.w.player {
|
||||
let at = [p.position.x, p.eye[1], p.position.z];
|
||||
m.look_at(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// EndermanLookForPlayerGoal: anger after being stared at for 5 ticks,
|
||||
/// teleport away when stared at close up, or towards a far target.
|
||||
#[derive(Clone, Debug)]
|
||||
struct LookForPlayer {
|
||||
pending: bool,
|
||||
aggro: i32,
|
||||
teleport: i32,
|
||||
}
|
||||
impl Goal for LookForPlayer {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
TARGET
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
self.pending = p.alive && !p.creative && m.distance_sqr(p.position) <= m.attrs.follow_range.powi(2) && stared_at(m, cx.w);
|
||||
self.pending
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
self.aggro = reduced(5);
|
||||
self.teleport = 0;
|
||||
// setBeingStaredAt: play the stare sound.
|
||||
m.extra.counter = m.age as i32;
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
self.pending = false;
|
||||
m.ai.target = None;
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(p) = cx.w.player.clone() else { return false };
|
||||
if self.pending {
|
||||
if !stared_at(m, cx.w) {
|
||||
return false;
|
||||
}
|
||||
m.turn_to(p.eye, 10.0, 10.0);
|
||||
return true;
|
||||
}
|
||||
p.alive && !p.creative && m.ai.target == Some(Who::Player) && m.distance_sqr(p.position) <= m.attrs.follow_range.powi(2)
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = cx.w.player.clone() else { return };
|
||||
if self.pending {
|
||||
self.aggro -= 1;
|
||||
if self.aggro <= 0 {
|
||||
self.pending = false;
|
||||
m.ai.target = Some(Who::Player);
|
||||
cx.events.push(MobEvent::Sound("entity.enderman.stare", m.center(), 2.5, 1.0));
|
||||
}
|
||||
} else if m.ai.target == Some(Who::Player) {
|
||||
if stared_at(m, cx.w) {
|
||||
if m.distance_sqr(p.position) < 16.0 {
|
||||
teleport_random(m, cx.w, cx.events);
|
||||
}
|
||||
self.teleport = 0;
|
||||
} else {
|
||||
let far = m.distance_sqr(p.position) > 256.0;
|
||||
let t = self.teleport;
|
||||
if far {
|
||||
self.teleport += 1;
|
||||
}
|
||||
if far && t >= reduced(30) && teleport_towards(m, cx.w, p.position, p.eye[1], cx.events) {
|
||||
self.teleport = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// EndermanTakeBlockGoal
|
||||
#[derive(Clone, Debug)]
|
||||
struct TakeBlock;
|
||||
impl Goal for TakeBlock {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
m.extra.carried.is_none() && m.random.next_int_bound(reduced(20)).unwrap_or(1) == 0
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let x = (m.position.x - 2.0 + m.random.next_double() * 4.0).floor() as i32;
|
||||
let y = (m.position.y + m.random.next_double() * 3.0).floor() as i32;
|
||||
let z = (m.position.z - 2.0 + m.random.next_double() * 4.0).floor() as i32;
|
||||
let state = cx.w.world.block(x, y, z);
|
||||
let name = cx.w.facts.get(state).name.to_string();
|
||||
if !cx.w.has_tag("minecraft:enderman_holdable", &name) {
|
||||
return;
|
||||
}
|
||||
// Reachable: the clip from the mob's column hits this block first.
|
||||
let from = Vec3::new(m.position.x.floor() + 0.5, f64::from(y) + 0.5, m.position.z.floor() + 0.5);
|
||||
let to = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.5, f64::from(z) + 0.5);
|
||||
let dx = (x - m.position.x.floor() as i32).abs() + (z - m.position.z.floor() as i32).abs();
|
||||
if dx > 0 && !cx.w.clear_between(from, Vec3::new(to.x - (to.x - from.x) * 0.3, to.y, to.z - (to.z - from.z) * 0.3), false) {
|
||||
return;
|
||||
}
|
||||
cx.events.push(MobEvent::SetBlock { pos: [x, y, z], state: cx.w.world.air });
|
||||
m.extra.carried = Some(state);
|
||||
}
|
||||
}
|
||||
/// EndermanLeaveBlockGoal
|
||||
#[derive(Clone, Debug)]
|
||||
struct LeaveBlock;
|
||||
impl Goal for LeaveBlock {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
m.extra.carried.is_some() && m.random.next_int_bound(reduced(2000)).unwrap_or(1) == 0
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(carried) = m.extra.carried else { return };
|
||||
let x = (m.position.x - 1.0 + m.random.next_double() * 2.0).floor() as i32;
|
||||
let y = (m.position.y + m.random.next_double() * 2.0).floor() as i32;
|
||||
let z = (m.position.z - 1.0 + m.random.next_double() * 2.0).floor() as i32;
|
||||
let target = cx.w.world.block(x, y, z);
|
||||
let below = cx.w.world.block(x, y - 1, z);
|
||||
let bf = cx.w.facts.get(below);
|
||||
let free = !cx.w.others.iter().any(|s| s.bounds.intersects(Aabb::new(Vec3::new(f64::from(x), f64::from(y), f64::from(z)), Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)))));
|
||||
if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" && bf.full_collision && free {
|
||||
cx.events.push(MobEvent::SetBlock { pos: [x, y, z], state: carried });
|
||||
m.extra.carried = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,453 @@
|
||||
//! `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.kind.species == super::Species::Pufferfish {
|
||||
let s = super::aquatic::puff_scale(self.extra.size);
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
} else if self.extra.size > 0 {
|
||||
let s = f64::from(self.extra.size);
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
}
|
||||
(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.attrs.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.attrs.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.attrs.follow_range * 16.0).floor() as f32
|
||||
* self.ai.nav.max_visited_multiplier) as i32;
|
||||
let finder = Finder::new(w, &pm, self.ai.nav.evaluator());
|
||||
let path = finder.find(targets, max_len, reach, max_visited);
|
||||
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,622 @@
|
||||
//! 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"
|
||||
}),
|
||||
),
|
||||
S::Squid => (baby_or(m, "squid#main", "squid_baby#main"), b("entity/squid/squid")),
|
||||
S::GlowSquid => (baby_or(m, "glow_squid#main", "glow_squid_baby#main"), b("entity/squid/glow_squid")),
|
||||
S::Dolphin => (baby_or(m, "dolphin#main", "dolphin_baby#main"), b("entity/dolphin/dolphin")),
|
||||
S::Pufferfish => {
|
||||
let model = match m.extra.size {
|
||||
0 => "pufferfish_small#main",
|
||||
1 => "pufferfish_medium#main",
|
||||
_ => "pufferfish_big#main",
|
||||
};
|
||||
(model.into(), "entity/fish/pufferfish".into())
|
||||
}
|
||||
S::TropicalFish => {
|
||||
if m.extra.variant < 6 {
|
||||
("tropical_fish_small#main".into(), "entity/fish/tropical_a".into())
|
||||
} else {
|
||||
("tropical_fish_large#main".into(), "entity/fish/tropical_b".into())
|
||||
}
|
||||
}
|
||||
_ => (m.kind.model_key(), m.kind.texture.clone()),
|
||||
}
|
||||
}
|
||||
/// LivingEntityRenderer.getModelTint (tropical fish base colour).
|
||||
pub fn body_color(m: &Mob) -> u32 {
|
||||
match m.species() {
|
||||
Species::TropicalFish => abgr(DYE[m.extra.variant2 as usize & 15]),
|
||||
_ => 0xFFFF_FFFF,
|
||||
}
|
||||
}
|
||||
/// Extra render layers drawn over the body with the same pose.
|
||||
pub fn layers(m: &Mob) -> Vec<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::TropicalFish => {
|
||||
// TropicalFishPatternLayer: the pattern tinted with the pattern colour.
|
||||
let (model, letter, n) = if m.extra.variant < 6 { ("tropical_fish_small#pattern", "a", m.extra.variant + 1) } else { ("tropical_fish_large#pattern", "b", m.extra.variant - 5) };
|
||||
push(&mut v, model, &format!("entity/fish/tropical_{letter}_pattern_{n}"), abgr(DYE[m.extra.variant3 as usize & 15]), false);
|
||||
}
|
||||
S::Villager | S::ZombieVillager => {
|
||||
let base = if m.species() == S::Villager {
|
||||
"villager"
|
||||
} 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 rotation = super::aquatic::rotations(m, alpha, body)
|
||||
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians()));
|
||||
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
|
||||
if m.death_time > 0 {
|
||||
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
|
||||
.sqrt()
|
||||
.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());
|
||||
let mut poses = Poses::new(&model);
|
||||
anim::setup(m, &s, &mut poses, &data.animations);
|
||||
if let Some(uv) = atlas(&texture) {
|
||||
draw(&model, base, &poses, uv, body_color(m), light, overlay, out);
|
||||
}
|
||||
held_items(m, &model, base, &poses, atlas, light, out);
|
||||
for layer in layers(m) {
|
||||
let Some(part) = m.kind.layer(&layer.model).cloned() else {
|
||||
continue;
|
||||
};
|
||||
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);
|
||||
}
|
||||
|
||||
/// The transform of a named part (ModelPart.translateAndRotate down the tree).
|
||||
pub fn part_matrix(part: &Part, parent: glam::Mat4, poses: &Poses, name: &str, x_offset: f32) -> Option<glam::Mat4> {
|
||||
let mut p = poses.pose(part);
|
||||
if part.name == name {
|
||||
p[0] += x_offset;
|
||||
}
|
||||
let m = parent
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(p[0], p[1], p[2]) / 16.0)
|
||||
* glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3]))
|
||||
* glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8]));
|
||||
if part.name == name {
|
||||
return Some(m);
|
||||
}
|
||||
part.children.iter().find_map(|c| part_matrix(c, m, poses, name, x_offset))
|
||||
}
|
||||
/// ItemModel thirdperson_righthand display transform by item model parent.
|
||||
fn item_display(item: &str) -> ([f32; 3], [f32; 3], [f32; 3]) {
|
||||
let name = item.trim_start_matches("minecraft:");
|
||||
if name == "bow" {
|
||||
([-80.0, 260.0, -40.0], [-1.0, -2.0, 2.5], [0.9; 3])
|
||||
} else if name == "crossbow" {
|
||||
([-90.0, 0.0, -60.0], [2.0, 0.1, -3.0], [0.9; 3])
|
||||
} else if name == "fishing_rod" || name == "carrot_on_a_stick" || name == "warped_fungus_on_a_stick" {
|
||||
([0.0, 90.0, 55.0], [0.0, 4.0, 2.5], [0.85; 3])
|
||||
} else if ["_sword", "_axe", "_pickaxe", "_shovel", "_hoe", "trident", "mace", "stick", "bone", "blaze_rod"].iter().any(|t| name.ends_with(t)) {
|
||||
([0.0, -90.0, 55.0], [0.0, 4.0, 0.5], [0.85; 3])
|
||||
} else {
|
||||
([0.0, 0.0, 0.0], [0.0, 3.0, 1.0], [0.55; 3])
|
||||
}
|
||||
}
|
||||
/// The sprite drawn for a held item (bow pull frames while charging).
|
||||
fn item_sprite(m: &Mob, item: &str) -> String {
|
||||
let name = item.trim_start_matches("minecraft:");
|
||||
if name == "bow" && m.extra.using_item > 0 {
|
||||
let pull = m.extra.using_item as f32 * 0.05;
|
||||
let frame = if pull >= 0.9 { 2 } else if pull >= 0.65 { 1 } else { 0 };
|
||||
return format!("item/bow_pulling_{frame}");
|
||||
}
|
||||
if name == "crossbow" && m.extra.flag2 {
|
||||
return "item/crossbow_arrow".into();
|
||||
}
|
||||
format!("item/{name}")
|
||||
}
|
||||
/// ItemInHandLayer: items in the mob's hands.
|
||||
fn held_items(m: &Mob, model: &Part, base: glam::Mat4, poses: &Poses, atlas: Atlas, light: u32, out: &mut Vec<Vertex>) {
|
||||
let skeleton = matches!(m.species(), Species::Skeleton | Species::Stray | Species::Bogged | Species::WitherSkeleton);
|
||||
for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] {
|
||||
let Some(item) = item else { continue };
|
||||
let arm = if left { "left_arm" } else { "right_arm" };
|
||||
let offset = if skeleton { if left { -1.0 } else { 1.0 } } else { 0.0 };
|
||||
let Some(mut t) = part_matrix(model, base, poses, arm, offset) else { continue };
|
||||
let Some(uv) = atlas(&item_sprite(m, item)) else { continue };
|
||||
let baby = m.is_baby();
|
||||
let (ox, oy, oz) = if baby { (0.0, 1.0, -4.5) } else { (1.0, 2.0, -10.0) };
|
||||
t *= glam::Mat4::from_rotation_x((-90.0f32).to_radians()) * glam::Mat4::from_rotation_y(PI);
|
||||
t *= glam::Mat4::from_translation(glam::Vec3::new(if left { -ox } else { ox } / 16.0, oy / 16.0, oz / 16.0));
|
||||
// ItemTransform.apply (mirrored for the left hand).
|
||||
let (rot, tr, sc) = item_display(item);
|
||||
let (ry, rz, tx) = if left { (-rot[1], -rot[2], -tr[0]) } else { (rot[1], rot[2], tr[0]) };
|
||||
t *= glam::Mat4::from_translation(glam::Vec3::new(tx, tr[1], tr[2]) / 16.0);
|
||||
t *= glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, rot[0].to_radians(), ry.to_radians(), rz.to_radians()));
|
||||
t *= glam::Mat4::from_scale(glam::Vec3::from(sc));
|
||||
t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
|
||||
draw_item_plane(t, uv, light, out);
|
||||
}
|
||||
}
|
||||
/// A generated item model: the sprite on two faces 1/16 apart.
|
||||
pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec<Vertex>) {
|
||||
let (u0, v0, u1, v1) = (uv[0], uv[1], uv[2], uv[3]);
|
||||
let south = 8.5 / 16.0;
|
||||
let north = 7.5 / 16.0;
|
||||
let quads = [
|
||||
[([0.0, 0.0, south], [u0, v1]), ([1.0, 0.0, south], [u1, v1]), ([1.0, 1.0, south], [u1, v0]), ([0.0, 1.0, south], [u0, v0])],
|
||||
[([1.0, 0.0, north], [u1, v1]), ([0.0, 0.0, north], [u0, v1]), ([0.0, 1.0, north], [u0, v0]), ([1.0, 1.0, north], [u1, v0])],
|
||||
];
|
||||
for q in quads {
|
||||
for (p, uv) in q {
|
||||
let pos = t.transform_point3(glam::Vec3::from(p));
|
||||
out.push(Vertex { pos: pos.to_array(), uv, layer: 0, color: 0xFFFF_FFFF, light });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
//! 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
|
||||
}
|
||||
// GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water.
|
||||
S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water",
|
||||
S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => {
|
||||
// WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level.
|
||||
(50..=63).contains(&y) && w.fluid(x, y - 1, z) == Fluid::Water && w.block_name(x, y + 1, z) == "minecraft:water"
|
||||
}
|
||||
S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay",
|
||||
S::Strider => w.fluid(x, y, z) == Fluid::Lava,
|
||||
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);
|
||||
}
|
||||
S::TropicalFish => super::aquatic::finalize(m),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// 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,177 @@
|
||||
//! Witches (potion drinking and splash potion attacks) and the shared
|
||||
//! `RangedAttackGoal` (also used by snow golems).
|
||||
use super::{
|
||||
Mob, MobEvent, Species, Who,
|
||||
anim::{Poses, State},
|
||||
goals::{Cx, Float, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, Stroll, goal_clone},
|
||||
};
|
||||
use crate::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
|
||||
pub fn register(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(1, Float);
|
||||
g.add(2, RangedAttack::new(1.0, 60, 60, 10.0, witch_attack));
|
||||
g.add(2, Stroll::avoiding_water(1.0));
|
||||
g.add(3, LookAtPlayer::new(8.0));
|
||||
g.add(3, RandomLookAround::default());
|
||||
m.ai.targets.add(1, HurtByTarget::new());
|
||||
m.ai.targets.add(3, NearestTarget::player(true).interval(10));
|
||||
}
|
||||
/// The callback a ranged mob uses to fire (`RangedAttackMob.performRangedAttack`).
|
||||
pub type Fire = fn(&mut Mob, Who, f32, &mut Cx);
|
||||
|
||||
/// RangedAttackGoal(speed, intervalMin, intervalMax, radius).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RangedAttack {
|
||||
speed: f64,
|
||||
min: i32,
|
||||
max: i32,
|
||||
radius: f32,
|
||||
fire: Fire,
|
||||
attack_time: i32,
|
||||
see_time: i32,
|
||||
}
|
||||
impl RangedAttack {
|
||||
pub fn new(speed: f64, min: i32, max: i32, radius: f32, fire: Fire) -> Self {
|
||||
Self { speed, min, max, radius, fire, attack_time: -1, see_time: 0 }
|
||||
}
|
||||
}
|
||||
impl Goal for RangedAttack {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
m.target_info(cx.w).is_some_and(|t| t.alive)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.can_use(m, cx) || m.target_info(cx.w).is_some_and(|t| t.alive) && !m.ai.nav.is_done()
|
||||
}
|
||||
fn stop(&mut self, _: &mut Mob, _: &mut Cx) {
|
||||
self.see_time = 0;
|
||||
self.attack_time = -1;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(who) = m.ai.target else { return };
|
||||
let Some(t) = cx.w.target_info(who) else { return };
|
||||
let d2 = m.distance_sqr(t.position);
|
||||
let sees = m.sees(cx.w, who);
|
||||
if sees {
|
||||
self.see_time += 1;
|
||||
} else {
|
||||
self.see_time = 0;
|
||||
}
|
||||
if d2 <= f64::from(self.radius * self.radius) && self.see_time >= 5 {
|
||||
m.nav_stop();
|
||||
} else {
|
||||
m.nav_move_to_entity(cx.w, [t.position.x, t.position.y, t.position.z], 1, self.speed);
|
||||
}
|
||||
m.look_at_speed([t.position.x, t.eye_y, t.position.z], 30.0, 30.0);
|
||||
self.attack_time -= 1;
|
||||
if self.attack_time == 0 {
|
||||
if !sees {
|
||||
return;
|
||||
}
|
||||
let dist = (d2.sqrt() as f32) / self.radius;
|
||||
let power = dist.clamp(0.1, 1.0);
|
||||
(self.fire)(m, who, power, cx);
|
||||
self.attack_time = (dist * (self.max - self.min) as f32 + self.min as f32).floor() as i32;
|
||||
} else if self.attack_time < 0 {
|
||||
let f = d2.sqrt() / f64::from(self.radius);
|
||||
self.attack_time = (f64::from(self.min) + f * f64::from(self.max - self.min)).floor() as i32;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Witch.performRangedAttack: harming by default, slowness at range, poison
|
||||
/// on healthy targets, weakness up close.
|
||||
fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
|
||||
if m.extra.using_item > 0 {
|
||||
return;
|
||||
}
|
||||
let Some(t) = cx.w.target_info(who) else { return };
|
||||
let xd = t.position.x - m.position.x;
|
||||
let yd = t.eye_y - 1.1 - m.position.y;
|
||||
let zd = t.position.z - m.position.z;
|
||||
let dist = (xd * xd + zd * zd).sqrt();
|
||||
let health = if t.is_player { 20.0 } else { cx.w.seen(match who { Who::Mob(id) => id, Who::Player => 0 }).map_or(20.0, |s| s.health) };
|
||||
let (effect, ticks, amplifier) = if dist >= 8.0 {
|
||||
("minecraft:slowness", 1800, 0)
|
||||
} else if health >= 8.0 {
|
||||
("minecraft:poison", 900, 0)
|
||||
} else if dist <= 3.0 && m.random.next_float() < 0.25 {
|
||||
("minecraft:weakness", 1800, 0)
|
||||
} else {
|
||||
("minecraft:instant_damage", 1, 0)
|
||||
};
|
||||
let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z);
|
||||
let mut p = Projectile::new(ProjectileKind::Potion { effect, ticks, amplifier, color: 0 }, start, Some(Who::Mob(m.id)));
|
||||
// Splash potions throw with gravity 0.05.
|
||||
p.shoot(&mut m.random, [xd, yd + dist * 0.2, zd], if dist <= 2.0 { 0.45 } else { 0.75 }, 8.0);
|
||||
cx.events.push(MobEvent::Projectile(p));
|
||||
let pitch = 0.8 + m.random.next_float() * 0.4;
|
||||
cx.events.push(MobEvent::Sound("entity.witch.throw", m.center(), 1.0, pitch));
|
||||
}
|
||||
/// Witch.aiStep: drink water breathing, fire resistance, healing or swiftness.
|
||||
pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
|
||||
if !m.alive() {
|
||||
return;
|
||||
}
|
||||
if m.extra.using_item > 0 {
|
||||
m.extra.using_item -= 1;
|
||||
if m.extra.using_item <= 0 {
|
||||
m.extra.using_item = 0;
|
||||
if let Some(potion) = m.extra.main_hand.take() {
|
||||
match potion.as_ref() {
|
||||
"minecraft:water_breathing" => m.add_effect("minecraft:water_breathing", 3600, 0),
|
||||
"minecraft:fire_resistance" => m.add_effect("minecraft:fire_resistance", 3600, 0),
|
||||
"minecraft:healing" => m.health = (m.health + 4.0).min(m.attrs.max_health),
|
||||
"minecraft:swiftness" => m.add_effect("minecraft:speed", 3600, 0),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
m.extra.flag = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let potion = if m.random.next_float() < 0.15 && m.fluids.eye_in_water && !m.has_effect("minecraft:water_breathing") {
|
||||
Some("minecraft:water_breathing")
|
||||
} else if m.random.next_float() < 0.15 && (m.fire_ticks > 0 || m.last_damage.is_some_and(|(d, _)| d.is_fire())) && !m.has_effect("minecraft:fire_resistance") {
|
||||
Some("minecraft:fire_resistance")
|
||||
} else if m.random.next_float() < 0.05 && m.health < m.attrs.max_health {
|
||||
Some("minecraft:healing")
|
||||
} else if m.random.next_float() < 0.5 && m.ai.target.is_some() && !m.has_effect("minecraft:speed") && target_far {
|
||||
Some("minecraft:swiftness")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(p) = potion {
|
||||
m.extra.main_hand = Some(p.into());
|
||||
// PotionItem use duration 32 ticks.
|
||||
m.extra.using_item = 32;
|
||||
m.extra.flag = true;
|
||||
let pitch = 0.8 + m.random.next_float() * 0.4;
|
||||
cx_events.push(MobEvent::Sound("entity.witch.drink", m.center(), 1.0, pitch));
|
||||
}
|
||||
}
|
||||
/// WitchModel.setupAnim (VillagerModel base with a wobbling nose).
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
p.yrot("head", s.y_rot.to_radians());
|
||||
p.xrot("head", s.x_rot.to_radians());
|
||||
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5);
|
||||
p.xrot("left_leg", (s.pos * 0.6662 + std::f32::consts::PI).cos() * 1.4 * s.speed * 0.5);
|
||||
let speed = 0.01 * (m.id % 10) as f32;
|
||||
p.xrot("nose", (s.age * speed).sin() * 4.5 * std::f32::consts::PI / 180.0);
|
||||
p.zrot("nose", (s.age * speed).cos() * 2.5 * std::f32::consts::PI / 180.0);
|
||||
if m.extra.main_hand.is_some() {
|
||||
let n = p.get("nose");
|
||||
n[0] = 0.0;
|
||||
n[1] = 1.0;
|
||||
n[2] = -1.5;
|
||||
n[3] = -0.9;
|
||||
}
|
||||
let _ = Species::Witch;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -378,6 +378,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])
|
||||
@@ -406,6 +422,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