From e0541ece83edfde9b8860f36e5321bd307f4180d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:44:46 +0200 Subject: [PATCH 1/4] Verify entity model animation against vanilla and fix what differed A new Java oracle bakes every vanilla model layer, builds the model's own render state and runs the real setupAnim; tools/test_entity_model_parity.py replays the same states through Horizon's animation code and compares every part pose, visibility and the baked polygon sums (about 3700 cases over 125 layers). Fixes the harness found: model sine and cosine now use vanilla's quantised table, the creeper's swapped leg bindings, humanoid arm poses in vanilla order (held items no longer tilt mob arms, bows pose both arms last, crossbow charge, riding, crouching), swing weapon down, piglin ears and dancing, illager hats, arms and bow pose, zombified piglin ears, baby donkey head and legs, hoglin baby head, ravager neck, vex charging arms, feline sitting and lying poses including babies, camel and zombie/skeleton horse baby models, and new ports of the goat, polar bear, panda, llama, turtle, strider, snow golem, silverfish, endermite, parrot, bee, bat, armadillo, axolotl, frog, rabbit and fox models. Hidden parts are now an explicit flag instead of a zero scale, and skipDraw is supported. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/entity_anim_fixture.rs | 433 +++++++ crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/allay.rs | 18 +- crates/horizon-client/src/mobs/anim.rs | 378 +++--- crates/horizon-client/src/mobs/aquatic.rs | 31 +- crates/horizon-client/src/mobs/body_anim.rs | 1044 +++++++++++++++++ crates/horizon-client/src/mobs/camel.rs | 3 +- crates/horizon-client/src/mobs/data.rs | 8 + crates/horizon-client/src/mobs/equine.rs | 35 +- crates/horizon-client/src/mobs/guardian.rs | 21 +- crates/horizon-client/src/mobs/illager.rs | 96 +- crates/horizon-client/src/mobs/nether.rs | 23 +- crates/horizon-client/src/mobs/phantom.rs | 19 +- crates/horizon-client/src/mobs/piglin.rs | 125 +- crates/horizon-client/src/mobs/ravager.rs | 26 +- crates/horizon-client/src/mobs/render.rs | 7 +- crates/horizon-client/src/mobs/shulker.rs | 9 +- crates/horizon-client/src/mobs/species.rs | 3 + crates/horizon-client/src/mobs/tame.rs | 110 +- crates/horizon-client/src/mobs/vex.rs | 32 +- crates/horizon-client/src/mobs/villager.rs | 7 +- crates/horizon-client/src/mobs/witch.rs | 16 +- crates/horizon-client/src/mobs/wither.rs | 11 +- crates/horizon-core/src/geometry/trig.rs | 14 + .../parity/VanillaEntityAnimOracle.java | 196 ++++ tools/test_entity_model_parity.py | 296 +++++ 26 files changed, 2608 insertions(+), 354 deletions(-) create mode 100644 crates/horizon-client/examples/entity_anim_fixture.rs create mode 100644 crates/horizon-client/src/mobs/body_anim.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java create mode 100644 tools/test_entity_model_parity.py diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs new file mode 100644 index 000000000..df13cbb61 --- /dev/null +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -0,0 +1,433 @@ +//! Replays the render states of the vanilla entity-animation oracle through +//! Horizon's `mobs::anim::setup` and writes every part's pose. +//! +//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ +//! RESOURCES VANILLA.jsonl OUT.jsonl +use horizon_client::mobs::{ + Mob, MobData, MobTypes, Part, Species, allay, + anim::{self, Poses, State}, + aquatic, body_anim as b_anim, equine, guardian, + keyframes::AnimationState, + shulker, species, tame, +}; +use horizon_core::geometry::Vec3; +use serde_json::{Value, json}; +use std::{collections::BTreeMap, fs, path::PathBuf, sync::Arc}; + +fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap) { + let p = poses.pose(part); + let mut polys = 0; + let mut sum = 0.0f64; + for polygon in &part.polygons { + polys += 1; + for v in polygon.vertices { + sum += f64::from(v[0]) + + 2.0 * f64::from(v[1]) + + 3.0 * f64::from(v[2]) + + 5.0 * f64::from(v[3]) + + 7.0 * f64::from(v[4]); + } + } + let visible = !poses.is_hidden(part) && !poses.skips(part); + let mut row: Vec = p.iter().map(|&x| json!(x)).collect(); + row.push(json!(u8::from(visible))); + row.push(json!(polys)); + row.push(json!(sum)); + out.insert(path.to_owned(), Value::Array(row)); + for c in &part.children { + let child = if path.is_empty() { + c.name.clone() + } else { + format!("{path}/{}", c.name) + }; + walk(c, &child, poses, out); + } +} + +/// The entity-side values behind the render-state fields the case sets, for +/// the species whose Horizon animation reads them from the `Mob`. +fn entity_state(mob: &mut Mob, species: Species, case: &Value) { + let flag = |k: &str| case[k].as_bool().unwrap_or(false); + let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + match species { + Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32, + Species::Guardian | Species::ElderGuardian => { + mob.anim.v[guardian::TAIL] = num("tailAnimation"); + mob.anim.vo[guardian::TAIL] = num("tailAnimation"); + mob.anim.v[guardian::SPIKES] = num("spikesAnimation"); + mob.anim.vo[guardian::SPIKES] = num("spikesAnimation"); + } + Species::Shulker => { + mob.anim.v[shulker::PEEK] = num("peekAmount"); + mob.anim.vo[shulker::PEEK] = num("peekAmount"); + } + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + | Species::Giant + | Species::Skeleton + | Species::Stray + | Species::Bogged + | Species::WitherSkeleton + | Species::Parched => { + mob.ai.aggressive = flag("isAggressive"); + mob.extra.crouching = flag("isCrouching"); + mob.extra.passenger = flag("isPassenger"); + if flag("isHoldingBow") { + mob.extra.main_hand = Some("minecraft:bow".into()); + } + } + Species::IronGolem => { + mob.extra.anim_ticks = num("attackTicksRemaining") as i32; + mob.extra.counter = num("offerFlowerTick") as i32; + } + Species::Hoglin | Species::Zoglin => { + mob.extra.anim_ticks = num("attackAnimationRemainingTicks") as i32; + } + Species::Ravager => { + mob.extra.counter2 = num("stunnedTicksRemaining") as i32; + mob.extra.counter = num("attackTicksRemaining") as i32; + let roar = num("roarAnimation"); + if roar > 0.0 { + mob.extra.anim_ticks = (20.0 - roar * 20.0) as i32; + } + } + Species::Vex => mob.extra.flag = flag("isCharging"), + Species::Squid | Species::GlowSquid => { + mob.anim.v[aquatic::TENTACLE_ANGLE] = num("tentacleAngle"); + mob.anim.vo[aquatic::TENTACLE_ANGLE] = num("tentacleAngle"); + } + Species::Dolphin => { + if flag("isMoving") { + mob.velocity.x = 0.1; + } + } + Species::Cod | Species::Salmon | Species::TropicalFish | Species::Tadpole => { + mob.fluids.in_water = flag("isInWater"); + } + Species::Allay => { + mob.extra.flag = flag("isDancing"); + mob.extra.ints[4] = if flag("isSpinning") { 10 } else { 20 }; + mob.anim.v[allay::SPIN] = num("spinningProgress") * 15.0; + mob.anim.vo[allay::SPIN] = num("spinningProgress") * 15.0; + mob.anim.v[allay::HOLD] = num("holdingAnimationProgress") * 5.0; + mob.anim.vo[allay::HOLD] = num("holdingAnimationProgress") * 5.0; + } + Species::Horse + | Species::Donkey + | Species::Mule + | Species::ZombieHorse + | Species::SkeletonHorse => { + for (slot, key) in [ + (equine::EAT, "eatAnimation"), + (equine::STAND, "standAnimation"), + (equine::MOUTH, "feedingAnimation"), + ] { + mob.anim.v[slot] = num(key); + mob.anim.vo[slot] = num(key); + } + mob.fluids.in_water = flag("isInWater"); + mob.extra.chested = flag("hasChest"); + } + Species::Camel => { + for (i, k) in [ + "sitAnimationState", + "sitPoseAnimationState", + "sitUpAnimationState", + "idleAnimationState", + "dashAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + mob.extra.anim_ticks = num("jumpCooldown") as i32; + } + Species::Chicken => { + mob.anim.flap = num("flap"); + mob.anim.flap_o = num("flap"); + mob.anim.flap_speed = num("flapSpeed"); + mob.anim.flap_speed_o = num("flapSpeed"); + } + Species::Wolf => { + mob.extra.sitting = flag("isSitting"); + mob.extra.anger = if flag("isAngry") { 100 } else { 0 }; + mob.anim.v[tame::SHAKE] = num("shakeAnim"); + mob.anim.vo[tame::SHAKE] = num("shakeAnim"); + mob.anim.v[tame::INTEREST] = num("interest"); + mob.anim.vo[tame::INTEREST] = num("interest"); + } + Species::Creaking => { + mob.extra.flag2 = !flag("canMove"); + for (i, k) in [ + "attackAnimationState", + "invulnerabilityAnimationState", + "deathAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + } + Species::Witch if flag("isHoldingItem") => { + mob.extra.main_hand = Some("minecraft:potion".into()); + } + _ => {} + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let root = PathBuf::from(&args[0]); + let types = MobTypes::load(&root)?; + let animations = MobData::load_animations(&root); + let mut out = String::new(); + for line in fs::read_to_string(&args[1])?.lines() { + let v: Value = serde_json::from_str(line)?; + let layer = v["layer"] + .as_str() + .unwrap_or_default() + .trim_start_matches("minecraft:"); + let baby = layer.contains("_baby#"); + let adult = layer.replace("_baby#", "#"); + // Variant layers (sizes, hatless villagers, climate cows...) animate + // like their base model. + let mut base = adult.clone(); + for cut in ["_no_hat", "_small", "_medium", "_large"] { + base = base.replace(cut, ""); + } + let base = base.trim_start_matches("cold_").trim_start_matches("warm_"); + let Some(def) = species::ALL.iter().find(|d| { + d.model == layer + || (baby && d.model == adult) + || d.model == base + || d.model.trim_end_matches("#main") == base.trim_end_matches("#main") + }) else { + out.push_str(&format!("{}\n", json!({"skip": "no species"}))); + continue; + }; + let Some(kind) = types.types.get(&format!("minecraft:{}", def.name)) else { + out.push_str(&format!("{}\n", json!({"skip": "no type"}))); + continue; + }; + let kind = Arc::new(kind.clone()); + let model = kind + .layer(layer) + .cloned() + .unwrap_or_else(|| kind.model.clone()); + let mut mob = Mob::new(7, kind, Vec3::new(0.0, 64.0, 0.0), 0.0); + mob.extra.main_hand = None; + let case = &v["case"]; + let f = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + if baby { + mob.extra.age = -24000; + } + mob.age = f("ageInTicks") as u32; + let state = State { + pos: f("walkAnimationPos"), + speed: f("walkAnimationSpeed"), + age: f("ageInTicks"), + y_rot: f("yRot"), + x_rot: f("xRot"), + swing: f("swingAnimation"), + baby, + partial: 0.0, + }; + let mut poses = Poses::new(&model); + entity_state(&mut mob, def.species, case); + let flag = |k: &str| case[k].as_bool().unwrap_or(false); + let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; + let started = |k: &str| AnimationState { + started: case[k].as_f64().map(|v| v as f32), + }; + let (p, s) = (&mut poses, &state); + match def.species { + Species::Goat => b_anim::goat( + p, + s, + &b_anim::Goat { + left_horn: flag("hasLeftHorn"), + right_horn: flag("hasRightHorn"), + ramming_x_head_rot: num("rammingXHeadRot"), + }, + ), + Species::PolarBear => b_anim::polar_bear(p, s, num("standScale")), + Species::Panda => b_anim::panda( + p, + s, + &b_anim::Panda { + unhappy: flag("isUnhappy"), + sneezing: flag("isSneezing"), + sneeze_time: num("sneezeTime") as i32, + eating: flag("isEating"), + scared: flag("isScared"), + sit_amount: num("sitAmount"), + lie_on_back_amount: num("lieOnBackAmount"), + roll_amount: num("rollAmount"), + }, + ), + Species::Llama | Species::TraderLlama => b_anim::llama(p, s, flag("hasChest")), + Species::Turtle => b_anim::turtle( + p, + s, + &b_anim::Turtle { + on_land: flag("isOnLand"), + laying_egg: flag("isLayingEgg"), + has_egg: flag("hasEgg"), + }, + ), + Species::Strider => b_anim::strider(p, s, flag("isRidden")), + Species::SnowGolem => b_anim::snow_golem(p, s), + Species::Silverfish => b_anim::silverfish(p, s), + Species::Endermite => b_anim::endermite(p, s), + Species::Parrot => b_anim::parrot( + p, + s, + match case["pose"].as_str() { + Some("FLYING") => b_anim::ParrotPose::Flying, + Some("ON_SHOULDER") => b_anim::ParrotPose::OnShoulder, + Some("SITTING") => b_anim::ParrotPose::Sitting, + Some("PARTY") => b_anim::ParrotPose::Party, + _ => b_anim::ParrotPose::Standing, + }, + num("flapAngle"), + ), + Species::Bee => b_anim::bee( + p, + s, + &b_anim::Bee { + has_stinger: flag("hasStinger"), + on_ground: flag("isOnGround"), + angry: flag("isAngry"), + roll_amount: num("rollAmount"), + }, + ), + Species::Bat => b_anim::bat( + p, + s, + flag("isResting"), + &started("flyAnimationState"), + &started("restAnimationState"), + &animations, + ), + Species::Armadillo => b_anim::armadillo( + p, + s, + &b_anim::Armadillo { + hiding_in_shell: flag("isHidingInShell"), + roll_out: started("rollOutAnimationState"), + roll_up: started("rollUpAnimationState"), + peek: started("peekAnimationState"), + }, + &animations, + ), + Species::Axolotl => b_anim::axolotl( + p, + s, + &b_anim::Axolotl { + playing_dead: num("playingDeadFactor"), + in_water: num("inWaterFactor"), + on_ground: num("onGroundFactor"), + moving: num("movingFactor"), + swim: started("swimAnimation"), + walk: started("walkAnimationState"), + idle_on_ground: started("idleOnGroundAnimationState"), + idle_underwater_on_ground: started("idleUnderWaterOnGroundAnimationState"), + idle_underwater: started("idleUnderWaterAnimationState"), + play_dead: started("playDeadAnimationState"), + }, + &animations, + ), + Species::Frog => b_anim::frog( + p, + s, + &b_anim::Frog { + swimming: flag("isSwimming"), + jump: started("jumpAnimationState"), + croak: started("croakAnimationState"), + tongue: started("tongueAnimationState"), + swim_idle: started("swimIdleAnimationState"), + }, + &animations, + ), + Species::Rabbit => b_anim::rabbit( + p, + s, + &started("hopAnimationState"), + &started("idleHeadTiltAnimationState"), + &animations, + ), + Species::Fox => b_anim::fox( + p, + s, + &b_anim::Fox { + crouching: flag("isCrouching"), + sleeping: flag("isSleeping"), + sitting: flag("isSitting"), + pouncing: flag("isPouncing"), + faceplanted: flag("isFaceplanted"), + head_roll_angle: num("headRollAngle"), + crouch_amount: num("crouchAmount"), + leg_motion_pos: 0.67, + }, + &animations, + ), + Species::Cat | Species::Ocelot => horizon_client::mobs::tame::feline( + p, + s, + &horizon_client::mobs::tame::Feline { + crouching: flag("isCrouching"), + sprinting: flag("isSprinting"), + sitting: flag("isSitting"), + lie_down: num("lieDownAmount"), + lie_down_tail: num("lieDownAmountTail"), + relax_one: num("relaxStateOneAmount"), + }, + ), + Species::Piglin | Species::PiglinBrute => { + use horizon_client::mobs::piglin::{PiglinPose, piglin_pose}; + let pose = match case["armPose"].as_str() { + Some("DANCING") => PiglinPose::Dancing, + Some("ATTACKING_WITH_MELEE_WEAPON") => PiglinPose::MeleeWeapon, + Some("CROSSBOW_HOLD") => PiglinPose::CrossbowHold, + Some("CROSSBOW_CHARGE") => PiglinPose::CrossbowCharge, + Some("ADMIRING_ITEM") => PiglinPose::AdmiringItem, + _ => PiglinPose::Default, + }; + piglin_pose( + p, + s, + pose, + num("maxCrossbowChageDuration"), + num("ticksUsingItem"), + ); + } + Species::Evoker | Species::Pillager | Species::Vindicator => { + use horizon_client::mobs::illager::{ArmPose, anim_pose}; + let pose = match case["armPose"].as_str() { + Some("CROSSED") => ArmPose::Crossed, + Some("ATTACKING") => ArmPose::Attacking, + Some("SPELLCASTING") => ArmPose::Spellcasting, + Some("BOW_AND_ARROW") => ArmPose::BowAndArrow, + Some("CROSSBOW_HOLD") => ArmPose::CrossbowHold, + Some("CROSSBOW_CHARGE") => ArmPose::CrossbowCharge, + Some("CELEBRATING") => ArmPose::Celebrating, + _ => ArmPose::Neutral, + }; + mob.extra.passenger = flag("isRiding"); + mob.extra.using_item = num("ticksUsingItem") as i32; + anim_pose(&mob, s, p, pose); + } + _ => anim::setup(&mob, s, p, &animations), + } + let mut parts = BTreeMap::new(); + walk(&model, "", &poses, &mut parts); + out.push_str(&format!("{}\n", json!({"parts": parts}))); + } + fs::write(&args[2], out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 9261846a1..093042a2c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -9,6 +9,7 @@ pub mod ai; pub mod allay; pub mod anim; pub mod aquatic; +pub mod body_anim; pub mod camel; pub mod control; pub mod creaking; diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index d371c1be7..2b674fb87 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -8,6 +8,7 @@ use super::{ goals::{Cx, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone}, nav::NavKind, }; +use horizon_core::geometry::trig::Mth; // Allay state: `main_hand` the held item, `ints[1]` how many it carries, // `tame` a liked player, `point` the wanted item (set by the game), @@ -15,8 +16,8 @@ use super::{ // pickup cooldown, `flag` dancing with `ints[4]` the dance clock, // `egg_time` the duplication cooldown. AnimState slots: holding (0), // spinning (1). -const HOLD: usize = 0; -const SPIN: usize = 1; +pub const HOLD: usize = 0; +pub const SPIN: usize = 1; pub fn register(m: &mut Mob) { m.ai.mov.kind = MoveKind::Flying { @@ -151,22 +152,22 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { use std::f32::consts::PI; let (speed, pos) = (s.speed, s.pos); let flap_speed = (s.age * 20.0).to_radians() + pos; - let flap = flap_speed.cos() * PI * 0.15 + speed; + let flap = flap_speed.mcos() * PI * 0.15 + speed; let idle_bob = (s.age * 9.0).to_radians(); let flying = (speed / 0.3).min(1.0); let idle = 1.0 - flying; let hold = m.anim.lerp(HOLD, s.partial) / 5.0; if m.extra.flag { let dance = (s.age * 8.0).to_radians() + speed; - let freq = dance.cos() * 16f32.to_radians(); + let freq = dance.mcos() * 16f32.to_radians(); let spin = m.anim.lerp(SPIN, s.partial) / 15.0; let spinning = (m.extra.ints[4] as f32 % 55.0) < 15.0; if spinning { p.yrot("root", PI * 4.0 * spin); } p.zrot("root", freq * (1.0 - spin)); - p.yrot("head", dance.cos() * 30f32.to_radians() * (1.0 - spin)); - p.zrot("head", dance.cos() * 14f32.to_radians() * (1.0 - spin)); + p.yrot("head", dance.mcos() * 30f32.to_radians() * (1.0 - spin)); + p.zrot("head", dance.mcos() * 14f32.to_radians() * (1.0 - spin)); } else { p.xrot("head", s.x_rot.to_radians()); p.yrot("head", s.y_rot.to_radians()); @@ -177,11 +178,12 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("left_wing", PI / 4.0 - flap); p.xrot("body", flying * PI / 4.0); let arm_x = hold * (-PI / 3.0 + (-1.134_464 + PI / 3.0) * flying); - p.get("root")[1] += idle_bob.cos() * 0.25 * idle; + // `(float) Math.cos`: the exact function, not `Mth.cos`. + p.get("root")[1] += (f64::from(idle_bob).cos() as f32) * 0.25 * idle; p.xrot("right_arm", arm_x); p.xrot("left_arm", arm_x); let arm_bob = idle * (1.0 - hold); - let amount = 0.436_332_32 - (idle_bob + PI * 1.5).cos() * PI * 0.075 * arm_bob; + let amount = 0.436_332_32 - (idle_bob + PI * 1.5).mcos() * PI * 0.075 * arm_bob; p.zrot("left_arm", -amount); p.zrot("right_arm", amount); p.yrot("right_arm", 0.279_252_68 * hold); diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index ae44a2630..ca72c04a7 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -2,6 +2,7 @@ //! (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 horizon_core::geometry::trig::Mth; use std::collections::HashMap; use std::f32::consts::PI; @@ -98,6 +99,10 @@ impl AnimState { pub struct Poses { map: HashMap, dummy: [f32; 9], + /// Parts with `skipDraw` set: their own cubes are not drawn, children are. + skipped: std::collections::HashSet, + /// Parts with `visible` cleared: neither they nor their children draw. + hidden: std::collections::HashSet, } impl Poses { pub fn new(model: &Part) -> Self { @@ -112,6 +117,8 @@ impl Poses { Self { map, dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), } } pub fn get(&mut self, name: &str) -> &mut [f32; 9] { @@ -123,6 +130,12 @@ impl Poses { pub fn pose(&self, part: &Part) -> [f32; 9] { self.map.get(&part.name).copied().unwrap_or(part.pose) } + pub fn skip_draw(&mut self, name: &str) { + self.skipped.insert(name.to_owned()); + } + pub fn skips(&self, part: &Part) -> bool { + self.skipped.contains(&part.name) + } pub fn has(&self, name: &str) -> bool { self.map.contains_key(name) } @@ -135,14 +148,17 @@ impl Poses { pub fn zrot(&mut self, n: &str, v: f32) { self.get(n)[5] = v; } + /// `ModelPart.visible = v`; a hidden part and its children do not draw. 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; + if v { + self.hidden.remove(n); + } else if self.map.contains_key(n) { + self.hidden.insert(n.to_owned()); } } + pub fn is_hidden(&self, part: &Part) -> bool { + self.hidden.contains(&part.name) + } } /// The LivingEntityRenderState values setupAnim reads. #[derive(Clone, Copy, Debug)] @@ -191,21 +207,21 @@ fn head(p: &mut Poses, s: &State) { p.yrot("head", s.y_rot.to_radians()); } /// QuadrupedModel.setupAnim -fn quadruped(p: &mut Poses, s: &State) { +pub(super) 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); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * sp); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 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); + q[5] += scale * ((age * 0.09).mcos() * 0.05 + 0.05); + q[3] += scale * ((age * 0.067).msin() * 0.05); } -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum ArmPose { Empty, Item, @@ -213,118 +229,196 @@ pub enum ArmPose { CrossbowHold, CrossbowCharge, } -/// HumanoidModel.setupAnim holding an item or not (piglins). -pub fn humanoid_item(p: &mut Poses, s: &State, holding: bool) { - let right = if holding { - ArmPose::Item - } else { - ArmPose::Empty - }; - humanoid(p, s, right, ArmPose::Empty, None, holding); +/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. +pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { + humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { - humanoid(p, s, ArmPose::Empty, ArmPose::Empty, None, false); + humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); } -/// HumanoidModel.setupAnim up to (and including) the attack animation hook. -fn humanoid( - p: &mut Poses, - s: &State, - right: ArmPose, - left: ArmPose, - zombie: Option, - holding: bool, -) { +/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm. +pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) { + let attack2 = (swing * PI).msin(); + let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); + p.zrot("right_arm", 0.0); + p.zrot("left_arm", 0.0); + p.yrot("right_arm", PI / 20.0); + p.yrot("left_arm", -PI / 20.0); + p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15); + p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5); + p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4; + p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4; + bob(p, "right_arm", age, 1.0); + bob(p, "left_arm", age, -1.0); +} +/// What `HumanoidModel.setupAnim` reads besides the walk and head inputs. +#[derive(Clone, Copy, Debug)] +pub struct Hum { + pub right: ArmPose, + pub left: ArmPose, + pub crouching: bool, + pub passenger: bool, + /// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`. + pub zombie: Option, + /// The main hand holds something (`getMainHandItemStack() != EMPTY`). + pub holding: bool, + /// `maxCrossbowChargeDuration`, `ticksUsingItem`. + pub charge: (f32, f32), + /// `PiglinModel.setupAttackAnimation`: swing a held weapon down. + pub weapon_swing: bool, +} +impl Hum { + pub fn new(right: ArmPose, left: ArmPose) -> Self { + Self { + right, + left, + crouching: false, + passenger: false, + zombie: None, + holding: false, + charge: (0.0, 0.0), + weapon_swing: false, + } + } +} +impl ArmPose { + fn two_handed(self) -> bool { + matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge) + } + fn affects_offhand(self) -> bool { + self.two_handed() + } +} +/// `AnimationUtils.animateCrossbowHold`. +fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) { + let (hold, shoot) = if in_right { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if in_right { -0.3 } else { 0.3 } + hy); + p.yrot(shoot, if in_right { 0.6 } else { -0.6 } + hy); + p.xrot(hold, -PI / 2.0 + hx + 0.1); + p.xrot(shoot, -1.5 + hx); +} +/// `AnimationUtils.animateCrossbowCharge`. +fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) { + let (hold, pull) = if in_right { + ("right_arm", "left_arm") + } else { + ("left_arm", "right_arm") + }; + p.yrot(hold, if in_right { -0.8 } else { 0.8 }); + p.xrot(hold, -0.970_796_35); + p.xrot(pull, -0.970_796_35); + let use_ticks = ticks.clamp(0.0, max); + let alpha = use_ticks / max; + let lerp = |a: f32, p0: f32, p1: f32| p0 + a * (p1 - p0); + p.yrot( + pull, + lerp(alpha, 0.4, 0.85) * if in_right { 1.0 } else { -1.0 }, + ); + let x = lerp(alpha, p.get(pull)[3], -PI / 2.0); + p.xrot(pull, x); +} +/// `HumanoidModel.poseRightArm` / `poseLeftArm`. +fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { + let arm = if right { "right_arm" } else { "left_arm" }; + let (hx, hy) = (p.get("head")[3], p.get("head")[4]); + 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 => { + p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 }); + p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 }); + p.xrot("right_arm", -PI / 2.0 + hx); + p.xrot("left_arm", -PI / 2.0 + hx); + } + ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right), + ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right), + } +} +/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`). +pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { 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.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5); + p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5); + p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp); + p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 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); - } + if h.passenger { + p.get("right_arm")[3] += -PI / 5.0; + p.get("left_arm")[3] += -PI / 5.0; + p.xrot("right_leg", -1.413_716_7); + p.yrot("right_leg", PI / 10.0); + p.zrot("right_leg", 0.078_539_82); + p.xrot("left_leg", -1.413_716_7); + p.yrot("left_leg", -PI / 10.0); + p.zrot("left_leg", -0.078_539_82); + } + // The main arm is the right one: the off-hand pose goes first unless it + // needs both hands. + if h.left.two_handed() { + pose_arm(p, h.right, true, h); + if !h.right.affects_offhand() { + pose_arm(p, h.left, false, h); + } + } else { + pose_arm(p, h.left, false, h); + if !h.left.affects_offhand() { + pose_arm(p, h.right, true, h); } } // setupAttackAnimation (WHACK swing with the right arm). + let hx = p.get("head")[3]; let swing = s.swing; - if swing > 0.0 { - let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2; + if swing > 0.0 && h.weapon_swing { + swing_weapon_down(p, swing, s.age); + } else if swing > 0.0 { + let body_y = (swing.sqrt() * PI * 2.0).msin() * 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; + r[2] = body_y.msin() * 5.0 * age_scale; + r[0] = -body_y.mcos() * 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; + l[2] = -body_y.msin() * 5.0 * age_scale; + l[0] = body_y.mcos() * 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; + // Ease.outQuart 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 aa = (eased * PI).msin(); + let bb = (swing * PI).msin() * -(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; + r[5] += (swing * PI).msin() * -0.4; } - if let Some(aggressive) = zombie { + if let Some(aggressive) = h.zombie { // AnimationUtils.animateZombieArms - let raise = !s.baby || !holding; + let raise = !s.baby || !h.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 ym = if raise { 1.0 } else { -1.0 } * (swing * PI).msin(); + let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); let x = drop + ym * 1.2 - xm * 0.4; let y = 0.1 - ym * 0.6; p.xrot("right_arm", x); @@ -334,6 +428,17 @@ fn humanoid( p.yrot("left_arm", if raise { y } else { -y }); p.zrot("left_arm", 0.0); } + if h.crouching { + p.xrot("body", 0.5); + p.get("right_arm")[3] += 0.4; + p.get("left_arm")[3] += 0.4; + p.get("right_leg")[2] += 4.0; + p.get("left_leg")[2] += 4.0; + p.get("head")[1] += 4.2; + p.get("body")[1] += 3.2; + p.get("left_arm")[1] += 3.2; + p.get("right_arm")[1] += 3.2; + } bob(p, "right_arm", s.age, 1.0); bob(p, "left_arm", s.age, -1.0); } @@ -344,6 +449,9 @@ pub fn setup( p: &mut Poses, w_anims: &HashMap, ) { + if super::body_anim::anim(m, s, p, w_anims) { + return; + } match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), @@ -368,7 +476,7 @@ pub fn setup( }; 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() + PI / 5.0 + 0.219_911_49 * (f * 28.7).msin() } else if t > 0 { PI / 5.0 } else { @@ -382,9 +490,9 @@ pub fn setup( 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); + let angle = (flap.msin() + 1.0) * flap_speed; + p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed); + p.xrot("left_leg", (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed); p.zrot("right_wing", angle); p.zrot("left_wing", -angle); if !s.baby { @@ -396,57 +504,35 @@ pub fn setup( | 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); + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.zombie = Some(m.ai.aggressive); + h.holding = m.extra.main_hand.is_some(); + h.crouching = m.extra.crouching; + h.passenger = m.extra.passenger; + humanoid(p, s, &h); + if m.kind.anim == Anim::ZombifiedPiglin { + super::piglin::ears(p, s); + } } Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => { let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow"); + let player = matches!(m.kind.anim, Anim::Humanoid { .. }); let right = if bow && m.ai.aggressive { ArmPose::Bow - } else if m.extra.main_hand.is_some() { + } else if player && 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.extra.passenger { - // HumanoidModel.setupAnim: riding. - p.get("right_arm")[3] -= PI / 5.0; - p.get("left_arm")[3] -= PI / 5.0; - for (leg, side) in [("right_leg", 1.0), ("left_leg", -1.0)] { - p.xrot(leg, -1.413_716_7); - p.yrot(leg, side * PI / 10.0); - p.zrot(leg, side * 0.078_539_82); - } - } - if m.extra.crouching { - p.xrot("body", 0.5); - p.get("right_arm")[3] += 0.4; - p.get("left_arm")[3] += 0.4; - p.get("right_leg")[2] += 4.0; - p.get("left_leg")[2] += 4.0; - p.get("head")[1] += 4.2; - p.get("body")[1] += 3.2; - p.get("left_arm")[1] += 3.2; - p.get("right_arm")[1] += 3.2; - } + let mut h = Hum::new(right, ArmPose::Empty); + h.crouching = m.extra.crouching; + h.passenger = m.extra.passenger; + humanoid(p, s, &h); 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(); + let s2 = (sw * PI).msin(); + let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", -(0.1 - s2 * 0.6)); @@ -474,37 +560,37 @@ pub fn setup( // DonkeyModel: the chests show once fitted. if !m.extra.chested { for part in ["left_chest", "right_chest"] { - if p.has(part) { - let v = p.get(part); - v[6] = 0.0; - v[7] = 0.0; - v[8] = 0.0; - } + p.visible(part, false); } } } Anim::Hoglin => super::piglin::hoglin_anim(m, s, p), Anim::Blaze => super::nether::blaze_anim(s, p), Anim::Ghast => super::nether::ghast_anim(s, p), - Anim::Feline if m.species() == super::Species::Cat => super::tame::cat_anim(m, s, p), + Anim::Feline => super::tame::cat_anim(m, s, p), Anim::Enderman => super::enderman::anim(m, s, p), Anim::Slime | Anim::MagmaCube => super::cube::anim(m, s, p), 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); + // CreeperModel binds its fields to the opposite-side parts, so the + // left formulas drive the right parts and the reverse. + p.xrot("left_hind_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed); p.xrot( - "right_front_leg", - (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed, + "right_hind_leg", + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed, ); - p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed); + p.xrot( + "left_front_leg", + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed, + ); + p.xrot("right_front_leg", (s.pos * 0.6662).mcos() * 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 swing = |o: f32| -((pos * 2.0 + o).mcos() * 0.4) * sp; + let step = |o: f32| ((pos + o).msin() * 0.4).abs() * sp; let legs = [ ("hind", 0.0f32, 0.0f32), ("middle_hind", PI, PI), diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index d93a138c9..667802b26 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -12,12 +12,13 @@ use super::{ nav::NavKind, }; use crate::blocks::Fluid; +use horizon_core::geometry::trig::Mth; 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; +pub const TENTACLE_ANGLE: usize = 1; const X_BODY_ROT: usize = 2; const Z_BODY_ROT: usize = 3; const TENTACLE_SPEED: usize = 4; @@ -229,7 +230,7 @@ fn squid_ai_step(m: &mut Mob) { 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; + v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25; if scale > 0.75 { let mv = m.extra.vector; m.velocity = Vec3::new(mv[0], mv[1], mv[2]); @@ -250,7 +251,7 @@ fn squid_ai_step(m: &mut Mob) { 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; + v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().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; @@ -339,9 +340,9 @@ impl Goal for SquidRandomMovement { 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(angle.mcos() * 0.2), f64::from(y), - f64::from(angle.sin() * 0.2), + f64::from(angle.msin() * 0.2), ]; } } @@ -496,23 +497,23 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot(&format!("tentacle{i}"), angle); } } - S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()), + S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).msin()), // TadpoleModel: a stronger tail swing out of water. S::Tadpole => { let a = if m.fluids.in_water { 1.0 } else { 1.5 }; - p.yrot("tail", -a * 0.25 * (0.3 * s.age).sin()) + p.yrot("tail", -a * 0.25 * (0.3 * s.age).msin()) } - S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()), + S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).msin()), 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()); + p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).msin()); } S::Pufferfish => { - let fin = 0.2 - 0.4 * (s.age * 0.2).sin(); + let fin = 0.2 - 0.4 * (s.age * 0.2).msin(); if p.has("right_blue_fin") { p.zrot("right_blue_fin", -fin); p.zrot("left_blue_fin", fin); @@ -526,9 +527,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { 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()); + p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).mcos(); + p.xrot("tail", -0.1 * (s.age * 0.3).mcos()); + p.xrot("tail_fin", -0.2 * (s.age * 0.3).mcos()); } } _ => {} @@ -565,7 +566,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { (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()); + * glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).msin()).to_radians()); if !m.fluids.in_water { let off = if m.species() == S::Cod { glam::Vec3::new(0.1, 0.1, -0.1) @@ -577,7 +578,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option { 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_translation(glam::Vec3::new(0.0, (age * 0.05).mcos() * 0.08, 0.0)) * glam::Mat4::from_rotation_y((180.0 - body).to_radians()), ), _ => None, diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs new file mode 100644 index 000000000..b6b232b8b --- /dev/null +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -0,0 +1,1044 @@ +//! `EntityModel.setupAnim` ports for the animals and monsters whose models +//! have no species file of their own (goat, polar bear, panda, llama, turtle, +//! strider, snow golem, silverfish, endermite, parrot, bee, bat, armadillo, +//! axolotl, frog, rabbit, fox). Each reads the render-state values vanilla's +//! renderer extracts, as plain structs so the differential harness can set +//! them directly; `from_mob` adapters fill them from what a `Mob` tracks. +use super::{ + Mob, Species, + anim::{Poses, State, quadruped}, + keyframes::{Animation, AnimationState}, +}; +use horizon_core::geometry::trig::Mth; +use std::{collections::HashMap, f64::consts::PI}; + +pub type Animations = HashMap; +const FPI: f32 = PI as f32; +/// `(float) (Math.PI / n)` and friends, evaluated in double like Java. +fn rad(v: f64) -> f32 { + v as f32 +} +fn lerp(a: f32, p: f32, q: f32) -> f32 { + p + a * (q - p) +} +/// `Mth.rotLerpRad`. +fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 { + let mut diff = to - from; + while diff < -FPI { + diff += rad(PI * 2.0); + } + while diff >= FPI { + diff -= rad(PI * 2.0); + } + from + a * diff +} +fn head_look(p: &mut Poses, s: &State) { + p.xrot("head", s.x_rot.to_radians()); + p.yrot("head", s.y_rot.to_radians()); +} +/// `KeyframeAnimation.apply(AnimationState, ageInTicks)`. +fn run(animations: &Animations, name: &str, state: &AnimationState, s: &State, p: &mut Poses) { + if let (Some(ms), Some(a)) = (state.millis(s.age), animations.get(name)) { + a.apply(ms, 1.0, p); + } +} +fn walk(animations: &Animations, name: &str, s: &State, factor: f32, scale: f32, p: &mut Poses) { + if let Some(a) = animations.get(name) { + a.apply_walk(s.pos, s.speed, factor, scale, p); + } +} +fn adds(p: &mut Poses, part: &str, i: usize, v: f32) { + p.get(part)[i] += v; +} + +// ---- goat ----------------------------------------------------------------- +#[derive(Clone, Copy, Debug)] +pub struct Goat { + pub left_horn: bool, + pub right_horn: bool, + pub ramming_x_head_rot: f32, +} +impl Goat { + pub fn from_mob(_m: &Mob) -> Self { + Self { + left_horn: true, + right_horn: true, + ramming_x_head_rot: 0.0, + } + } +} +/// `GoatModel` / `BabyGoatModel.setupAnim`. +pub fn goat(p: &mut Poses, s: &State, g: &Goat) { + quadruped(p, s); + p.visible("left_horn", g.left_horn); + p.visible("right_horn", g.right_horn); + if g.ramming_x_head_rot != 0.0 { + p.xrot("head", g.ramming_x_head_rot); + } + if s.baby && g.ramming_x_head_rot == 0.0 { + p.xrot("head", rad(PI / 8.0)); + } +} + +// ---- polar bear ----------------------------------------------------------- +/// `PolarBearModel.setupAnim`. +pub fn polar_bear(p: &mut Poses, s: &State, stand_scale: f32) { + quadruped(p, s); + let stand = stand_scale * stand_scale; + let age_scale = if s.baby { 0.5 } else { 1.0 }; + adds(p, "body", 3, -(stand * FPI * 0.35)); + adds(p, "body", 1, stand * age_scale * 2.0); + adds(p, "right_front_leg", 1, -(stand * age_scale * 20.0)); + adds(p, "right_front_leg", 2, stand * age_scale * 4.0); + adds(p, "right_front_leg", 3, -(stand * FPI * 0.45)); + let (y, z) = { + let r = p.get("right_front_leg"); + (r[1], r[2]) + }; + let l = p.get("left_front_leg"); + l[1] = y; + l[2] = z; + l[3] -= stand * FPI * 0.45; + adds(p, "head", 1, -(stand * 24.0)); + adds(p, "head", 2, stand * 13.0); + adds(p, "head", 3, stand * FPI * 0.15); +} + +// ---- panda ---------------------------------------------------------------- +#[derive(Clone, Copy, Debug, Default)] +pub struct Panda { + pub unhappy: bool, + pub sneezing: bool, + pub sneeze_time: i32, + pub eating: bool, + pub scared: bool, + pub sit_amount: f32, + pub lie_on_back_amount: f32, + pub roll_amount: f32, +} +/// `PandaModel` / `BabyPandaModel.setupAnim`. +pub fn panda(p: &mut Poses, s: &State, st: &Panda) { + quadruped(p, s); + let age = s.age; + if st.unhappy { + p.yrot("head", 0.35 * (0.6 * age).msin()); + p.zrot("head", 0.35 * (0.6 * age).msin()); + p.xrot("right_front_leg", -0.75 * (0.3 * age).msin()); + p.xrot("left_front_leg", 0.75 * (0.3 * age).msin()); + } else { + p.zrot("head", 0.0); + } + if st.sneezing { + if st.sneeze_time < 15 { + p.xrot("head", rad(-PI / 4.0) * st.sneeze_time as f32 / 14.0); + } else if st.sneeze_time < 20 { + let pos = ((st.sneeze_time - 15) / 5) as f32; + p.xrot("head", rad(-PI / 4.0) + rad(PI / 4.0) * pos); + } + } + if st.sit_amount > 0.0 { + let a = st.sit_amount; + if s.baby { + let x = rot_lerp_rad(a, p.get("body")[3], rad(PI / 18.0)); + p.xrot("body", x); + let v = lerp(a, p.get("body")[2], -1.5); + p.get("body")[2] = v; + let v = lerp(a, p.get("head")[2], -11.5); + p.get("head")[2] = v; + let v = lerp(a, p.get("head")[1], 17.5); + p.get("head")[1] = v; + for (part, z) in [ + ("right_front_leg", -5.0), + ("left_front_leg", -5.0), + ("right_hind_leg", 3.0), + ("left_hind_leg", 3.0), + ] { + let v = lerp(a, p.get(part)[2], z); + p.get(part)[2] = v; + } + } else { + let x = rot_lerp_rad(a, p.get("body")[3], 1.740_796_3); + p.xrot("body", x); + let x = rot_lerp_rad(a, p.get("head")[3], rad(PI / 2.0)); + p.xrot("head", x); + } + p.zrot("right_front_leg", -0.270_796_42); + p.zrot("left_front_leg", 0.270_796_42); + p.zrot("right_hind_leg", 0.570_796_4); + p.zrot("left_hind_leg", -0.570_796_4); + if st.eating { + p.xrot("head", rad(PI / 2.0) + 0.2 * (age * 0.6).msin()); + p.xrot("right_front_leg", -0.4 - 0.2 * (age * 0.6).msin()); + p.xrot("left_front_leg", -0.4 - 0.2 * (age * 0.6).msin()); + } + if st.scared { + p.xrot("head", 2.170_796_4); + p.xrot("right_front_leg", -0.9); + p.xrot("left_front_leg", -0.9); + } + } else { + for leg in [ + "right_hind_leg", + "left_hind_leg", + "right_front_leg", + "left_front_leg", + ] { + p.zrot(leg, 0.0); + } + } + if st.lie_on_back_amount > 0.0 { + p.xrot("right_hind_leg", -0.6 * (age * 0.15).msin()); + p.xrot("left_hind_leg", 0.6 * (age * 0.15).msin()); + p.xrot("right_front_leg", 0.3 * (age * 0.25).msin()); + p.xrot("left_front_leg", -0.3 * (age * 0.25).msin()); + let x = rot_lerp_rad(st.lie_on_back_amount, p.get("head")[3], rad(PI / 2.0)); + p.xrot("head", x); + } + if st.roll_amount > 0.0 { + let x = rot_lerp_rad(st.roll_amount, p.get("head")[3], 2.056_194_5); + p.xrot("head", x); + p.xrot("right_hind_leg", -0.5 * (age * 0.5).msin()); + p.xrot("left_hind_leg", 0.5 * (age * 0.5).msin()); + p.xrot("right_front_leg", 0.5 * (age * 0.5).msin()); + p.xrot("left_front_leg", -0.5 * (age * 0.5).msin()); + } +} + +// ---- llama ---------------------------------------------------------------- +/// `LlamaModel.setupAnim`. +pub fn llama(p: &mut Poses, s: &State, has_chest: bool) { + quadruped(p, s); + p.visible("right_chest", has_chest); + p.visible("left_chest", has_chest); +} + +// ---- turtle --------------------------------------------------------------- +#[derive(Clone, Copy, Debug, Default)] +pub struct Turtle { + pub on_land: bool, + pub laying_egg: bool, + pub has_egg: bool, +} +/// `TurtleModel` / `AdultTurtleModel.setupAnim`. +pub fn turtle(p: &mut Poses, s: &State, t: &Turtle) { + quadruped(p, s); + let (pos, speed) = (s.pos, s.speed); + if t.on_land { + let lay = if t.laying_egg { 4.0 } else { 1.0 }; + let amp = if t.laying_egg { 2.0 } else { 1.0 }; + let swing = pos * 5.0; + let front = (lay * swing).mcos(); + let hind = swing.mcos(); + p.yrot("right_front_leg", -front * 8.0 * speed * amp); + p.yrot("left_front_leg", front * 8.0 * speed * amp); + p.yrot("right_hind_leg", -hind * 3.0 * speed); + p.yrot("left_hind_leg", hind * 3.0 * speed); + } else { + let scale = 0.5 * speed; + let swing = (pos * 0.6662 * 0.6).mcos() * scale; + p.xrot("right_hind_leg", swing); + p.xrot("left_hind_leg", -swing); + p.zrot("right_front_leg", -swing); + p.zrot("left_front_leg", swing); + } + if !s.baby { + p.visible("egg_belly", t.has_egg); + if t.has_egg { + adds(p, "root", 1, -1.0); + } + } +} + +// ---- strider -------------------------------------------------------------- +/// `StriderModel.animateBristle` with the rotation axis the model adds to. +fn bristles(p: &mut Poses, age: f32, flow: f32, parts: [&str; 3], axis: usize) { + adds(p, parts[0], axis, flow * 0.6); + adds(p, parts[1], axis, flow * 1.2); + adds(p, parts[2], axis, flow * 1.3); + adds(p, parts[0], axis, 0.1 * (age * 0.4).msin()); + adds(p, parts[1], axis, 0.1 * (age * 0.2).msin()); + adds(p, parts[2], axis, 0.05 * (age * -0.4).msin()); +} +/// `StriderModel` / `AdultStriderModel` / `BabyStriderModel.setupAnim`. +pub fn strider(p: &mut Poses, s: &State, ridden: bool) { + let pos = s.pos; + let speed = s.speed.min(0.25); + if !ridden { + p.xrot("body", s.x_rot.to_radians()); + p.yrot("body", s.y_rot.to_radians()); + } else { + p.xrot("body", 0.0); + p.yrot("body", 0.0); + } + p.zrot("body", 0.1 * (pos * 1.5).msin() * 4.0 * speed); + p.xrot("left_leg", (pos * 1.5 * 0.5).msin() * 2.0 * speed); + p.xrot("right_leg", (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed); + p.zrot( + "left_leg", + rad(PI / 18.0) * (pos * 1.5 * 0.5).mcos() * speed, + ); + p.zrot( + "right_leg", + rad(PI / 18.0) * (pos * 1.5 * 0.5 + FPI).mcos() * speed, + ); + let flow = (pos * 1.5 + FPI).mcos() * speed; + if !s.baby { + p.zrot("right_bottom_bristle", -1.221_730_5); + p.zrot("right_middle_bristle", -1.134_464); + p.zrot("right_top_bristle", -0.872_664_63); + p.zrot("left_top_bristle", 0.872_664_63); + p.zrot("left_middle_bristle", 1.134_464); + p.zrot("left_bottom_bristle", 1.221_730_5); + bristles( + p, + s.age, + flow, + [ + "right_top_bristle", + "right_middle_bristle", + "right_bottom_bristle", + ], + 5, + ); + bristles( + p, + s.age, + flow, + [ + "left_top_bristle", + "left_middle_bristle", + "left_bottom_bristle", + ], + 5, + ); + p.get("body")[1] = 2.0; + p.get("body")[1] -= 2.0 * (pos * 1.5).mcos() * 2.0 * speed; + p.get("left_leg")[1] = 8.0 + 2.0 * (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed; + p.get("right_leg")[1] = 8.0 + 2.0 * (pos * 1.5 * 0.5).msin() * 2.0 * speed; + } else { + p.get("body")[1] = 17.25; + p.get("body")[1] -= 1.0 * (pos * 1.5).mcos() * 2.0 * speed; + p.get("left_leg")[1] = 20.0 + 2.0 * (pos * 1.5 * 0.5 + FPI).msin() * 2.0 * speed; + p.get("right_leg")[1] = 20.0 + 2.0 * (pos * 1.5 * 0.5).msin() * 2.0 * speed; + bristles(p, s.age, flow, ["bristle2", "bristle1", "bristle0"], 3); + } +} + +// ---- snow golem ----------------------------------------------------------- +/// `SnowGolemModel.setupAnim`. +pub fn snow_golem(p: &mut Poses, s: &State) { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + p.xrot("head", s.x_rot * rad(PI / 180.0)); + let y = s.y_rot * rad(PI / 180.0) * 0.25; + p.yrot("upper_body", y); + let (sin, cos) = (y.msin(), y.mcos()); + p.yrot("left_arm", y); + p.yrot("right_arm", y + FPI); + p.get("left_arm")[0] = cos * 5.0; + p.get("left_arm")[2] = -sin * 5.0; + p.get("right_arm")[0] = -cos * 5.0; + p.get("right_arm")[2] = sin * 5.0; +} + +// ---- silverfish and endermite --------------------------------------------- +/// `SilverfishModel.setupAnim`. +pub fn silverfish(p: &mut Poses, s: &State) { + let mut ys = [0.0f32; 7]; + let mut xs = [0.0f32; 7]; + for i in 0..7usize { + let d = (i as i32 - 2).abs(); + let phase = s.age * 0.9 + i as f32 * 0.15 * FPI; + ys[i] = phase.mcos() * FPI * 0.05 * (1 + d) as f32; + xs[i] = phase.msin() * FPI * 0.2 * d as f32; + let name = format!("segment{i}"); + p.yrot(&name, ys[i]); + p.get(&name)[0] = xs[i]; + } + p.yrot("layer0", ys[2]); + p.yrot("layer1", ys[4]); + p.get("layer1")[0] = xs[4]; + p.yrot("layer2", ys[1]); + p.get("layer2")[0] = xs[1]; +} +/// `EndermiteModel.setupAnim`. +pub fn endermite(p: &mut Poses, s: &State) { + for i in 0..4usize { + let d = (i as i32 - 2).abs(); + let phase = s.age * 0.9 + i as f32 * 0.15 * FPI; + let name = format!("segment{i}"); + p.yrot(&name, phase.mcos() * FPI * 0.01 * (1 + d) as f32); + p.get(&name)[0] = phase.msin() * FPI * 0.1 * d as f32; + } +} + +// ---- parrot --------------------------------------------------------------- +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ParrotPose { + #[default] + Standing, + Flying, + OnShoulder, + Sitting, + Party, +} +/// `ParrotModel.setupAnim`. +pub fn parrot(p: &mut Poses, s: &State, pose: ParrotPose, flap_angle: f32) { + use ParrotPose as P; + match pose { + P::Flying => { + adds(p, "left_leg", 3, rad(PI * 2.0 / 9.0)); + adds(p, "right_leg", 3, rad(PI * 2.0 / 9.0)); + } + P::Sitting => { + adds(p, "head", 1, 1.9); + adds(p, "tail", 3, rad(PI / 6.0)); + adds(p, "tail", 1, 1.9); + adds(p, "body", 1, 1.9); + p.zrot("left_wing", -0.0873); + adds(p, "left_wing", 1, 1.9); + p.zrot("right_wing", 0.0873); + adds(p, "right_wing", 1, 1.9); + adds(p, "left_leg", 1, 1.9); + adds(p, "right_leg", 1, 1.9); + adds(p, "left_leg", 3, rad(PI / 2.0)); + adds(p, "right_leg", 3, rad(PI / 2.0)); + } + P::Party => { + p.zrot("left_leg", rad(-PI / 9.0)); + p.zrot("right_leg", rad(PI / 9.0)); + } + _ => {} + } + head_look(p, s); + let flutter = |p: &mut Poses| { + let bob = flap_angle * 0.3; + adds(p, "head", 1, bob); + adds(p, "tail", 3, (s.pos * 0.6662).mcos() * 0.3 * s.speed); + adds(p, "tail", 1, bob); + adds(p, "body", 1, bob); + p.zrot("left_wing", -0.0873 - flap_angle); + adds(p, "left_wing", 1, bob); + p.zrot("right_wing", 0.0873 + flap_angle); + adds(p, "right_wing", 1, bob); + adds(p, "left_leg", 1, bob); + adds(p, "right_leg", 1, bob); + }; + match pose { + P::Standing => { + adds(p, "left_leg", 3, (s.pos * 0.6662).mcos() * 1.4 * s.speed); + adds( + p, + "right_leg", + 3, + (s.pos * 0.6662 + FPI).mcos() * 1.4 * s.speed, + ); + flutter(p); + } + P::Flying | P::OnShoulder => flutter(p), + P::Sitting => {} + P::Party => { + let (x, y) = (s.age.mcos(), s.age.msin()); + adds(p, "head", 0, x); + adds(p, "head", 1, y); + p.xrot("head", 0.0); + p.yrot("head", 0.0); + p.zrot("head", s.age.msin() * 0.4); + adds(p, "body", 0, x); + adds(p, "body", 1, y); + p.zrot("left_wing", -0.0873 - flap_angle); + adds(p, "left_wing", 0, x); + adds(p, "left_wing", 1, y); + p.zrot("right_wing", 0.0873 + flap_angle); + adds(p, "right_wing", 0, x); + adds(p, "right_wing", 1, y); + adds(p, "tail", 0, x); + adds(p, "tail", 1, y); + } + } +} + +// ---- bee ------------------------------------------------------------------ +#[derive(Clone, Copy, Debug)] +pub struct Bee { + pub has_stinger: bool, + pub on_ground: bool, + pub angry: bool, + pub roll_amount: f32, +} +/// `BeeModel` / `AdultBeeModel.setupAnim`. +pub fn bee(p: &mut Poses, s: &State, b: &Bee) { + p.visible("stinger", b.has_stinger); + let age = s.age; + if !b.on_ground { + let speed = age * 120.32113 * rad(PI / 180.0); + p.yrot("right_wing", 0.0); + p.zrot("right_wing", speed.mcos() * FPI * 0.15); + let (x, y, z) = { + let r = p.get("right_wing"); + (r[3], r[4], r[5]) + }; + p.xrot("left_wing", x); + p.yrot("left_wing", y); + p.zrot("left_wing", -z); + p.xrot("front_legs", rad(PI / 4.0)); + p.xrot("middle_legs", rad(PI / 4.0)); + p.xrot("back_legs", rad(PI / 4.0)); + } + if !b.angry && !b.on_ground { + let speed = (age * 0.18).mcos(); + p.xrot("bone", 0.1 + speed * FPI * 0.025); + adds(p, "bone", 1, -((age * 0.18).mcos() * 0.9)); + p.xrot("front_legs", -speed * FPI * 0.1 + rad(PI / 8.0)); + p.xrot("back_legs", -speed * FPI * 0.05 + rad(PI / 4.0)); + if !s.baby { + p.xrot("left_antenna", speed * FPI * 0.03); + p.xrot("right_antenna", speed * FPI * 0.03); + } + } + if b.roll_amount > 0.0 { + let x = rot_lerp_rad(b.roll_amount, p.get("bone")[3], 3.091_592_8); + p.xrot("bone", x); + } +} + +// ---- bat ------------------------------------------------------------------ +/// `BatModel.setupAnim`. +pub fn bat( + p: &mut Poses, + s: &State, + resting: bool, + fly: &AnimationState, + rest: &AnimationState, + a: &Animations, +) { + if resting { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + } + run(a, "BatAnimation.BAT_FLYING", fly, s, p); + run(a, "BatAnimation.BAT_RESTING", rest, s, p); +} + +// ---- armadillo ------------------------------------------------------------ +#[derive(Clone, Debug, Default)] +pub struct Armadillo { + pub hiding_in_shell: bool, + pub roll_out: AnimationState, + pub roll_up: AnimationState, + pub peek: AnimationState, +} +/// `ArmadilloModel.setupAnim`. +pub fn armadillo(p: &mut Poses, s: &State, st: &Armadillo, a: &Animations) { + if st.hiding_in_shell { + p.skip_draw("body"); + p.visible("left_hind_leg", false); + p.visible("right_hind_leg", false); + p.visible("tail", false); + } else { + p.visible("cube", false); + p.xrot("head", s.x_rot.clamp(-22.5, 25.0) * rad(PI / 180.0)); + p.yrot("head", s.y_rot.clamp(-32.5, 32.5) * rad(PI / 180.0)); + let prefix = if s.baby { + "BabyArmadilloAnimation.ARMADILLO_BABY_" + } else { + "ArmadilloAnimation.ARMADILLO_" + }; + walk(a, &format!("{prefix}WALK"), s, 16.5, 2.5, p); + } + let prefix = if s.baby { + "BabyArmadilloAnimation.ARMADILLO_BABY_" + } else { + "ArmadilloAnimation.ARMADILLO_" + }; + run(a, &format!("{prefix}ROLL_OUT"), &st.roll_out, s, p); + run(a, &format!("{prefix}ROLL_UP"), &st.roll_up, s, p); + run(a, &format!("{prefix}PEEK"), &st.peek, s, p); +} + +// ---- axolotl -------------------------------------------------------------- +#[derive(Clone, Debug, Default)] +pub struct Axolotl { + pub playing_dead: f32, + pub in_water: f32, + pub on_ground: f32, + pub moving: f32, + pub swim: AnimationState, + pub walk: AnimationState, + pub idle_on_ground: AnimationState, + pub idle_underwater_on_ground: AnimationState, + pub idle_underwater: AnimationState, + pub play_dead: AnimationState, +} +/// `AdultAxolotlModel` / `BabyAxolotlModel.setupAnim`. +pub fn axolotl(p: &mut Poses, s: &State, x: &Axolotl, a: &Animations) { + if s.baby { + if x.walk.started.is_some() { + walk( + a, + "BabyAxolotlAnimation.AXOLOTL_WALK_FLOOR", + s, + 15.0, + 30.0, + p, + ); + } + run(a, "BabyAxolotlAnimation.BABY_AXOLOTL_SWIM", &x.swim, s, p); + run( + a, + "BabyAxolotlAnimation.WALK_FLOOR_UNDERWATER", + // The model reads `walkAnimationState` again here, not the + // underwater state the renderer also copies. + &x.walk, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.BABY_AXOLOTL_IDLE_FLOOR", + &x.idle_on_ground, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.IDLE_UNDERWATER", + &x.idle_underwater, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.IDLE_FLOOR_UNDERWATER", + &x.idle_underwater_on_ground, + s, + p, + ); + run( + a, + "BabyAxolotlAnimation.BABY_AXOLOTL_PLAY_DEAD", + &x.play_dead, + s, + p, + ); + return; + } + let not_moving = 1.0 - x.moving; + let mirrored = 1.0 - x.on_ground.min(x.moving); + adds(p, "body", 4, s.y_rot * rad(PI / 180.0)); + axolotl_swim(p, s.age, s.x_rot, x.moving.min(x.in_water)); + axolotl_hover(p, s.age, not_moving.min(x.in_water)); + axolotl_crawl(p, s.age, x.moving.min(x.on_ground)); + axolotl_lay(p, s.age, not_moving.min(x.on_ground)); + axolotl_dead(p, x.playing_dead); + if mirrored > 1.0e-5 { + let l_hind = [ + p.get("left_hind_leg")[3], + p.get("left_hind_leg")[4], + p.get("left_hind_leg")[5], + ]; + let l_front = [ + p.get("left_front_leg")[3], + p.get("left_front_leg")[4], + p.get("left_front_leg")[5], + ]; + for (part, l) in [("right_hind_leg", l_hind), ("right_front_leg", l_front)] { + let r = p.get(part); + r[3] += l[0] * mirrored; + r[4] += -l[1] * mirrored; + r[5] += -l[2] * mirrored; + } + } +} +fn axolotl_lay(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.09; + let sine = sway.msin(); + let cosine = sway.mcos(); + let movement = sine * sine - 2.0 * sine; + let movement2 = cosine * cosine - 3.0 * sine; + adds(p, "head", 3, -0.09 * movement * factor); + adds(p, "head", 5, -0.2 * factor); + adds(p, "tail", 4, (-0.1 + 0.1 * movement) * factor); + let gill = (0.6 + 0.05 * movement2) * factor; + adds(p, "top_gills", 3, gill); + adds(p, "left_gills", 4, -gill); + adds(p, "right_gills", 4, gill); + adds(p, "left_hind_leg", 3, 1.1 * factor); + adds(p, "left_hind_leg", 4, 1.0 * factor); + adds(p, "left_front_leg", 3, 0.8 * factor); + adds(p, "left_front_leg", 4, 2.3 * factor); + adds(p, "left_front_leg", 5, -0.5 * factor); +} +fn axolotl_crawl(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.11; + let cosine = sway.mcos(); + let hind_y = (cosine * cosine - 2.0 * cosine) / 5.0; + let front_y = 0.7 * cosine; + let head_tail = 0.09 * cosine * factor; + adds(p, "head", 4, head_tail); + adds(p, "tail", 4, head_tail); + let gill = (0.6 - 0.08 * (cosine * cosine + 2.0 * sway.msin())) * factor; + adds(p, "top_gills", 3, gill); + adds(p, "left_gills", 4, -gill); + adds(p, "right_gills", 4, gill); + let hind_x = 0.942_477_9 * factor; + let front_x = 1.099_557_4 * factor; + adds(p, "left_hind_leg", 3, hind_x); + adds(p, "left_hind_leg", 4, (1.5 - hind_y) * factor); + adds(p, "left_hind_leg", 5, -0.1 * factor); + adds(p, "left_front_leg", 3, front_x); + adds(p, "left_front_leg", 4, (rad(PI / 2.0) - front_y) * factor); + adds(p, "right_hind_leg", 3, hind_x); + adds(p, "right_hind_leg", 4, (-1.0 - hind_y) * factor); + adds(p, "right_front_leg", 3, front_x); + adds(p, "right_front_leg", 4, (rad(-PI / 2.0) - front_y) * factor); +} +fn axolotl_hover(p: &mut Poses, age: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.075; + let cosine = sway.mcos(); + let sine = sway.msin() * 0.15; + let body_x = (-0.15 + 0.075 * cosine) * factor; + adds(p, "body", 3, body_x); + adds(p, "body", 1, -(sine * factor)); + adds(p, "head", 3, -body_x); + adds(p, "top_gills", 3, 0.2 * cosine * factor); + let gill_y = (-0.3 * cosine - 0.19) * factor; + adds(p, "left_gills", 4, gill_y); + adds(p, "right_gills", 4, -gill_y); + adds( + p, + "left_hind_leg", + 3, + (rad(PI * 3.0 / 4.0) - cosine * 0.11) * factor, + ); + adds(p, "left_hind_leg", 4, 0.471_238_94 * factor); + adds(p, "left_hind_leg", 5, 1.727_876_1 * factor); + adds( + p, + "left_front_leg", + 3, + (rad(PI / 4.0) - cosine * 0.2) * factor, + ); + adds(p, "left_front_leg", 4, 2.042_035 * factor); + adds(p, "tail", 4, 0.5 * cosine * factor); +} +fn axolotl_swim(p: &mut Poses, age: f32, x_rot: f32, factor: f32) { + if factor <= 1.0e-5 { + return; + } + let sway = age * 0.33; + let sine = sway.msin(); + let cosine = sway.mcos(); + let body_sway = 0.13 * sine; + adds(p, "body", 3, (x_rot * rad(PI / 180.0) + body_sway) * factor); + adds(p, "head", 3, -(body_sway * 1.8 * factor)); + adds(p, "body", 1, -(0.45 * cosine * factor)); + adds(p, "top_gills", 3, (-0.5 * sine - 0.8) * factor); + let gill_y = (0.3 * sine + 0.9) * factor; + adds(p, "left_gills", 4, gill_y); + adds(p, "right_gills", 4, -gill_y); + let tail = p.get("tail")[4] + 0.3 * (sway * 0.9).mcos() * factor; + p.yrot("tail", tail); + adds(p, "left_hind_leg", 3, 1.884_955_8 * factor); + adds(p, "left_hind_leg", 4, -0.4 * sine * factor); + adds(p, "left_hind_leg", 5, rad(PI / 2.0) * factor); + adds(p, "left_front_leg", 3, 1.884_955_8 * factor); + adds(p, "left_front_leg", 4, (-0.2 * cosine - 0.1) * factor); + adds(p, "left_front_leg", 5, rad(PI / 2.0) * factor); +} +fn axolotl_dead(p: &mut Poses, factor: f32) { + if factor <= 1.0e-5 { + return; + } + adds(p, "left_hind_leg", 3, 1.413_716_7 * factor); + adds(p, "left_hind_leg", 4, 1.099_557_4 * factor); + adds(p, "left_hind_leg", 5, rad(PI / 4.0) * factor); + adds(p, "left_front_leg", 3, rad(PI / 4.0) * factor); + adds(p, "left_front_leg", 4, 2.042_035 * factor); + adds(p, "body", 3, -0.15 * factor); + adds(p, "body", 5, 0.35 * factor); +} + +// ---- frog ----------------------------------------------------------------- +#[derive(Clone, Debug, Default)] +pub struct Frog { + pub swimming: bool, + pub jump: AnimationState, + pub croak: AnimationState, + pub tongue: AnimationState, + pub swim_idle: AnimationState, +} +/// `FrogModel.setupAnim`. +pub fn frog(p: &mut Poses, s: &State, f: &Frog, a: &Animations) { + run(a, "FrogAnimation.FROG_JUMP", &f.jump, s, p); + run(a, "FrogAnimation.FROG_CROAK", &f.croak, s, p); + run(a, "FrogAnimation.FROG_TONGUE", &f.tongue, s, p); + if f.swimming { + walk(a, "FrogAnimation.FROG_SWIM", s, 1.0, 2.5, p); + } else { + walk(a, "FrogAnimation.FROG_WALK", s, 1.5, 2.5, p); + } + run(a, "FrogAnimation.FROG_IDLE_WATER", &f.swim_idle, s, p); + p.visible("croaking_body", f.croak.started.is_some()); +} + +// ---- rabbit --------------------------------------------------------------- +/// `RabbitModel.setupAnim`. +pub fn rabbit( + p: &mut Poses, + s: &State, + hop: &AnimationState, + tilt: &AnimationState, + a: &Animations, +) { + if tilt.started.is_none() { + p.yrot("head", s.y_rot * rad(PI / 180.0)); + p.xrot("head", s.x_rot * rad(PI / 180.0)); + } + let prefix = if s.baby { + "BabyRabbitAnimation." + } else { + "RabbitAnimation." + }; + run(a, &format!("{prefix}HOP"), hop, s, p); + run(a, &format!("{prefix}IDLE_HEAD_TILT"), tilt, s, p); +} + +// ---- fox ------------------------------------------------------------------ +#[derive(Clone, Copy, Debug, Default)] +pub struct Fox { + pub crouching: bool, + pub sleeping: bool, + pub sitting: bool, + pub pouncing: bool, + pub faceplanted: bool, + pub head_roll_angle: f32, + pub crouch_amount: f32, + /// `FoxModel.legMotionPos` after this frame's `+= 0.67`. + pub leg_motion_pos: f32, +} +/// `FoxModel` / `AdultFoxModel` / `BabyFoxModel.setupAnim`. +pub fn fox(p: &mut Poses, s: &State, f: &Fox, a: &Animations) { + let baby = s.baby; + let age_scale = if baby { 0.5 } else { 1.0 }; + // setWalkingPose + p.zrot("head", f.head_roll_angle); + if baby { + walk(a, "FoxBabyAnimation.FOX_BABY_WALK", s, 1.0, 2.5, p); + } else { + let (pos, speed) = (s.pos, s.speed); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed); + p.xrot("left_hind_leg", (pos * 0.6662 + FPI).mcos() * 1.4 * speed); + p.xrot("right_front_leg", (pos * 0.6662 + FPI).mcos() * 1.4 * speed); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed); + } + if f.crouching { + // setCrouchingPose + adds(p, "body", 3, 0.104_719_76); + adds(p, "head", 1, f.crouch_amount * age_scale); + let wiggle = s.age.mcos() * 0.05; + p.yrot("body", wiggle); + p.zrot("right_hind_leg", wiggle); + p.zrot("left_hind_leg", wiggle); + p.zrot("right_front_leg", wiggle / 2.0); + p.zrot("left_front_leg", wiggle / 2.0); + if baby { + adds(p, "body", 1, f.crouch_amount / 6.0); + } else { + adds(p, "body", 1, f.crouch_amount); + } + } else if f.sleeping { + // setSleepingPose + for leg in [ + "right_hind_leg", + "left_hind_leg", + "right_front_leg", + "left_front_leg", + ] { + p.visible(leg, false); + } + if baby { + p.zrot("body", rad(-PI / 2.0)); + p.xrot("body", rad(-PI / 18.0)); + adds(p, "body", 1, 1.5); + adds(p, "body", 2, -1.5); + adds(p, "body", 0, -1.5); + p.xrot("tail", rad(-PI * 5.0 / 6.0)); + p.xrot("tail", -2.181_661_6); + adds(p, "tail", 0, -0.7); + adds(p, "tail", 2, 0.6); + adds(p, "tail", 1, 0.9); + adds(p, "head", 0, -2.0); + adds(p, "head", 1, 2.8); + adds(p, "head", 2, -4.0); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", 0.0); + } else { + p.zrot("body", rad(-PI / 2.0)); + adds(p, "body", 1, 5.0); + p.xrot("tail", rad(-PI * 5.0 / 6.0)); + adds(p, "head", 0, 2.0); + adds(p, "head", 1, 2.99); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", 0.0); + } + } else if f.sitting { + // setSittingPose + p.xrot("head", 0.0); + p.yrot("head", 0.0); + if baby { + p.xrot("body", -0.959_931); + adds(p, "body", 2, -(4.5 * age_scale)); + adds(p, "body", 1, 3.0 * age_scale); + adds(p, "tail", 1, -0.6); + adds(p, "tail", 2, -(2.0 * age_scale)); + p.xrot("tail", 0.959_931_14); + adds(p, "head", 1, -0.75); + adds(p, "head", 2, 0.0); + p.xrot("right_front_leg", rad(-PI / 12.0)); + p.xrot("left_front_leg", rad(-PI / 12.0)); + adds(p, "right_front_leg", 2, -1.5); + adds(p, "left_front_leg", 2, -1.5); + adds(p, "right_front_leg", 0, 0.01); + adds(p, "left_front_leg", 0, -0.01); + adds(p, "right_hind_leg", 2, -3.75); + adds(p, "left_hind_leg", 2, -3.75); + adds(p, "right_hind_leg", 0, 0.01); + adds(p, "left_hind_leg", 0, -0.01); + } else { + p.xrot("body", rad(PI / 6.0)); + adds(p, "body", 1, -7.0); + adds(p, "body", 2, 3.0); + p.xrot("tail", rad(PI / 4.0)); + adds(p, "head", 1, -6.5); + adds(p, "head", 2, 2.75); + p.xrot("right_front_leg", rad(-PI / 12.0)); + p.xrot("left_front_leg", rad(-PI / 12.0)); + p.xrot("right_hind_leg", rad(-PI * 5.0 / 12.0)); + adds(p, "right_hind_leg", 1, 4.0); + adds(p, "right_hind_leg", 2, -0.25); + p.xrot("left_hind_leg", rad(-PI * 5.0 / 12.0)); + adds(p, "left_hind_leg", 1, 4.0); + adds(p, "left_hind_leg", 2, -0.25); + adds(p, "tail", 2, -1.0); + } + } + if f.pouncing && !baby { + let crouch = f.crouch_amount / 2.0; + adds(p, "body", 1, -crouch); + adds(p, "head", 1, -crouch); + } + if !f.sleeping && !f.faceplanted && !f.crouching { + p.xrot("head", s.x_rot * rad(PI / 180.0)); + p.yrot("head", s.y_rot * rad(PI / 180.0)); + } + if f.sleeping { + p.xrot("head", 0.0); + p.yrot("head", rad(-PI * 2.0 / 3.0)); + p.zrot("head", (s.age * 0.027).mcos() / 22.0); + } + if f.faceplanted { + let m = f.leg_motion_pos; + p.xrot("right_hind_leg", (m * 0.4662).mcos() * 0.1); + p.xrot("left_hind_leg", (m * 0.4662 + FPI).mcos() * 0.1); + p.xrot("right_front_leg", (m * 0.4662 + FPI).mcos() * 0.1); + p.xrot("left_front_leg", (m * 0.4662).mcos() * 0.1); + } +} + +// ---- adapters --------------------------------------------------------------- +/// Dispatch for the species ported here; `false` when `m` is not one of them. +pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { + let st = &m.anim.states; + match m.species() { + Species::Goat => goat(p, s, &Goat::from_mob(m)), + Species::PolarBear => polar_bear(p, s, 0.0), + Species::Panda => panda(p, s, &Panda::default()), + Species::Llama | Species::TraderLlama => { + llama(p, s, m.extra.chested && !s.baby); + } + Species::Turtle => turtle( + p, + s, + &Turtle { + on_land: !m.fluids.in_water && m.on_ground, + laying_egg: false, + has_egg: false, + }, + ), + Species::Strider => strider(p, s, m.rider.is_some()), + Species::SnowGolem => snow_golem(p, s), + Species::Silverfish => silverfish(p, s), + Species::Endermite => endermite(p, s), + Species::Parrot => { + let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; + let speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; + let pose = if m.extra.sitting { + ParrotPose::Sitting + } else if !m.on_ground && !m.fluids.in_water { + ParrotPose::Flying + } else { + ParrotPose::Standing + }; + parrot(p, s, pose, (flap.msin() + 1.0) * speed); + } + Species::Bee => bee( + p, + s, + &Bee { + has_stinger: true, + on_ground: m.on_ground, + angry: m.extra.anger > 0, + roll_amount: 0.0, + }, + ), + Species::Bat => bat(p, s, m.extra.flag, &st[0], &st[1], a), + Species::Armadillo => armadillo( + p, + s, + &Armadillo { + hiding_in_shell: false, + roll_out: st[0], + roll_up: st[1], + peek: st[2], + }, + a, + ), + Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m), a), + Species::Frog => frog( + p, + s, + &Frog { + swimming: m.fluids.in_water, + jump: st[0], + croak: st[1], + tongue: st[2], + swim_idle: st[3], + }, + a, + ), + Species::Rabbit => rabbit(p, s, &st[0], &st[1], a), + Species::Fox => fox(p, s, &Fox::default(), a), + _ => return false, + } + true +} +impl Axolotl { + pub fn from_mob(m: &Mob) -> Self { + let in_water = m.fluids.in_water; + Self { + in_water: if in_water { 1.0 } else { 0.0 }, + on_ground: if m.on_ground { 1.0 } else { 0.0 }, + walk: m.anim.states[0], + swim: m.anim.states[1], + ..Self::default() + } + } +} diff --git a/crates/horizon-client/src/mobs/camel.rs b/crates/horizon-client/src/mobs/camel.rs index 7d1c200b8..741d6a897 100644 --- a/crates/horizon-client/src/mobs/camel.rs +++ b/crates/horizon-client/src/mobs/camel.rs @@ -8,6 +8,7 @@ use super::{ Tempt, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::collections::HashMap; @@ -179,7 +180,7 @@ pub fn dash(m: &mut Mob, amount: f32, events: &mut Vec) { return; } let yaw = m.yaw.to_radians(); - let (dx, dz) = (f64::from(-yaw.sin()), f64::from(yaw.cos())); + let (dx, dz) = (f64::from(-yaw.msin()), f64::from(yaw.mcos())); let speed = m.movement_speed(); let a = f64::from(amount); m.velocity.x += dx * 22.2222 * a * speed; diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 490b207b0..dc9e391aa 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -68,6 +68,14 @@ impl MobData { data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); data } + /// Only the keyframe animation definitions of `mob-data.json`. + pub fn load_animations(root: &Path) -> HashMap { + fs::read(root.join("mob-data.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .map(|v| Self::from_json(&v).animations) + .unwrap_or_default() + } pub fn entity_has(&self, tag: &str, entity: &str) -> bool { self.entity_tags .get(tag) diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 33be2a248..dd56a85a0 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -9,6 +9,7 @@ use super::{ Tempt, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -24,9 +25,9 @@ pub const COLORS: [&str; 7] = [ pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackdots"]; // AnimState slots. -const EAT: usize = 0; -const STAND: usize = 1; -const MOUTH: usize = 2; +pub const EAT: usize = 0; +pub const STAND: usize = 1; +pub const MOUTH: usize = 2; /// What a rider asks of its mount this tick. #[derive(Clone, Copy, Debug, Default)] @@ -164,7 +165,7 @@ fn boost_factor(m: &mut Mob) -> f32 { m.extra.counter2 = 0; return 1.0; } - 1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).sin() + 1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).msin() } /// `AbstractHorse.MountPanicGoal`: only without a rider. #[derive(Clone, Debug)] @@ -360,7 +361,7 @@ pub fn ridden_step(m: &mut Mob) { let impulse = m.extra.vector[0] as f32 * r.jump; m.velocity.y = f64::from(impulse); if forward > 0.0 { - let (s, c) = (m.yaw.to_radians().sin(), m.yaw.to_radians().cos()); + let (s, c) = (m.yaw.to_radians().msin(), m.yaw.to_radians().mcos()); m.velocity.x += f64::from(-0.4 * s * r.jump); m.velocity.z += f64::from(0.4 * c * r.jump); } @@ -482,19 +483,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let mut head_x = s.x_rot.to_radians(); let (speed, pos) = (s.speed, s.pos); if speed > 0.2 { - head_x += (pos * 0.8).cos() * 0.15 * speed; + head_x += (pos * 0.8).mcos() * 0.15 * speed; } let eating = m.anim.lerp(EAT, s.partial); let standing = m.anim.lerp(STAND, s.partial); let istand = 1.0 - standing; let feeding = m.anim.lerp(MOUTH, s.partial); let in_water = if m.fluids.in_water { 0.2 } else { 1.0 }; - let leg1 = (in_water * pos * 0.6662 + PI).cos(); + let leg1 = (in_water * pos * 0.6662 + PI).mcos(); let leg_x = leg1 * 0.8 * speed; - let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.sin() * 0.05); + let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05); p.xrot( "head_parts", - standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.sin() * 0.05) + base, + standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.msin() * 0.05) + base, ); p.yrot( "head_parts", @@ -527,7 +528,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { rf[2] = z; } let stand = stand_angle * standing; - let bob = (s.age * 0.6 + PI).cos(); + let bob = (s.age * 0.6 + PI).mcos(); let rleg = (stand_x_off + bob) * standing + leg_x * istand; let lleg = (stand_x_off - bob) * standing - leg_x * istand; p.xrot("left_hind_leg", stand - leg1 * 0.5 * speed * istand); @@ -536,9 +537,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("right_front_leg", lleg); if baby && donkey { let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t; + // BabyDonkeyModel lerps the right leg from the left leg's new height. let y = lerp(standing, p.get("left_hind_leg")[1], -0.3); p.get("left_hind_leg")[1] = y; - p.get("right_hind_leg")[1] = y; + p.get("right_hind_leg")[1] = lerp(standing, y, -0.3); } let age = if baby { 0.5 } else { 1.0 }; p.xrot("tail", tail_off + PI / 6.0 + speed * 0.75); @@ -548,4 +550,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { t[2] += speed * 2.0 * age; } p.yrot("tail", 0.0); + if baby && donkey { + // BabyDonkeyModel overrides the state's pitch with -30 degrees and + // sets the head parts again. + let head_x = -30.0f32 * horizon_core::geometry::trig::DEG_TO_RAD; + let base = + (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05); + p.xrot( + "head_parts", + standing * (PI / 12.0 + head_x) + eating * (PI / 2.0 + s.age.msin() * 0.05) + base, + ); + } } diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 16d5dfa7b..3b773e001 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -12,15 +12,16 @@ use super::{ nav::NavKind, path::PathType, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; // Guardian state: `flag` an active beam target (DATA_ID_ATTACK_TARGET), // `flag2` moving (DATA_ID_MOVING), `counter2` the client attack time. // AnimState slots: tail animation, its speed, spikes animation. -const TAIL: usize = 0; +pub const TAIL: usize = 0; const TAIL_SPEED: usize = 1; -const SPIKES: usize = 2; +pub const SPIKES: usize = 2; const EYE_X: usize = 3; const EYE_Y: usize = 4; @@ -166,8 +167,8 @@ pub fn move_control(m: &mut Mob) { let t = f64::from(m.age as i32 + m.id as i32); let push = (t * 0.5).sin() * 0.05; let (cos, sin) = ( - f64::from(m.yaw.to_radians().cos()), - f64::from(m.yaw.to_radians().sin()), + f64::from(m.yaw.to_radians().mcos()), + f64::from(m.yaw.to_radians().msin()), ); let y_push = (t * 0.75).sin() * 0.05; m.velocity = m.velocity.add_vector(Vec3::new( @@ -277,7 +278,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; let yaw = m.head_yaw.to_radians(); let pitch = m.head_pitch.to_radians(); - let view = [-yaw.sin() * pitch.cos(), yaw.cos() * pitch.cos()]; + let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; let d = [m.position.x - look[0], m.position.z - look[2]]; let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); @@ -365,7 +366,7 @@ pub fn beam_geometry( 128u32.saturating_sub((cs * 64.0) as u32), ); let color = 0xFF00_0000 | (b.min(255) << 16) | (g.min(255) << 8) | r.min(255); - let at = |a: f32, radius: f32| (a.cos() * radius, a.sin() * radius); + let at = |a: f32, radius: f32| (a.mcos() * radius, a.msin() * radius); let quarter = std::f32::consts::FRAC_PI_4; let (wx, wz) = at(rot + PI, 0.2); let (ex, ez) = at(rot, 0.2); @@ -432,7 +433,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { 8.0, -8.0, 0.0, 0.0, -8.0, -8.0, 8.0, 8.0, 8.0, -8.0, 0.0, 0.0, ]; for i in 0..12 { - let offset = 1.0 + (s.age * 1.5 + i as f32).cos() * 0.01 - withdrawal; + let offset = 1.0 + (s.age * 1.5 + i as f32).mcos() * 0.01 - withdrawal; let part = p.get(&format!("spike{i}")); part[0] = X[i] * offset; part[1] = 16.0 + Y[i] * offset; @@ -442,7 +443,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { e[0] = m.anim.v[EYE_X]; e[1] = m.anim.v[EYE_Y]; let tail = m.anim.lerp(TAIL, s.partial); - p.yrot("tail0", tail.sin() * PI * 0.05); - p.yrot("tail1", tail.sin() * PI * 0.1); - p.yrot("tail2", tail.sin() * PI * 0.15); + p.yrot("tail0", tail.msin() * PI * 0.05); + p.yrot("tail1", tail.msin() * PI * 0.1); + p.yrot("tail2", tail.msin() * PI * 0.15); } diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 2351916ad..7af4a579a 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -9,6 +9,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; @@ -304,8 +305,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..5 { let a = angle + i as f32 * PI * 0.4; place( - x + f64::from(a.cos()) * 1.5, - z + f64::from(a.sin()) * 1.5, + x + f64::from(a.mcos()) * 1.5, + z + f64::from(a.msin()) * 1.5, a, 0, ); @@ -313,8 +314,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..8 { let a = angle + i as f32 * PI * 2.0 / 8.0 + PI * 2.0 / 5.0; place( - x + f64::from(a.cos()) * 2.5, - z + f64::from(a.sin()) * 2.5, + x + f64::from(a.mcos()) * 2.5, + z + f64::from(a.msin()) * 2.5, a, 3, ); @@ -323,8 +324,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) { for i in 0..16 { let reach = 1.25 * f64::from(i + 1); place( - x + f64::from(angle.cos()) * reach, - z + f64::from(angle.sin()) * reach, + x + f64::from(angle.mcos()) * reach, + z + f64::from(angle.msin()) * reach, angle, i, ); @@ -532,8 +533,9 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) { pitch, )); } -#[derive(Clone, Copy, PartialEq, Eq)] -enum ArmPose { +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ArmPose { + BowAndArrow, Spellcasting, Crossed, Celebrating, @@ -578,35 +580,53 @@ pub fn shows_item(m: &Mob) -> bool { m.species() != Species::Vindicator || m.ai.aggressive } fn hide(p: &mut Poses, part: &str) { - if p.has(part) { - let v = p.get(part); - v[6] = 0.0; - v[7] = 0.0; - v[8] = 0.0; - } + p.visible(part, false); } /// `IllagerModel.setupAnim`. pub fn anim(m: &Mob, s: &State, p: &mut Poses) { + anim_pose(m, s, p, arm_pose(m)); +} +/// `IllagerModel.setupAnim` for a given arm pose. +pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) { + // The hat is hidden by the model's constructor. + hide(p, "hat"); let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); p.yrot("head", hy); p.xrot("head", hx); let (pos, sp) = (s.pos, s.speed); - p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5); - p.yrot("right_arm", 0.0); - p.zrot("right_arm", 0.0); - p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5); - p.yrot("left_arm", 0.0); - p.zrot("left_arm", 0.0); - p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp * 0.5); - p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp * 0.5); - let pose = arm_pose(m); + if m.extra.passenger { + for arm in ["right_arm", "left_arm"] { + p.xrot(arm, -PI / 5.0); + p.yrot(arm, 0.0); + p.zrot(arm, 0.0); + } + p.xrot("right_leg", -1.413_716_7); + p.yrot("right_leg", PI / 10.0); + p.zrot("right_leg", 0.078_539_82); + p.xrot("left_leg", -1.413_716_7); + p.yrot("left_leg", -PI / 10.0); + p.zrot("left_leg", -0.078_539_82); + } else { + p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5); + p.yrot("right_arm", 0.0); + p.zrot("right_arm", 0.0); + p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5); + p.yrot("left_arm", 0.0); + p.zrot("left_arm", 0.0); + p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp * 0.5); + p.yrot("right_leg", 0.0); + p.zrot("right_leg", 0.0); + p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp * 0.5); + p.yrot("left_leg", 0.0); + p.zrot("left_leg", 0.0); + } match pose { ArmPose::Attacking => { if m.extra.main_hand.is_none() { // animateZombieArms + bobArms let swing = s.swing; - let a = (swing * PI).sin(); - let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let a = (swing * PI).msin(); + let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", -(0.1 - a * 0.6)); @@ -617,22 +637,25 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { } else { // swingWeaponDown (right-handed). let swing = s.swing; - let a2 = (swing * PI).sin(); - let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin(); + let a2 = (swing * PI).msin(); + let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); p.zrot("right_arm", 0.0); p.zrot("left_arm", 0.0); p.yrot("right_arm", PI / 20.0); p.yrot("left_arm", -PI / 20.0); p.xrot( "right_arm", - -1.884_955_8 + (s.age * 0.09).cos() * 0.15 + (a2 * 2.2 - a * 0.4), + -1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4), + ); + p.xrot( + "left_arm", + -0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4), ); - p.xrot("left_arm", (s.age * 0.19).cos() * 0.5); } let bob = |p: &mut Poses, part: &str, sign: f32| { let v = p.get(part); - v[5] += sign * ((s.age * 0.09).cos() * 0.05 + 0.05); - v[3] += sign * (s.age * 0.067).sin() * 0.05; + v[5] += sign * ((s.age * 0.09).mcos() * 0.05 + 0.05); + v[3] += sign * (s.age * 0.067).msin() * 0.05; }; bob(p, "right_arm", 1.0); bob(p, "left_arm", -1.0); @@ -659,7 +682,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let v = p.get(arm); v[2] = 0.0; v[0] = x; - v[3] = (s.age * 0.6662).cos() * 0.25; + v[3] = (s.age * 0.6662).mcos() * 0.25; v[4] = 0.0; v[5] = z_rot; } @@ -672,11 +695,18 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let v = p.get(arm); v[2] = 0.0; v[0] = x; - v[3] = (s.age * 0.6662).cos() * 0.05; + v[3] = (s.age * 0.6662).mcos() * 0.05; v[4] = 0.0; v[5] = z_rot; } } + ArmPose::BowAndArrow => { + p.yrot("right_arm", -0.1 + hy); + p.xrot("right_arm", -PI / 2.0 + hx); + p.xrot("left_arm", -0.942_477_9 + hx); + p.yrot("left_arm", hy - 0.4); + p.zrot("left_arm", PI / 2.0); + } ArmPose::Crossed | ArmPose::Neutral => {} } if pose == ArmPose::Crossed { diff --git a/crates/horizon-client/src/mobs/nether.rs b/crates/horizon-client/src/mobs/nether.rs index 984ee1b27..e95547f84 100644 --- a/crates/horizon-client/src/mobs/nether.rs +++ b/crates/horizon-client/src/mobs/nether.rs @@ -10,6 +10,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -181,25 +182,25 @@ pub fn blaze_anim(s: &State, p: &mut Poses) { let mut angle = age * PI * -0.1; for i in 0..4 { let part = p.get(&format!("part{i}")); - part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).cos(); - part[0] = angle.cos() * 9.0; - part[2] = angle.sin() * 9.0; + part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).mcos(); + part[0] = angle.mcos() * 9.0; + part[2] = angle.msin() * 9.0; angle += PI / 2.0; } angle = PI / 4.0 + age * PI * 0.03; for i in 4..8 { let part = p.get(&format!("part{i}")); - part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).cos(); - part[0] = angle.cos() * 7.0; - part[2] = angle.sin() * 7.0; + part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).mcos(); + part[0] = angle.mcos() * 7.0; + part[2] = angle.msin() * 7.0; angle += PI / 2.0; } angle = 0.471_238_94 + age * PI * -0.05; for i in 8..12 { let part = p.get(&format!("part{i}")); - part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).cos(); - part[0] = angle.cos() * 5.0; - part[2] = angle.sin() * 5.0; + part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).mcos(); + part[0] = angle.mcos() * 5.0; + part[2] = angle.msin() * 5.0; angle += PI / 2.0; } p.yrot("head", s.y_rot.to_radians()); @@ -365,7 +366,7 @@ impl Goal for GhastShoot { } if self.charge == 20 { let yaw = m.yaw.to_radians(); - let view = [-f64::from(yaw.sin()), f64::from(yaw.cos())]; + let view = [-f64::from(yaw.msin()), f64::from(yaw.mcos())]; let half = f64::from(m.height()) * 0.5; let ty = (t.bounds.min_position().y + t.bounds.max_position().y) * 0.5; let dir = [ @@ -404,7 +405,7 @@ pub fn ghast_anim(s: &State, p: &mut Poses) { for i in 0..9 { let name = format!("tentacle{i}"); if p.has(&name) { - p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).sin() + 0.4); + p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).msin() + 0.4); } } } diff --git a/crates/horizon-client/src/mobs/phantom.rs b/crates/horizon-client/src/mobs/phantom.rs index 33ce2c59d..a6be959ef 100644 --- a/crates/horizon-client/src/mobs/phantom.rs +++ b/crates/horizon-client/src/mobs/phantom.rs @@ -5,6 +5,7 @@ use super::{ control::MoveKind, goals::{Cx, Goal, MOVE, TARGET, goal_clone, reduced}, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; /// Phantom state in `Extra`: `flag` swooping, `home` the anchor, @@ -151,9 +152,9 @@ impl CircleAroundAnchor { ]); self.angle += self.clockwise * 15.0f32.to_radians(); m.extra.vector = [ - f64::from(a[0]) + f64::from(self.distance * self.angle.cos()), + f64::from(a[0]) + f64::from(self.distance * self.angle.mcos()), f64::from(a[1]) + f64::from(-4.0 + self.height), - f64::from(a[2]) + f64::from(self.distance * self.angle.sin()), + f64::from(a[2]) + f64::from(self.distance * self.angle.msin()), ]; } } @@ -319,9 +320,9 @@ pub fn move_control(m: &mut Mob) { let x_rot = -((-dy).atan2(sd) as f32).to_degrees(); m.head_pitch = x_rot; let move_angle = (m.yaw + 90.0).to_radians(); - let tx = f64::from(speed * move_angle.cos()) * (dx / sd2).abs(); - let tz = f64::from(speed * move_angle.sin()) * (dz / sd2).abs(); - let ty = f64::from(speed * x_rot.to_radians().sin()) * (dy / sd2).abs(); + let tx = f64::from(speed * move_angle.mcos()) * (dx / sd2).abs(); + let tz = f64::from(speed * move_angle.msin()) * (dz / sd2).abs(); + let ty = f64::from(speed * x_rot.to_radians().msin()) * (dy / sd2).abs(); let v = m.velocity; m.velocity = Vec3::new( v.x + (tx - v.x) * 0.2, @@ -336,20 +337,20 @@ pub fn move_control(m: &mut Mob) { /// `PhantomModel.setupAnim` (flap time offset by the id). pub fn anim(m: &Mob, s: &super::anim::State, p: &mut super::anim::Poses) { let flap = (m.id as f32 * 3.0 + s.age) * 7.448_451_f32.to_radians(); - let wing = flap.cos() * 16.0f32.to_radians(); + let wing = flap.mcos() * 16.0f32.to_radians(); p.zrot("left_wing_base", wing); p.zrot("left_wing_tip", wing); p.zrot("right_wing_base", -wing); p.zrot("right_wing_tip", -wing); - let tail = -(5.0 + (flap * 2.0).cos() * 5.0f32).to_radians(); + let tail = -(5.0 + (flap * 2.0).mcos() * 5.0f32).to_radians(); p.xrot("tail_base", tail); p.xrot("tail_tip", tail); } /// The flap sound when a wingbeat begins (`Phantom.isFlapping`). pub fn flap_sound(m: &Mob, events: &mut Vec) { let t = m.id as f32 * 3.0 + m.age as f32; - let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); - let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos(); + let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos(); + let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos(); if a > 0.0 && b <= 0.0 { events.push(MobEvent::Sound( "entity.phantom.flap", diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index f5a70bd6c..410364097 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -9,6 +9,7 @@ use super::{ NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -251,48 +252,112 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }; cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0)); } +/// `AbstractPiglinModel.setupAnim`: the ears flap around their default angle +/// (30 degrees for adults, 5 for babies). +pub fn ears(p: &mut Poses, s: &State) { + use horizon_core::geometry::trig::DEG_TO_RAD; + let default = if s.baby { 5.0 } else { 30.0 } * DEG_TO_RAD; + let freq = s.age * 0.1 + s.pos * 0.5; + let amp = 0.08 + s.speed * 0.4; + p.zrot("left_ear", -default - (freq * 1.2).mcos() * amp); + p.zrot("right_ear", default + freq.mcos() * amp); +} /// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the /// arm pose (`PiglinModel`). pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) { - super::anim::humanoid_item(p, s, m.extra.main_hand.is_some()); - let default = PI / 6.0; - let freq = s.age * 0.1 + s.pos * 0.5; - let amp = 0.08 + s.speed * 0.4; - p.zrot("left_ear", -default - (freq * 1.2).cos() * amp); - p.zrot("right_ear", default + freq.cos() * amp); - let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); - if m.extra.using_item > 0 { - // ADMIRING_ITEM: head down at the left hand. - p.xrot("head", 0.5); - p.yrot("head", 0.0); - p.yrot("left_arm", 0.5); - p.xrot("left_arm", -0.9); + let pose = if m.extra.using_item > 0 { + PiglinPose::AdmiringItem } else if m.extra.flag { - p.yrot("right_arm", -0.8); - p.xrot("right_arm", -0.970_796_35); - let a = (m.extra.using_item as f32).clamp(0.0, 25.0) / 25.0; - p.yrot("left_arm", 0.4 + 0.45 * a); - p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a); + PiglinPose::CrossbowCharge } else if m.extra.main_hand.as_deref() == Some("minecraft:crossbow") && m.ai.aggressive { - p.yrot("right_arm", -0.3 + hy); - p.yrot("left_arm", 0.6 + hy); - p.xrot("right_arm", -PI / 2.0 + hx + 0.1); - p.xrot("left_arm", -1.5 + hx); - } else if m.ai.aggressive && m.extra.main_hand.is_some() && s.swing == 0.0 { - p.xrot("right_arm", -1.8); + PiglinPose::CrossbowHold + } else if m.ai.aggressive && m.extra.main_hand.is_some() { + PiglinPose::MeleeWeapon + } else { + PiglinPose::Default + }; + piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32); +} +/// `PiglinArmPose`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PiglinPose { + Default, + Dancing, + MeleeWeapon, + CrossbowHold, + CrossbowCharge, + AdmiringItem, +} +/// `PiglinModel.setupAnim` for a piglin facing right-handed. +pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) { + use super::anim::{ArmPose, Hum, humanoid}; + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.weapon_swing = pose == PiglinPose::MeleeWeapon; + h.charge = (max_charge, ticks); + humanoid(p, s, &h); + ears(p, s); + let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians()); + let rad = |v: f64| v as f32; + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + match pose { + PiglinPose::Dancing => { + let dance = s.age / 60.0; + p.zrot( + "right_ear", + rad(std::f64::consts::PI / 6.0) + deg * (dance * 30.0).msin() * 10.0, + ); + p.zrot( + "left_ear", + rad(-std::f64::consts::PI / 6.0) - deg * (dance * 30.0).mcos() * 10.0, + ); + p.get("head")[0] += (dance * 10.0).msin(); + p.get("head")[1] += (dance * 40.0).msin() + 0.4; + let z = deg * (70.0 + (dance * 40.0).mcos() * 10.0); + p.zrot("right_arm", z); + p.zrot("left_arm", -z); + p.get("right_arm")[1] += (dance * 40.0).msin() * 0.5 - 0.5; + p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5; + p.get("body")[1] += (dance * 40.0).msin() * 0.35; + } + PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8), + PiglinPose::CrossbowHold => { + p.yrot("right_arm", -0.3 + hy); + p.yrot("left_arm", 0.6 + hy); + p.xrot("right_arm", -PI / 2.0 + hx + 0.1); + p.xrot("left_arm", -1.5 + hx); + } + PiglinPose::CrossbowCharge => { + p.yrot("right_arm", -0.8); + p.xrot("right_arm", -0.970_796_35); + p.xrot("left_arm", -0.970_796_35); + let alpha = ticks.clamp(0.0, max_charge) / max_charge; + p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4)); + let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35); + p.xrot("left_arm", x); + } + PiglinPose::AdmiringItem => { + p.xrot("head", 0.5); + p.yrot("head", 0.0); + p.yrot("left_arm", 0.5); + p.xrot("left_arm", -0.9); + } + _ => {} } } /// `HoglinModel.setupAnim`. pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) { let (pos, sp) = (s.pos, s.speed); - p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.sin()); - p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.sin()); + p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.msin()); + p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.msin()); p.yrot("head", s.y_rot.to_radians()); let remaining = m.extra.anim_ticks as f32; let f = 1.0 - (10.0 - 2.0 * remaining).abs() / 10.0; p.xrot("head", 0.872_664_63 + (-PI / 9.0 - 0.872_664_63) * f); - p.xrot("right_front_leg", pos.cos() * 1.2 * sp); - p.xrot("left_front_leg", (pos + PI).cos() * 1.2 * sp); - p.xrot("right_hind_leg", (pos + PI).cos() * 1.2 * sp); - p.xrot("left_hind_leg", pos.cos() * 1.2 * sp); + if s.baby { + p.get("head")[1] += f * 2.5; + } + p.xrot("right_front_leg", pos.mcos() * 1.2 * sp); + p.xrot("left_front_leg", (pos + PI).mcos() * 1.2 * sp); + p.xrot("right_hind_leg", (pos + PI).mcos() * 1.2 * sp); + p.xrot("left_hind_leg", pos.mcos() * 1.2 * sp); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 0166a21c3..be30712f0 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -7,6 +7,7 @@ use super::{ goals::{Float, HurtByTarget, LookAtPlayer, MeleeAttack, NearestTarget, Stroll}, path::PathType, }; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::f32::consts::PI; @@ -134,9 +135,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Particles { kind: "entity_effect", at: [ - m.position.x - width * f64::from(yaw.sin()), + m.position.x - width * f64::from(yaw.msin()), m.position.y + f64::from(m.height()) - 0.3, - m.position.z + width * f64::from(yaw.cos()), + m.position.z + width * f64::from(yaw.mcos()), ], count: 0, }); @@ -225,34 +226,35 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let neck_x_rot = p.get("neck")[3]; let neck = p.get("neck"); neck[2] = -6.5 + head; - neck[1] = -7.0 - head * neck_x_rot.sin(); + neck[1] = -7.0 - head * neck_x_rot.msin(); let mouth = if attack > 5.0 { - ((-4.0 + attack) / 4.0).sin() * PI * 0.4 + ((-4.0 + attack) / 4.0).msin() * PI * 0.4 } else { - PI / 20.0 * (PI * attack / 10.0).sin() + PI / 20.0 * (PI * attack / 10.0).msin() }; p.xrot("mouth", mouth); } else { let is_stunned = stunned > 0.0; let x_rot: f32 = if is_stunned { 0.219_911_49 } else { 0.0 }; let neck = p.get("neck"); + let y_offset = -neck[3].msin(); neck[0] = 0.0; - neck[1] = -7.0 + x_rot.sin(); + neck[1] = -7.0 - y_offset; neck[2] = 5.5; neck[3] = x_rot; p.xrot("mouth", PI * if is_stunned { 0.05 } else { 0.01 }); if is_stunned { - p.get("neck")[0] = ((stunned / 40.0) * 10.0).sin() * 3.0; + p.get("neck")[0] = ((f64::from(stunned) / 40.0) * 10.0).sin() as f32 * 3.0; } else if m.extra.anim_ticks > 0 { let roar = (20.0 - m.extra.anim_ticks as f32 + s.partial) / 20.0; - p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).sin()); + p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).msin()); } } p.xrot("head", s.x_rot.to_radians()); p.yrot("head", s.y_rot.to_radians()); let (pos, leg) = (s.pos, 0.4 * s.speed); - p.xrot("right_hind_leg", (pos * 0.6662).cos() * leg); - p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * leg); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * leg); - p.xrot("left_front_leg", (pos * 0.6662).cos() * leg); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * leg); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * leg); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * leg); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * leg); } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index d640b6973..46513a311 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -8,6 +8,7 @@ use super::{ living::wrap, }; use crate::mesher::Vertex; +use horizon_core::geometry::trig::Mth; use std::f32::consts::PI; /// A texture lookup into the shared atlas (name without namespace -> uv rect). @@ -667,7 +668,7 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { 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 wobble = 1.0 + (s * 100.0).msin() * 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; @@ -699,10 +700,10 @@ pub fn draw( 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 { + if poses.is_hidden(part) || p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 { return; } - for poly in &part.polygons { + for poly in part.polygons.iter().filter(|_| !poses.skips(part)) { for v in poly.vertices { let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0); out.push(Vertex { diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index b40ddbf0a..11ebdadb4 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -11,6 +11,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileWorld, STEPS}; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -20,7 +21,7 @@ use std::f32::consts::PI; // Shulker state: `variant3` the attach face (3D data value), `counter` the // raw peek (0..100), `color` the shell colour (16 none). AnimState slot 0 // the current peek amount. -const PEEK: usize = 0; +pub const PEEK: usize = 0; pub const NO_COLOR: u8 = 16; pub fn register(m: &mut Mob) { @@ -335,14 +336,14 @@ pub fn rotations(m: &Mob) -> glam::Mat4 { pub fn anim(m: &Mob, s: &State, p: &mut Poses) { let peek = m.anim.lerp(PEEK, s.partial); let bs = (0.5 + peek) * PI; - let q = -1.0 + bs.sin(); + let q = -1.0 + bs.msin(); let extra = if bs > PI { - (s.age * 0.1).sin() * 0.7 + (s.age * 0.1).msin() * 0.7 } else { 0.0 }; let lid = p.get("lid"); - lid[1] = 16.0 + bs.sin() * 8.0 + extra; + lid[1] = 16.0 + bs.msin() * 8.0 + extra; lid[4] = if peek > 0.3 { q * q * q * q * PI * 0.125 } else { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 1d38d4789..96b98dd78 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1221,6 +1221,9 @@ impl Def { Species::Hoglin => &["hoglin_baby"], Species::Zoglin => &["zoglin_baby"], Species::Strider => &["strider_baby"], + Species::Camel => &["camel_baby"], + Species::ZombieHorse => &["zombie_horse_baby"], + Species::SkeletonHorse => &["skeleton_horse_baby"], _ => &[], }; v.extend_from_slice(extra); diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1b6ef9d66..c00706b89 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -10,6 +10,7 @@ use super::{ reduced, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -54,8 +55,8 @@ pub fn wolf_variant_for(biome: &str, has_tag: &dyn Fn(&str) -> bool) -> u8 { pub const RED: u8 = 14; // AnimState slots: begging interest and the shake animation. -const INTEREST: usize = 0; -const SHAKE: usize = 1; +pub const INTEREST: usize = 0; +pub const SHAKE: usize = 1; pub fn register(m: &mut Mob) { m.extra.color = RED; @@ -537,7 +538,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.anim.vo[SHAKE] = 0.0; } if m.anim.v[SHAKE] > 0.4 { - let count = (((m.anim.v[SHAKE] - 0.4) * PI).sin() * 7.0) as u32; + let count = (((m.anim.v[SHAKE] - 0.4) * PI).msin() * 7.0) as u32; if count > 0 { events.push(MobEvent::Particles { kind: "splash", @@ -576,7 +577,7 @@ fn tail_angle(m: &Mob) -> f32 { /// `WolfRenderState.getBodyRollAngle`. fn body_roll(shake: f32, offset: f32) -> f32 { let p = ((shake + offset) / 1.8).clamp(0.0, 1.0); - (p * PI).sin() * (p * PI * 11.0).sin() * 0.15 * PI + (p * PI).msin() * (p * PI * 11.0).msin() * 0.15 * PI } /// `WolfModel.setupAnim` with the adult and baby overrides. pub fn anim(m: &Mob, s: &State, p: &mut Poses) { @@ -585,7 +586,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { if angry(m) { p.yrot("tail", 0.0); } else { - p.yrot("tail", (pos * 0.6662).cos() * 1.4 * speed); + p.yrot("tail", (pos * 0.6662).mcos() * 1.4 * speed); } if m.extra.sitting { let age = if baby { 0.5 } else { 1.0 }; @@ -615,10 +616,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("upper_body", 0.0); } } else { - p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * speed); - p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed); - p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * speed); + p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed); + p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed); + p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed); } // shakeOffWater let shake = m.anim.lerp(SHAKE, s.partial); @@ -946,26 +947,39 @@ pub fn cat_rotations(m: &Mob, partial: f32) -> glam::Mat4 { glam::Mat4::from_translation(glam::Vec3::new(0.4 * lie, 0.15 * lie, 0.1 * lie)) * glam::Mat4::from_rotation_z((90.0 * lie).to_radians()) } +/// `Mth.rotLerp`: degrees-wrapping, applied by the feline models to radians. fn rot_lerp(t: f32, from: f32, to: f32) -> f32 { - let mut d = (to - from) % (PI * 2.0); - if d < -PI { - d += PI * 2.0; - } - if d >= PI { - d -= PI * 2.0; - } - from + t * d + from + t * super::living::wrap(to - from) } -/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats. +/// `FelineRenderState` values the feline models read. +#[derive(Clone, Copy, Debug, Default)] +pub struct Feline { + pub crouching: bool, + pub sprinting: bool, + pub sitting: bool, + pub lie_down: f32, + pub lie_down_tail: f32, + pub relax_one: f32, +} +/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats and ocelots. pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { - let baby = m.is_baby(); - let age = if baby { 0.5 } else { 1.0 }; let wanted = m.ai.mov.has_wanted(); let speed_mod = m.ai.mov.speed_modifier; // Cat.customServerAiStep: crouch while stalking, sprint while dashing. - let crouching = wanted && (speed_mod - 0.6).abs() < 1e-6; - let sprinting = wanted && (speed_mod - 1.33).abs() < 1e-6; - let sitting = cat_sitting(m); + let st = Feline { + crouching: wanted && (speed_mod - 0.6).abs() < 1e-6, + sprinting: wanted && (speed_mod - 1.33).abs() < 1e-6, + sitting: cat_sitting(m), + lie_down: m.anim.lerp(LIE, s.partial), + lie_down_tail: m.anim.lerp(LIE_TAIL, s.partial), + relax_one: m.anim.lerp(RELAX, s.partial), + }; + feline(p, s, &st); +} +pub fn feline(p: &mut Poses, s: &State, st: &Feline) { + let baby = s.baby; + let age = if baby { 0.5 } else { 1.0 }; + let (crouching, sprinting, sitting) = (st.crouching, st.sprinting, st.sitting); let add = |p: &mut Poses, part: &str, x: f32, y: f32, z: f32| { let v = p.get(part); v[0] += x; @@ -994,18 +1008,18 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("body", PI / 2.0); } if sprinting { - p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp); - p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).cos() * sp); - p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).cos() * sp); - p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.cos() * sp); + p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp); + p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).mcos() * sp); + p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).mcos() * sp); + p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.mcos() * sp); } else { - p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp); - p.xrot("right_hind_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("left_front_leg", (pos * 0.6662 + PI).cos() * sp); - p.xrot("right_front_leg", (pos * 0.6662).cos() * sp); + p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp); + p.xrot("right_hind_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("left_front_leg", (pos * 0.6662 + PI).mcos() * sp); + p.xrot("right_front_leg", (pos * 0.6662).mcos() * sp); let swing = if crouching { 0.471_238_94 } else { PI / 4.0 }; - p.xrot("tail2", 1.727_876_1 + swing * pos.cos() * sp); + p.xrot("tail2", 1.727_876_1 + swing * pos.mcos() * sp); } } else if baby { let x = p.get("body")[3] - 0.436_332_32; @@ -1034,9 +1048,31 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("right_hind_leg", -PI / 2.0); add(p, "right_hind_leg", 0.0, 3.0 * age, -4.0 * age); } - let lie = m.anim.lerp(LIE, s.partial); - let lie_tail = m.anim.lerp(LIE_TAIL, s.partial); - if lie > 0.0 && !baby { + let lie = st.lie_down; + let lie_tail = st.lie_down_tail; + if lie > 0.0 && baby { + add(p, "body", 1.0, 0.0, 0.0); + let hx = p.get("head")[3]; + p.xrot("head", rot_lerp(lie, hx, PI / 18.0)); + let hz = p.get("head")[5]; + p.zrot("head", rot_lerp(lie, hz, -PI * 5.0 / 12.0)); + add(p, "head", 1.5, 0.75, -0.5); + p.xrot("right_front_leg", -PI / 4.0); + add(p, "right_front_leg", 3.5, -0.5, 0.0); + p.xrot("left_front_leg", -PI / 2.0); + add(p, "left_front_leg", 1.5, -1.0, -2.0); + p.xrot("right_hind_leg", PI * 2.0 / 9.0); + p.yrot("right_hind_leg", PI / 9.0); + p.zrot("right_hind_leg", -PI / 9.0); + add(p, "right_hind_leg", 2.5, -0.25, 0.5); + add(p, "left_hind_leg", 1.5, 0.0, -1.0); + let t = p.get("tail1"); + let (tx, ty, tz) = (t[3], t[4], t[5]); + p.xrot("tail1", tx + rot_lerp(lie_tail, tx, -PI / 6.0)); + p.yrot("tail1", ty + rot_lerp(lie_tail, ty, 0.0)); + p.zrot("tail1", tz + rot_lerp(lie_tail, tz, -PI / 18.0)); + add(p, "tail1", 1.0, 0.5, -0.25); + } else if lie > 0.0 { let (hz, hy) = (p.get("head")[5], p.get("head")[4]); p.zrot("head", rot_lerp(lie, hz, -1.270_796_3)); p.yrot("head", rot_lerp(lie, hy, 1.270_796_3)); @@ -1052,7 +1088,7 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) { p.xrot("tail1", rot_lerp(lie_tail, t1, 0.8)); p.xrot("tail2", rot_lerp(lie_tail, t2, -0.4)); } - let relax = m.anim.lerp(RELAX, s.partial); + let relax = st.relax_one; if relax > 0.0 { let hx = p.get("head")[3]; p.xrot("head", rot_lerp(relax, hx, -0.581_776_44)); diff --git a/crates/horizon-client/src/mobs/vex.rs b/crates/horizon-client/src/mobs/vex.rs index 2ee444d84..19e873cb2 100644 --- a/crates/horizon-client/src/mobs/vex.rs +++ b/crates/horizon-client/src/mobs/vex.rs @@ -9,6 +9,7 @@ use super::{ Cx, Float, Goal, HurtByTarget, LookAtPlayer, MOVE, NearestTarget, goal_clone, reduced, }, }; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; @@ -224,19 +225,38 @@ pub fn ai_step(m: &mut Mob, w: &super::MobWorld) { 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()); - let bob = (s.age * 5.5).to_radians().cos() * 0.1; + let bob = (s.age * 5.5 * horizon_core::geometry::trig::DEG_TO_RAD).mcos() * 0.1; p.zrot("right_arm", PI / 5.0 + bob); p.zrot("left_arm", -(PI / 5.0 + bob)); if m.extra.flag { p.xrot("body", 0.0); - // Holding the sword in the right hand. - p.xrot("right_arm", PI * 7.0 / 6.0); - p.yrot("right_arm", PI / 12.0); - p.zrot("right_arm", -0.471_238_88 - bob); + // setArmsCharging + let (right, left) = (m.extra.main_hand.is_some(), m.extra.off_hand.is_some()); + if !right && !left { + p.xrot("right_arm", -1.221_730_5); + p.yrot("right_arm", PI / 12.0); + p.zrot("right_arm", -0.471_238_88 - bob); + p.xrot("left_arm", -1.221_730_5); + p.yrot("left_arm", -PI / 12.0); + p.zrot("left_arm", 0.471_238_88 + bob); + } else { + let sword = (std::f64::consts::PI * 7.0 / 6.0) as f32; + if right { + p.xrot("right_arm", sword); + p.yrot("right_arm", PI / 12.0); + p.zrot("right_arm", -0.471_238_88 - bob); + } + if left { + p.xrot("left_arm", sword); + p.yrot("left_arm", -PI / 12.0); + p.zrot("left_arm", 0.471_238_88 + bob); + } + } } else { p.xrot("body", PI / 20.0); } - let wing = 1.099_557_4 + (s.age * 45.836_624).to_radians().cos() * 16.2_f32.to_radians(); + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + let wing = 1.099_557_4 + (s.age * 45.836_624 * deg).mcos() * deg * 16.2; p.yrot("left_wing", wing); p.yrot("right_wing", -wing); p.xrot("left_wing", 0.471_238_88); diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 82e7645bd..7b9df3c33 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -13,6 +13,7 @@ use super::{ }, }; use crate::items::ItemStack; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; use std::{collections::HashMap, f32::consts::PI}; @@ -603,16 +604,16 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("head", if awake { s.y_rot.to_radians() } else { 0.0 }); p.xrot("head", if awake { s.x_rot.to_radians() } else { 0.0 }); if m.extra.ints[0] > 0 { - p.zrot("head", 0.3 * (0.45 * s.age).sin()); + p.zrot("head", 0.3 * (0.45 * s.age).msin()); p.xrot("head", 0.4); } else { p.zrot("head", 0.0); } - let leg = (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5; + let leg = (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5; p.xrot("right_leg", leg); p.xrot( "left_leg", - (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed * 0.5, + (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed * 0.5, ); p.yrot("right_leg", 0.0); p.yrot("left_leg", 0.0); diff --git a/crates/horizon-client/src/mobs/witch.rs b/crates/horizon-client/src/mobs/witch.rs index 9fc0b0171..32fea42c4 100644 --- a/crates/horizon-client/src/mobs/witch.rs +++ b/crates/horizon-client/src/mobs/witch.rs @@ -9,6 +9,7 @@ use super::{ }, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; pub fn register(m: &mut Mob) { @@ -258,20 +259,15 @@ pub fn ai_step(m: &mut Mob, cx_events: &mut Vec, target_far: bool) { 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("right_leg", (s.pos * 0.6662).mcos() * 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, + (s.pos * 0.6662 + std::f32::consts::PI).mcos() * 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, - ); + let deg = horizon_core::geometry::trig::DEG_TO_RAD; + p.xrot("nose", (s.age * speed).msin() * 4.5 * deg); + p.zrot("nose", (s.age * speed).mcos() * 2.5 * deg); if m.extra.main_hand.is_some() { let n = p.get("nose"); n[0] = 0.0; diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index f7e34d2cc..5782723d1 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -13,6 +13,7 @@ use super::{ nav::NavKind, }; use crate::projectiles::{Projectile, ProjectileKind}; +use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; // Wither state: `counter` the invulnerable ticks, `counter2` the block @@ -102,9 +103,9 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] { } let a = (m.body_yaw + 180.0 * (i as f32 - 1.0)).to_radians(); [ - m.position.x + f64::from(a.cos()) * 1.3, + m.position.x + f64::from(a.mcos()) * 1.3, m.position.y + 2.2, - m.position.z + f64::from(a.sin()) * 1.3, + m.position.z + f64::from(a.msin()) * 1.3, ] } /// `performRangedAttack`: a skull from a head toward a point. @@ -348,13 +349,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot(head, (y - body).to_radians()); p.xrot(head, x.to_radians()); } - let anim = (s.age * 0.1).cos(); + let anim = (s.age * 0.1).mcos(); let rib = (0.065 + 0.05 * anim) * std::f32::consts::PI; p.xrot("ribcage", rib); let tail = p.get("tail"); tail[0] = -2.0; - tail[1] = 6.9 + rib.cos() * 10.0; - tail[2] = -0.5 + rib.sin() * 10.0; + tail[1] = 6.9 + rib.mcos() * 10.0; + tail[2] = -0.5 + rib.msin() * 10.0; p.xrot("tail", (0.265 + 0.1 * anim) * std::f32::consts::PI); p.yrot("center_head", s.y_rot.to_radians()); p.xrot("center_head", s.x_rot.to_radians()); diff --git a/crates/horizon-core/src/geometry/trig.rs b/crates/horizon-core/src/geometry/trig.rs index 988f05177..bdc3529cf 100644 --- a/crates/horizon-core/src/geometry/trig.rs +++ b/crates/horizon-core/src/geometry/trig.rs @@ -23,6 +23,20 @@ pub fn cos(angle: f64) -> f32 { sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize] } +/// `Mth.sin` / `Mth.cos` on a float, as the models call them. +pub trait Mth { + fn msin(self) -> f32; + fn mcos(self) -> f32; +} +impl Mth for f32 { + fn msin(self) -> f32 { + sin(f64::from(self)) + } + fn mcos(self) -> f32 { + cos(f64::from(self)) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java new file mode 100644 index 000000000..a99361dc2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java @@ -0,0 +1,196 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.client.model.EntityModel; +import net.minecraft.client.model.geom.LayerDefinitions; +import net.minecraft.client.model.geom.ModelLayerLocation; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.renderer.entity.state.EntityRenderState; +import net.minecraft.server.Bootstrap; + +/** + * Original oracle for the client's entity model animation: bakes each vanilla model layer, builds + * its own render state class with the given walk/age/head/attack values plus optional extra + * fields, runs the real setupAnim and writes every part's pose. + * + * Input lines: "layer-key ModelClass|case-json" where case-json is an object of state field + * name to value. Output lines: {layer, case, parts:{path:[x,y,z,xRot,yRot,zRot,xScale,yScale,zScale,visible]}}. + */ +public final class VanillaEntityAnimOracle { + private static Field cubes; + private static Field children; + + @SuppressWarnings("unchecked") + private static void dump(String path, ModelPart part, JsonObject out) throws Exception { + var pose = new JsonArray(); + for (float f : new float[] {part.x, part.y, part.z, part.xRot, part.yRot, part.zRot, part.xScale, part.yScale, part.zScale}) + pose.add(f); + pose.add(part.visible && !part.skipDraw ? 1 : 0); + int polys = 0; + double sum = 0; + for (ModelPart.Cube cube : (List) cubes.get(part)) { + for (ModelPart.Polygon polygon : cube.polygons) { + polys++; + for (ModelPart.Vertex v : polygon.vertices()) { + float u = Float.isFinite(v.u()) ? v.u() : 0.0F, w = Float.isFinite(v.v()) ? v.v() : 0.0F; + sum += v.x() + 2.0 * v.y() + 3.0 * v.z() + 5.0 * u + 7.0 * w; + } + } + } + pose.add(polys); + pose.add(sum); + out.add(path, pose); + for (var entry : ((Map) children.get(part)).entrySet()) + dump(path.isEmpty() ? entry.getKey() : path + "/" + entry.getKey(), entry.getValue(), out); + } + + private static Class findClass(String simple) throws Exception { + for (String pkg : new String[] {"net.minecraft.client.model"}) { + // Search subpackages by trying every known class location through the jar index. + for (String name : CLASS_NAMES) { + if (name.endsWith("." + simple) || name.equals(simple)) return Class.forName(name); + } + } + throw new ClassNotFoundException(simple); + } + + private static final List CLASS_NAMES = new ArrayList<>(); + + private static Class raw(java.lang.reflect.Type t, Map, java.lang.reflect.Type> env) { + if (t instanceof Class c) return c; + if (t instanceof java.lang.reflect.ParameterizedType p) return raw(p.getRawType(), env); + if (t instanceof java.lang.reflect.TypeVariable v) { + var bound = env.get(v); + return raw(bound != null ? bound : v.getBounds()[0], env); + } + throw new IllegalArgumentException("cannot resolve " + t); + } + + /** The render state class: the model's `S`, resolved through its generic superclasses. */ + private static Class stateClass(Class model) { + var env = new HashMap, java.lang.reflect.Type>(); + Class current = model; + for (var v : current.getTypeParameters()) env.put(v, raw(v.getBounds()[0], env)); + while (current != net.minecraft.client.model.Model.class) { + var sup = current.getGenericSuperclass(); + if (sup instanceof java.lang.reflect.ParameterizedType p) { + var params = ((Class) p.getRawType()).getTypeParameters(); + for (int i = 0; i < params.length; i++) env.put(params[i], raw(p.getActualTypeArguments()[i], env)); + current = (Class) p.getRawType(); + } else { + current = (Class) sup; + } + } + return raw(net.minecraft.client.model.Model.class.getTypeParameters()[0], env); + } + + private static Field field(Class type, String name) { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredField(name); + } catch (NoSuchFieldException e) { + } + } + return null; + } + + private static void set(Object state, String name, JsonElement value) throws Exception { + boolean optional = name.startsWith("?") || Set.of("walkAnimationPos", "walkAnimationSpeed", "yRot", "xRot", "isBaby", "swingAnimation", "ageScale", "ageInTicks", "entityId", "yHeadRot", "yBodyRot", "eatTick", "flapOffset", "interest").contains(name); + if (name.startsWith("?")) name = name.substring(1); + Field f = field(state.getClass(), name); + if (f == null && optional) return; + if (f == null) throw new IllegalArgumentException("no field " + name + " on " + state.getClass()); + f.setAccessible(true); + Class t = f.getType(); + if (t == float.class) f.setFloat(state, value.getAsFloat()); + else if (t == int.class) f.setInt(state, value.getAsInt()); + else if (t == double.class) f.setDouble(state, value.getAsDouble()); + else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean()); + else if (t.isEnum()) { + for (Object c : t.getEnumConstants()) if (((Enum) c).name().equals(value.getAsString())) f.set(state, c); + } else if (t.getSimpleName().equals("AnimationState")) { + // value = age in ticks since start (negative = stopped) + var a = (net.minecraft.world.entity.AnimationState) f.get(state); + a.stop(); + if (value.getAsJsonPrimitive().isNumber()) a.start(value.getAsInt()); + } else throw new IllegalArgumentException("unsupported type " + t + " for " + name); + } + + /** Render-state values vanilla derives from entity state; the case gives the entity-side input. */ + private static void hooks(EntityRenderState state, JsonObject kase) { + if (state instanceof net.minecraft.client.renderer.entity.state.SheepRenderState sheep && kase.has("eatTick")) { + // Sheep.getHeadEatPositionScale / getHeadEatAngleScale at partial tick 0. + int t = kase.get("eatTick").getAsInt(); + float a = 0.0F; + sheep.headEatPositionScale = t <= 0 ? 0.0F : t >= 4 && t <= 36 ? 1.0F : t < 4 ? (t - a) / 4.0F : -(t - 40 - a) / 4.0F; + if (t > 4 && t <= 36) { + float scale = (t - 4 - a) / 32.0F; + sheep.headEatAngleScale = (float) (Math.PI / 5) + 0.21991149F * net.minecraft.util.Mth.sin(scale * 28.7F); + } else { + sheep.headEatAngleScale = t > 0 ? (float) (Math.PI / 5) : sheep.xRot * (float) (Math.PI / 180.0); + } + } + if (state instanceof net.minecraft.client.renderer.entity.state.WolfRenderState wolf && kase.has("interest")) + wolf.headRollAngle = kase.get("interest").getAsFloat() * 0.15F * (float) Math.PI; + if (state instanceof net.minecraft.client.renderer.entity.state.PhantomRenderState phantom && kase.has("flapOffset")) + phantom.flapTime = kase.get("flapOffset").getAsFloat() + phantom.ageInTicks; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + cubes = ModelPart.class.getDeclaredField("cubes"); + cubes.setAccessible(true); + children = ModelPart.class.getDeclaredField("children"); + children.setAccessible(true); + try (var zip = new java.util.zip.ZipFile(args[2])) { + zip.stream().map(e -> e.getName()).filter(n -> n.startsWith("net/minecraft/client/model/") && n.endsWith(".class")) + .forEach(n -> CLASS_NAMES.add(n.substring(0, n.length() - 6).replace('/', '.'))); + } + var roots = LayerDefinitions.createRoots(); + var byName = new HashMap(); + for (var key : roots.keySet()) byName.put(key.toString(), key); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + var halves = line.split("\\|", 2); + var head = halves[0].split(" "); + var layer = head[0]; + var kase = JsonParser.parseString(halves[1]).getAsJsonObject(); + var result = new JsonObject(); + result.addProperty("layer", layer); + result.add("case", kase); + try { + var location = byName.get(layer); + if (location == null) throw new IllegalArgumentException("no layer " + layer); + var cls = findClass(head[1]); + var baked = roots.get(location).bakeRoot(); + var model = (net.minecraft.client.model.Model) cls.getConstructor(ModelPart.class).newInstance(baked); + var type = stateClass(cls); + var state = (EntityRenderState) type.getDeclaredConstructor().newInstance(); + state.getClass(); + for (var entry : kase.entrySet()) set(state, entry.getKey(), entry.getValue()); + hooks(state, kase); + if (state instanceof net.minecraft.client.renderer.entity.state.ArmedEntityRenderState armed && armed.swingAnimation > 0) + armed.currentSwing = new net.minecraft.world.entity.LivingEntity.SwingDescription(net.minecraft.world.InteractionHand.MAIN_HAND, net.minecraft.world.item.component.SwingAnimation.DEFAULT, 6); + model.setupAnim(state); + var parts = new JsonObject(); + dump("", baked, parts); + result.add("parts", parts); + } catch (Throwable error) { + var cause = error.getCause() != null ? error.getCause() : error; + result.addProperty("error", cause.toString()); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py new file mode 100644 index 000000000..ed83a3b0e --- /dev/null +++ b/tools/test_entity_model_parity.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""Compare entity model geometry and setupAnim poses with the vanilla 26.3 client. + +The Java oracle bakes each vanilla model layer, builds the model's own render +state class with the generated walk/age/head/attack inputs (plus per-species +state fields), runs the real `setupAnim` and writes every part's pose. +`examples/entity_anim_fixture` replays the same inputs through Horizon's +`mobs::anim::setup` and the loaded model tree; the two must agree on every part +pose and on the baked polygon count and vertex sums. + + test_entity_model_parity.py [--filter SUBSTRING] [--detail LAYER] [--tolerance EPS] +""" +import argparse +import json +import math +import os +from pathlib import Path +import random +import re +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + +CLIENT = lab.LOCAL / 'minecraft' / '26.3' / 'sources' / 'client' / 'net' / 'minecraft' / 'client' + +# Models that no renderer builds with a plain `new Model(context.bakeLayer(CONSTANT))`. +EXTRAS = [ + ('minecraft:zombie#main', 'ZombieModel'), ('minecraft:zombie_baby#main', 'BabyZombieModel'), + ('minecraft:husk#main', 'ZombieModel'), ('minecraft:husk_baby#main', 'BabyZombieModel'), + ('minecraft:zombie_villager#main', 'ZombieVillagerModel'), + ('minecraft:zombie_villager_baby#main', 'BabyZombieVillagerModel'), + ('minecraft:zombified_piglin#main', 'AdultZombifiedPiglinModel'), + ('minecraft:zombified_piglin_baby#main', 'BabyZombifiedPiglinModel'), + ('minecraft:skeleton#main', 'SkeletonModel'), ('minecraft:stray#main', 'SkeletonModel'), + ('minecraft:wither_skeleton#main', 'SkeletonModel'), + ('minecraft:spider#main', 'SpiderModel'), ('minecraft:cave_spider#main', 'SpiderModel'), + ('minecraft:enderman#main', 'EndermanModel'), ('minecraft:endermite#main', 'EndermiteModel'), + ('minecraft:piglin#main', 'AdultPiglinModel'), ('minecraft:piglin_brute#main', 'AdultPiglinModel'), + ('minecraft:piglin_baby#main', 'BabyPiglinModel'), + ('minecraft:hoglin#main', 'HoglinModel'), ('minecraft:zoglin#main', 'HoglinModel'), + ('minecraft:hoglin_baby#main', 'BabyHoglinModel'), ('minecraft:zoglin_baby#main', 'BabyHoglinModel'), + ('minecraft:guardian#main', 'GuardianModel'), ('minecraft:elder_guardian#main', 'GuardianModel'), + ('minecraft:evoker#main', 'IllagerModel'), ('minecraft:illusioner#main', 'IllagerModel'), + ('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'), + ('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'), + ('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'), + ('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'), + ('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'), + ('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'), + ('minecraft:skeleton_horse_baby#main', 'BabyHorseModel'), ('minecraft:zombie_horse_baby#main', 'BabyHorseModel'), + ('minecraft:cave_spider#main', 'SpiderModel'), + ('minecraft:stray#main', 'SkeletonModel'), +] +# Layers a renderer reuses for another entity under a different constant. +SKIP_LAYERS = re.compile(r'(banner|bell|book|skull|head|chest|shulker_box|boat|cushion|conduit|leash|arrow|trident|' + r'shield|elytra|spin_attack|ears|cape|decorated_pot|minecart|wind_charge|evoker_fangs|' + r'llama_spit|shulker_bullet|bee_stinger|end_crystal|armor_stand|copper_golem|#(helmet|chestplate|leggings|' + r'boots|outer|armor|decor|saddle|collar|wool|wool_undercoat|eyes|wind|inner|pattern|tendrils|' + r'heart|bioluminescent|pulsating_spots|water_patch|flag|cage|shell)$)') + + +def layer_constant(name): + """minecraft:cow_baby#main -> constant COW_BABY (the main layer of a model).""" + return name.split(':')[1].split('#')[0].upper() + + +def renderer_pairs(): + pairs = {} + pattern = re.compile(r'new (\w+)\(\s*(?:context|this\.context|\w*)\.bakeLayer\(ModelLayers\.(\w+)\)') + for path in sorted((CLIENT / 'renderer').rglob('*.java')): + for match in pattern.finditer(path.read_text()): + pairs[match.group(2)] = match.group(1) + return pairs + + +def layers(models): + chosen = {} + pairs = renderer_pairs() + for key in models: + if not key.endswith('#main') or SKIP_LAYERS.search(key): + continue + constant = layer_constant(key) + if constant in pairs: + chosen[key] = pairs[constant] + for key, cls in EXTRAS: + if key in models: + chosen[key] = cls + return chosen + + +def cases(layer): + rng = random.Random(0x414e494d + sum(map(ord, layer))) + baby = '_baby#' in layer + base_cases = [ + (0.0, 0.0, 0.0, 0.0, 0.0, 0.0), + (1.0, 0.5, 10.0, 0.0, 0.0, 0.0), + (3.7, 0.6, 57.3, 20.0, -15.0, 0.0), + (12.25, 1.0, 123.5, -35.0, 40.0, 0.0), + (7.5, 0.3, 33.3, 5.0, 5.0, 0.35), + (2.0, 0.0, 77.7, 45.0, -60.0, 0.8), + ] + for _ in range(14): + base_cases.append((rng.uniform(0, 30), rng.uniform(0, 1), rng.uniform(0, 400), + rng.uniform(-50, 50), rng.uniform(-70, 70), + rng.choice([0.0, rng.uniform(0.01, 0.99)]))) + cases_out = [] + for pos, speed, age, y, x, attack in base_cases: + cases_out.append({'walkAnimationPos': pos, 'walkAnimationSpeed': speed, 'ageInTicks': age, + 'yRot': y, 'xRot': x, 'swingAnimation': attack, 'isBaby': baby, 'ageScale': 0.5 if baby else 1.0, + 'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0}) + name = layer.split(':')[1].split('#')[0].removesuffix('_baby') + cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out] + yield from cases_out + yield from species_cases(layer, cases_out) + + +T, F = True, False +FOX = [{'isCrouching': T, 'crouchAmount': 0.8}, {'isSleeping': T}, {'isSitting': T}, {'isPouncing': T, 'crouchAmount': 0.6}, + {'isFaceplanted': T}, {'headRollAngle': 0.3}, {'isCrouching': T, 'isPouncing': T, 'crouchAmount': 0.4}] +ILLAGER = [{'armPose': pose, 'maxCrossbowChargeDuration': 25, 'ticksUsingItem': 10.0} + for pose in ['NEUTRAL', 'CROSSED', 'ATTACKING', 'SPELLCASTING', 'BOW_AND_ARROW', 'CROSSBOW_HOLD', + 'CROSSBOW_CHARGE', 'CELEBRATING']] + [{'isRiding': T, 'armPose': 'CROSSED'}] +FELINE = [{'isCrouching': T}, {'isSprinting': T}, {'isSitting': T}, {'lieDownAmount': 0.7, 'lieDownAmountTail': 0.5}, + {'relaxStateOneAmount': 0.6}, {'isSitting': T, 'lieDownAmount': 1.0, 'lieDownAmountTail': 0.2}] +ZOMBIE = [{'isAggressive': T}, {'isCrouching': T}, {'isPassenger': T}, {'isAggressive': T, 'isPassenger': T, 'isCrouching': T}] +SKELETON = ZOMBIE + [{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW'}, {'isHoldingBow': T}, + {'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW', 'isCrouching': T}] +PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': 12.0} + for pose in ['DEFAULT', 'DANCING', 'ATTACKING_WITH_MELEE_WEAPON', 'CROSSBOW_HOLD', 'CROSSBOW_CHARGE', 'ADMIRING_ITEM']] +EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7}, + {'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}] +WATER = [{'isInWater': T}, {'isInWater': F}] +SPECIES = { + 'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE, + 'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}], + 'hoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)], + 'zoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)], + 'ravager': [{'stunnedTicksRemaining': 20.0}, {'attackTicksRemaining': 8.0}, {'attackTicksRemaining': 3.0}, + {'roarAnimation': 0.5}], + 'vex': [{'isCharging': T}, {'isCharging': F}], + 'squid': [{'tentacleAngle': 0.7}], 'glow_squid': [{'tentacleAngle': 1.2}], + 'dolphin': [{'isMoving': T}, {'isMoving': F}], + 'cod': WATER, 'salmon': WATER, 'tropical_fish_small': WATER, + 'allay': [{'isDancing': T, 'isSpinning': T, 'spinningProgress': 0.6}, {'isDancing': T, 'isSpinning': F, 'spinningProgress': 0.2}, + {'holdingAnimationProgress': 0.8}, {'holdingAnimationProgress': 1.0}], + 'camel': [{'sitAnimationState': 2}, {'sitPoseAnimationState': 3}, {'sitUpAnimationState': 1}, {'idleAnimationState': 4}, + {'dashAnimationState': 2}, {'jumpCooldown': 20.0}], + 'chicken': [{'flap': 2.0, 'flapSpeed': 0.7}, {'flap': 5.3, 'flapSpeed': 1.0}], + 'wolf': [{'isSitting': T}, {'isAngry': T, 'tailAngle': 1.5393804}, {'shakeAnim': 0.9}, {'interest': 0.6}, + {'isSitting': T, 'shakeAnim': 0.5, 'interest': 0.3}], + 'zombie': ZOMBIE, 'husk': ZOMBIE, 'drowned': ZOMBIE, 'zombie_villager': ZOMBIE, 'zombified_piglin': ZOMBIE, 'giant': ZOMBIE, + 'skeleton': SKELETON, 'stray': SKELETON, 'wither_skeleton': SKELETON, 'bogged': SKELETON, + 'piglin': PIGLIN, 'piglin_brute': PIGLIN, + 'cat': FELINE, 'ocelot': FELINE, + 'creaking': [{'canMove': F}, {'attackAnimationState': 2}, {'invulnerabilityAnimationState': 3}, {'deathAnimationState': 1}], + 'evoker': ILLAGER, 'pillager': ILLAGER, 'vindicator': ILLAGER, + 'sheep': [{'eatTick': t} for t in (2, 10, 36, 39)], + 'guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}, {'tailAnimation': 0.0, 'spikesAnimation': 0.0}], + 'elder_guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}], + 'shulker': [{'peekAmount': v} for v in (0.0, 0.2, 0.5, 1.0)], + 'witch': [{'isHoldingItem': T}, {'isHoldingItem': F}], + 'goat': [{'hasLeftHorn': T, 'hasRightHorn': T}, {'hasLeftHorn': F, 'hasRightHorn': T, 'rammingXHeadRot': 0.6}, + {'hasLeftHorn': T, 'hasRightHorn': F}], + 'polar_bear': [{'standScale': 0.0}, {'standScale': 0.5}, {'standScale': 1.0}], + 'panda': [{'isUnhappy': T}, {'isSneezing': T, 'sneezeTime': 5}, {'isSneezing': T, 'sneezeTime': 16}, + {'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3}, + {'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}], + 'llama': [{'hasChest': T}, {'hasChest': F}], + 'trader_llama': [{'hasChest': T}, {'hasChest': F}], + 'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}], + 'strider': [{'isRidden': T}, {'isRidden': F}], + 'parrot': [{'pose': pose, 'flapAngle': 0.4} for pose in ['STANDING', 'FLYING', 'ON_SHOULDER', 'SITTING', 'PARTY']], + 'bee': [{'hasStinger': T}, {'hasStinger': F, 'isOnGround': T}, {'isAngry': T}, {'rollAmount': 0.6, 'isAngry': T}, + {'isOnGround': T, 'hasStinger': T}], + 'bat': [{'isResting': T, 'restAnimationState': 3}, {'flyAnimationState': 2}, {'isResting': F, 'flyAnimationState': 0}], + 'armadillo': [{'isHidingInShell': T}, {'isHidingInShell': T, 'rollUpAnimationState': 2}, + {'rollOutAnimationState': 4}, {'peekAnimationState': 1}], + 'axolotl': [{'playingDeadFactor': 0.0, 'inWaterFactor': 1.0, 'onGroundFactor': 0.0, 'movingFactor': 1.0}, + {'inWaterFactor': 1.0, 'movingFactor': 0.0}, {'onGroundFactor': 1.0, 'movingFactor': 1.0}, + {'onGroundFactor': 1.0, 'movingFactor': 0.0}, {'inWaterFactor': 0.5, 'onGroundFactor': 0.5, 'movingFactor': 0.5}, + {'playingDeadFactor': 1.0, 'inWaterFactor': 1.0}, + {'walkAnimationState': 1}, {'swimAnimation': 2}, {'idleOnGroundAnimationState': 3}, + {'idleUnderWaterAnimationState': 2}, {'idleUnderWaterOnGroundAnimationState': 1}, {'playDeadAnimationState': 4}], + 'frog': [{'isSwimming': T}, {'isSwimming': F}, {'jumpAnimationState': 2}, {'croakAnimationState': 1}, + {'tongueAnimationState': 3}, {'swimIdleAnimationState': 2, 'isSwimming': T}], + 'rabbit': [{'hopAnimationState': 2}, {'idleHeadTiltAnimationState': 1}], + 'fox': FOX, +} + + +# Render-state defaults that are not zero/false in vanilla. +DEFAULTS = {'creaking': {'canMove': T}, 'wolf': {'tailAngle': 0.6283185307179586}, 'axolotl': {'inWaterFactor': 1.0}, 'bee': {'hasStinger': T}, 'sheep': {'eatTick': 0}, + 'goat': {'hasLeftHorn': T, 'hasRightHorn': T}, 'parrot': {'pose': 'STANDING'}, + 'phantom': {'flapOffset': 21.0}, 'guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}, + 'elder_guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}} + + +def species_cases(layer, base_cases): + name = layer.split(':')[1].split('#')[0].removesuffix('_baby') + for extra in SPECIES.get(name, []): + for index in (2, 3, 6): + yield {**base_cases[index], **extra} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--filter', default='') + parser.add_argument('--detail', default='') + parser.add_argument('--tolerance', type=float, default=5e-7) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-entity-model-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + models = json.loads((resources / 'entity-models.json').read_text()) + chosen = {k: v for k, v in layers(models).items() if args.filter in k} + extra_cases = json.loads((Path(__file__).with_suffix('.cases.json')).read_text()) \ + if Path(__file__).with_suffix('.cases.json').exists() else {} + lines = [] + for layer, cls in sorted(chosen.items()): + for case in cases(layer): + lines.append(f'{layer} {cls}|{json.dumps(case)}') + for case in extra_cases.get(layer.split(':')[1].split('#')[0], []): + lines.append(f'{layer} {cls}|{json.dumps(case)}') + inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(lines) + '\n') + classes = build / 'classes'; classes.mkdir(exist_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java' + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', + inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--', + resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust), (len(vanilla), len(rust)) + errors, skipped, mismatched, checked = {}, set(), {}, 0 + for v, r in zip(vanilla, rust): + layer = v['layer'] + if 'error' in v: + errors[layer] = v['error']; continue + if 'skip' in r: + skipped.add(layer); continue + checked += 1 + bad = [] + for path, expected in v['parts'].items(): + got = r['parts'].get(path) + if got is None: + bad.append((path, 'missing in Horizon')); continue + names = ['x', 'y', 'z', 'xRot', 'yRot', 'zRot', 'xScale', 'yScale', 'zScale', 'visible', 'polys', 'vsum'] + for i, (a, b) in enumerate(zip(expected, got)): + if i == 11 and abs(a - b) <= 1e-3 * max(1, abs(a)): + continue + if i == 9: + a, b = bool(a), bool(b) + if a != b: + bad.append((path, f'visible {a} != {b}')) + continue + if abs(a - b) > args.tolerance * (1.0 + abs(a)): + bad.append((path, f'{names[i]} {a!r} != {b!r}')) + for path in r['parts']: + if path not in v['parts']: + bad.append((path, 'extra in Horizon')) + if bad: + mismatched.setdefault(layer, []).append((v['case'], bad)) + print(f'{checked} cases compared over {len(chosen) - len(skipped) - len(errors)} layers') + if errors: + print('oracle errors:'); [print(' ', k, v) for k, v in sorted(errors.items())] + if skipped: + print('layers without a Horizon species:', ', '.join(sorted(skipped))) + for layer, items in sorted(mismatched.items()): + parts = {} + for case, bad in items: + for path, why in bad: + parts.setdefault(path, (why, case)) + total = sum(1 for x in vanilla if x['layer'] == layer) + print(f'MISMATCH {layer}: {len(items)}/{total} cases, {len(parts)} parts') + detailed = args.detail == layer + for path, (why, case) in list(parts.items())[:(10 ** 6 if detailed else 4)]: + print(f' {path or ""}: {why}' + (f' case={json.dumps(case)}' if detailed else '')) + if mismatched or errors: + sys.exit(f'{len(mismatched)} layers differ from vanilla') + print('entity model parity ok') + + +if __name__ == '__main__': + main() From a7e63b5c18881859855d5d4890f820480a8fad5e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:02:13 +0200 Subject: [PATCH 2/4] WIP: environment render parity harness Work in progress on the environment rendering differential harness: a Rust fixture example, a vanilla oracle and the driver script. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/environment_fixture.rs | 64 ++++++++++++ .../parity/VanillaEnvironmentOracle.java | 98 +++++++++++++++++++ tools/test_environment_render_parity.py | 91 +++++++++++++++++ 3 files changed, 253 insertions(+) create mode 100644 crates/horizon-client/examples/environment_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java create mode 100755 tools/test_environment_render_parity.py diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs new file mode 100644 index 000000000..261411d51 --- /dev/null +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -0,0 +1,64 @@ +//! Environment attributes for differential tests against vanilla +//! (tools/test_environment_render_parity.py): reads "dimension ticks rain +//! thunder biome" lines and prints the sampled sky state as JSON lines. +//! +//! usage: environment_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + biome::Biomes, + environment::{Environment, apply_weather}, +}; +use std::{collections::HashMap, fmt::Write as _, fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let biomes = Biomes::load(root)?; + let mut environments: HashMap = HashMap::new(); + let mut out = String::new(); + for line in input.lines() { + let f: Vec<&str> = line.split(' ').collect(); + let dimension = f[0]; + let environment = match environments.entry(dimension.to_owned()) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => e.insert(Environment::load_dimension( + root, + dimension, + dimension == "overworld", + )?), + }; + let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4]))); + let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog); + if dimension == "overworld" { + apply_weather(&mut sky, f[2].parse()?, f[3].parse()?); + } + let v3 = |c: [f32; 3]| format!("[{:?},{:?},{:?}]", c[0], c[1], c[2]); + let v4 = |c: [f32; 4]| format!("[{:?},{:?},{:?},{:?}]", c[0], c[1], c[2], c[3]); + let mut row = format!("{{\"case\":\"{line}\""); + let mut put = |name: &str, value: String| { + let _ = write!(row, ",\"minecraft:{name}\":{value}"); + }; + put("visual/sky_color", v3(sky.sky_color)); + put("visual/fog_color", v3(sky.fog_color)); + put("visual/cloud_color", v4(sky.cloud_color)); + put("visual/sunrise_sunset_color", v4(sky.sunrise_color)); + put("visual/sky_light_factor", format!("{:?}", sky.sky_light_factor)); + put("visual/sky_light_color", v3(sky.sky_light_color)); + put("visual/block_light_tint", v3(sky.block_light_tint)); + put("visual/ambient_light_color", v3(sky.ambient_light_color)); + put("visual/sun_angle", format!("{:?}", sky.sun_angle)); + put("visual/moon_angle", format!("{:?}", sky.moon_angle)); + put("visual/star_angle", format!("{:?}", sky.star_angle)); + put("visual/star_brightness", format!("{:?}", sky.star_brightness)); + put("gameplay/sky_light_level", format!("{:?}", sky.sky_light_level * 15.0)); + put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); + put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); + out.push_str(&row); + out.push_str("}\n"); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java new file mode 100644 index 000000000..df1d7b028 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java @@ -0,0 +1,98 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.attribute.*; +import net.minecraft.world.clock.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3fc; +import org.joml.Vector4fc; + +/** + * Original oracle: builds the vanilla EnvironmentAttributeSystem (dimension + * layer, biome layer for one fixed biome, dimension timelines, weather layers) + * from the vanilla data pack and prints every visual/gameplay attribute for + * fixture lines "dimension ticks rain thunder biome". + */ +public final class VanillaEnvironmentOracle { + private static String fmt(Object v) { + if (v instanceof Vector3fc c) return String.format("[%s,%s,%s]", c.x(), c.y(), c.z()); + if (v instanceof Vector4fc c) return String.format("[%s,%s,%s,%s]", c.x(), c.y(), c.z(), c.w()); + if (v instanceof Float f) return f.toString(); + if (v instanceof Boolean b) return b.toString(); + if (v instanceof Enum e) return "\"" + e.name() + "\""; + return null; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) { + b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base)); + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Path in = Path.of(args[0]), out = Path.of(args[1]); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + staticTags.forEach(Registry.PendingTags::apply); + var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE); + var biomes = world.lookupOrThrow(Registries.BIOME); + try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) { + for (String line : Files.readAllLines(in, StandardCharsets.UTF_8)) { + String[] f = line.split(" "); + DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.withDefaultNamespace(f[0]))).value(); + long ticks = Long.parseLong(f[1]); + float rain = Float.parseFloat(f[2]), thunder = Float.parseFloat(f[3]); + Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.withDefaultNamespace(f[4]))).value(); + ClockManager clocks = h -> new ClockInstance() { + public long totalTicks() { return ticks; } + public float partialTick() { return 0.0F; } + public float rate() { return 1.0F; } + public boolean isPaused() { return false; } + }; + var b = EnvironmentAttributeSystem.builder(); + b.addConstantLayer(dim.attributes()); + for (EnvironmentAttribute attr : biome.getAttributes().keySet()) addBiome(b, attr, biome); + dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks)); + if (dim.hasSkyLight() && !dim.hasCeiling()) { + WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() { + public float rainLevel() { return rain; } + public float thunderLevel() { return thunder; } + }); + } + var system = b.build(); + StringBuilder sb = new StringBuilder("{\"case\":\"" + line + "\""); + for (var entry : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.entrySet()) { + EnvironmentAttribute attr = entry.getValue(); + String s = fmt(system.getValue(attr, Vec3.ZERO)); + if (s != null) sb.append(",\"").append(entry.getKey().identifier()).append("\":").append(s); + } + w.println(sb.append("}")); + } + } + } +} diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py new file mode 100755 index 000000000..006f540ec --- /dev/null +++ b/tools/test_environment_render_parity.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Compare Horizon's environment attributes with the vanilla 26.3 attribute system. + +The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack +(dimension attributes, one biome's attributes, the dimension timelines and the +weather layers) and prints every visual/gameplay attribute for a grid of +dimensions, world times, rain/thunder levels and biomes. +`examples/environment_fixture` samples the same cases through Horizon's +`Environment::sample` + `apply_weather`; every attribute Horizon computes must +agree with vanilla. + + test_environment_render_parity.py [--tolerance EPS] +""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + + +def cases(resources): + biomes = sorted(p.stem for p in (resources / 'data/minecraft/worldgen/biome').glob('*.json')) + out = [] + for dim in ['overworld', 'overworld_caves', 'the_nether', 'the_end']: + for ticks in list(range(0, 48000, 250)) + [23999, 24001, 1234567]: + for rain, thunder in [(0, 0), (0.5, 0), (1, 0), (1, 1), (0.7, 0.3)] if dim == 'overworld' else [(0, 0)]: + out.append(f'{dim} {ticks} {rain} {thunder} plains') + for dim in ['overworld', 'the_nether', 'the_end']: + for biome in biomes: + for ticks in (0, 6000, 12500, 18000): + for rain, thunder in [(0, 0), (1, 0.4)] if dim == 'overworld' else [(0, 0)]: + out.append(f'{dim} {ticks} {rain} {thunder} {biome}') + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--tolerance', type=float, default=2e-5) + args = parser.parse_args() + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / 'rust-environment-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(cases(resources)) + '\n') + classes = build / 'classes'; classes.mkdir(exist_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java' + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--', + resources, inputs, build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust), (len(vanilla), len(rust)) + bad = {} + uncovered = set() + for v, r in zip(vanilla, rust): + for key, expected in v.items(): + if key == 'case': + continue + if key not in r: + uncovered.add(key); continue + got = r[key] + pairs = zip(expected, got) if isinstance(expected, list) else [(expected, got)] + if any(abs(a - b) > args.tolerance * (1 + abs(a)) for a, b in pairs): + bad.setdefault(key, []).append((v['case'], expected, got)) + print(f'{len(vanilla)} cases compared') + for key, items in sorted(bad.items()): + print(f'MISMATCH {key}: {len(items)} cases, e.g. {items[0]}') + if uncovered: + print('attributes Horizon does not model:', ', '.join(sorted(uncovered))) + if bad: + sys.exit(f'{len(bad)} attributes differ from vanilla') + print('environment parity ok') + + +if __name__ == '__main__': + main() From 353d8491267e8e1f6c3a575a92d248cda53eed32 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:59 +0200 Subject: [PATCH 3/4] Match vanilla weather colours and dimension sky defaults The environment differential harness now passes for every dimension, biome, time and weather level. Weather colour multipliers are floored to 8-bit channels as vanilla does. A biome without its own fog or sky colour falls back to its dimension's, which fixes the End's dark purple fog, and the missing cloud colour is transparent. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/environment_fixture.rs | 30 +++++++++++------- crates/horizon-client/src/biome.rs | 16 +++------- crates/horizon-client/src/environment.rs | 31 +++++++++++++------ tools/test_environment_render_parity.py | 8 ++++- 4 files changed, 52 insertions(+), 33 deletions(-) diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs index 261411d51..3300df232 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -22,14 +22,13 @@ fn main() -> horizon_client::Result<()> { for line in input.lines() { let f: Vec<&str> = line.split(' ').collect(); let dimension = f[0]; - let environment = match environments.entry(dimension.to_owned()) { - std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), - std::collections::hash_map::Entry::Vacant(e) => e.insert(Environment::load_dimension( - root, - dimension, - dimension == "overworld", - )?), - }; + let environment = + match environments.entry(dimension.to_owned()) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => e.insert( + Environment::load_dimension(root, dimension, dimension == "overworld")?, + ), + }; let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4]))); let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog); if dimension == "overworld" { @@ -45,15 +44,24 @@ fn main() -> horizon_client::Result<()> { put("visual/fog_color", v3(sky.fog_color)); put("visual/cloud_color", v4(sky.cloud_color)); put("visual/sunrise_sunset_color", v4(sky.sunrise_color)); - put("visual/sky_light_factor", format!("{:?}", sky.sky_light_factor)); + put( + "visual/sky_light_factor", + format!("{:?}", sky.sky_light_factor), + ); put("visual/sky_light_color", v3(sky.sky_light_color)); put("visual/block_light_tint", v3(sky.block_light_tint)); put("visual/ambient_light_color", v3(sky.ambient_light_color)); put("visual/sun_angle", format!("{:?}", sky.sun_angle)); put("visual/moon_angle", format!("{:?}", sky.moon_angle)); put("visual/star_angle", format!("{:?}", sky.star_angle)); - put("visual/star_brightness", format!("{:?}", sky.star_brightness)); - put("gameplay/sky_light_level", format!("{:?}", sky.sky_light_level * 15.0)); + put( + "visual/star_brightness", + format!("{:?}", sky.star_brightness), + ); + put( + "gameplay/sky_light_level", + format!("{:?}", sky.sky_light_level * 15.0), + ); put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); out.push_str(&row); diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 5fd6f3e4b..1be7a4ce9 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -32,8 +32,9 @@ pub struct BiomeInfo { pub foliage: u32, pub dry_foliage: u32, pub water: u32, - pub sky: u32, - pub fog: u32, + pub sky: Option, + /// The biome's own fog colour attribute; otherwise the dimension's applies. + pub fog: Option, pub water_fog: u32, } pub struct Biomes { @@ -77,13 +78,6 @@ impl Biomes { let grass = colormap(root, "grass")?; let foliage = colormap(root, "foliage")?; let dry = colormap(root, "dry_foliage")?; - let dimension: Value = serde_json::from_slice(&fs::read( - root.join("data/minecraft/dimension_type/overworld.json"), - )?)?; - let default_fog = - color(&dimension["attributes"]["minecraft:visual/fog_color"]).unwrap_or(0xC0D8FF); - let default_sky = - color(&dimension["attributes"]["minecraft:visual/sky_color"]).unwrap_or(0x78A7FF); let mut list = Vec::new(); let mut names: Vec<_> = fs::read_dir(root.join("data/minecraft/worldgen/biome"))? .filter_map(|e| e.ok()) @@ -151,8 +145,8 @@ impl Biomes { dry_foliage: color(&effects["dry_foliage_color"]) .unwrap_or_else(|| sample(&dry, temperature, downfall, 0x5D4930)), water: color(&effects["water_color"]).unwrap_or(0x3F76E4), - sky: color(&attributes["minecraft:visual/sky_color"]).unwrap_or(default_sky), - fog: color(&attributes["minecraft:visual/fog_color"]).unwrap_or(default_fog), + sky: color(&attributes["minecraft:visual/sky_color"]), + fog: color(&attributes["minecraft:visual/fog_color"]), water_fog: color(&attributes["minecraft:visual/water_fog_color"]) .unwrap_or(0x050533), name, diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs index a7d87e75e..43c48af4e 100644 --- a/crates/horizon-client/src/environment.rs +++ b/crates/horizon-client/src/environment.rs @@ -229,7 +229,7 @@ impl Environment { self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) } /// Sky state for a time of day, with the biome's sky and fog colours as base values. - pub fn sample(&self, ticks: i64, biome_sky: u32, biome_fog: u32) -> Sky { + pub fn sample(&self, ticks: i64, biome_sky: Option, biome_fog: Option) -> Sky { let rgb = |c: u32| { [ (c >> 16 & 255) as f32 / 255.0, @@ -260,8 +260,14 @@ impl Environment { .map_or(0.0, |t| t.sample(ticks, self.period)[0]) }; Sky { - sky_color: three(v("minecraft:visual/sky_color", rgb(biome_sky))), - fog_color: three(v("minecraft:visual/fog_color", rgb(biome_fog))), + sky_color: three(v( + "minecraft:visual/sky_color", + biome_sky.map_or_else(|| self.base("minecraft:visual/sky_color"), rgb), + )), + fog_color: three(v( + "minecraft:visual/fog_color", + biome_fog.map_or_else(|| self.base("minecraft:visual/fog_color"), rgb), + )), sky_light_factor: scalar("minecraft:visual/sky_light_factor"), sky_light_color: three(v( "minecraft:visual/sky_light_color", @@ -279,7 +285,10 @@ impl Environment { .map_or([0.0; 4], |t| t.sample(ticks, self.period)), cloud_color: v( "minecraft:visual/cloud_color", - self.base("minecraft:visual/cloud_color"), + self.base + .get("minecraft:visual/cloud_color") + .copied() + .unwrap_or([0.0; 4]), ), sky_light_level: scalar("minecraft:gameplay/sky_light_level") / 15.0, fog_start: self @@ -304,24 +313,26 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) }; let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t; - let night = [0.48, 0.48, 1.0]; + // Vanilla stores these colours as 8-bit ARGB (`ARGB.colorFromFloat` floors). + let q = |v: f32| (v * 255.0).floor() / 255.0; + let night = [q(0.48), q(0.48), 1.0]; // (level, sky gray (brightness, factor), fog multiplier, cloud gray, alpha, sunrise multiplier) let layers = [ ( rain - thunder, (0.6, 0.75), - [0.5, 0.5, 0.6], + [q(0.5), q(0.5), q(0.6)], (0.24, 0.5), 0.3125, - [0.5, 0.5, 0.6], + [q(0.5), q(0.5), q(0.6)], ), ( thunder, (0.24, 0.94), - [0.25, 0.25, 0.3], + [q(0.25), q(0.25), q(0.3)], (0.095, 0.94), 0.527_343_75, - [0.25, 0.25, 0.3], + [q(0.25), q(0.25), q(0.3)], ), ]; for (level, (sb, sf), fog, (cb, cf), alpha, sunrise) in layers { @@ -347,7 +358,7 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) { sky.sky_light_color = lerp3( level, sky.sky_light_color, - lerp3(alpha, sky.sky_light_color, night), + lerp3(q(alpha), sky.sky_light_color, night), ); sky.sky_light_factor = lerp( level, diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 006f540ec..4a1979fc2 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -27,12 +27,18 @@ except ImportError: def cases(resources): biomes = sorted(p.stem for p in (resources / 'data/minecraft/worldgen/biome').glob('*.json')) out = [] - for dim in ['overworld', 'overworld_caves', 'the_nether', 'the_end']: + for dim in ['overworld', 'the_nether', 'the_end']: for ticks in list(range(0, 48000, 250)) + [23999, 24001, 1234567]: for rain, thunder in [(0, 0), (0.5, 0), (1, 0), (1, 1), (0.7, 0.3)] if dim == 'overworld' else [(0, 0)]: out.append(f'{dim} {ticks} {rain} {thunder} plains') + own = {'the_nether': {'nether_wastes', 'soul_sand_valley', 'crimson_forest', 'warped_forest', 'basalt_deltas'}, + 'the_end': {'the_end', 'small_end_islands', 'end_midlands', 'end_highlands', 'end_barrens'}} for dim in ['overworld', 'the_nether', 'the_end']: for biome in biomes: + if dim in own and biome not in own[dim]: + continue + if dim == 'overworld' and any(biome in b for b in own.values()): + continue for ticks in (0, 6000, 12500, 18000): for rain, thunder in [(0, 0), (1, 0.4)] if dim == 'overworld' else [(0, 0)]: out.append(f'{dim} {ticks} {rain} {thunder} {biome}') From f5fa9b5026b481b77e58beb9542141b4d4463611 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:09:59 +0200 Subject: [PATCH 4/4] Add night vision and torch flicker to the lightmap and rebuild the health HUD The lightmap now brightens with night vision and conduit water vision and flickers its block light like vanilla's extractor. The hearts, armour and food rows follow Hud.extractPlayerHealth: absorption rows, hardcore sprites, poison and wither tints, the regeneration hop, low-health shaking, the damage blink and hunger jitter, driven by vanilla's java.util.Random. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/fog.rs | 22 ++ crates/horizon-client/src/game.rs | 72 +++--- crates/horizon-client/src/game/health_hud.rs | 226 ++++++++++++++++++ crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/game/sculk.rs | 23 ++ crates/horizon-client/src/gfx.rs | 21 +- 6 files changed, 332 insertions(+), 33 deletions(-) create mode 100644 crates/horizon-client/src/game/health_hud.rs diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 4146de4f6..dffcf7280 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -68,8 +68,30 @@ pub struct FogState { pub water_vision_time: i32, /// `AtmosphericFogEnvironment.rainFogMultiplier`. pub rain_fog_multiplier: f32, + /// `LightmapRenderStateExtractor.blockLightFlicker`. + pub block_light_flicker: f32, + flicker_seed: u64, } impl FogState { + fn next_float(&mut self) -> f32 { + // splitmix64: the vanilla source is unseeded `RandomSource.create()`. + self.flicker_seed = self.flicker_seed.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.flicker_seed; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + ((z ^ (z >> 31)) >> 40) as f32 / (1u32 << 24) as f32 + } + /// `LightmapRenderStateExtractor.tick`: the torch light flickers. + pub fn tick_flicker(&mut self) { + let (a, b, c, d) = ( + self.next_float(), + self.next_float(), + self.next_float(), + self.next_float(), + ); + self.block_light_flicker += (a - b) * c * d * 0.1; + self.block_light_flicker *= 0.9; + } /// `LocalPlayer.aiStep`: water vision ramps up while the eye is in water. pub fn tick(&mut self, eye_in_water: bool) { self.water_vision_time = if eye_in_water { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 882905617..5c1422098 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -32,6 +32,7 @@ mod functions; mod game_mode; mod golems; mod growth; +mod health_hud; mod jukebox; mod lightning; mod loom; @@ -525,6 +526,7 @@ struct Game<'a> { fps_frames: u64, fps_at: Instant, ticks: u64, + health_hud: health_hud::HealthHud, error: Option, message: Option<(String, Instant)>, save: Arc, @@ -2928,7 +2930,7 @@ impl Game<'_> { let atlas = &self.res.atlas; if !self.creative && !spectator - && let Some(p) = &self.player + && let Some(p) = &mut self.player { // Experience bar and hearts/food (Gui.renderPlayerHealth). let saddled_mount = mounted @@ -2964,33 +2966,37 @@ impl Game<'_> { } batch.text(atlas, &text, x, y, rgba(128, 255, 32, 255), false); } - let health = p.health.health().ceil() as i32; - let top = h - 39.0; - for i in 0..10 { - let x = w / 2.0 - 91.0 + i as f32 * 8.0; - let y = if health <= 4 { - top + ((self.ticks + i as u64 * 7) % 3) as f32 - 1.0 - } else { - top - }; - batch.sprite(atlas, "gui/sprites/hud/heart/container", x, y); - let v = health - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/heart/full", x, y); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/heart/half", x, y); - } - } - let food = p.health.food.food; - for i in (0..10).filter(|_| !mounted) { - let x = w / 2.0 + 91.0 - i as f32 * 8.0 - 9.0; - batch.sprite(atlas, "gui/sprites/hud/food_empty", x, top); - let v = food - i * 2; - if v >= 2 { - batch.sprite(atlas, "gui/sprites/hud/food_full", x, top); - } else if v == 1 { - batch.sprite(atlas, "gui/sprites/hud/food_half", x, top); - } + let effects = &self.potions.effects; + let kind = if effects.get("poison").is_some() { + health_hud::HeartKind::Poisoned + } else if effects.get("wither").is_some() { + health_hud::HeartKind::Withered + } else { + health_hud::HeartKind::Normal + }; + let inputs = health_hud::HealthInputs { + tick: self.ticks, + health: p.health.health(), + max_health: p.attribute("minecraft:max_health").unwrap_or(20.0) as f32, + absorption: p.health.absorption(), + armor: p + .attribute("minecraft:armor") + .or_else(|_| p.attribute("armor")) + .unwrap_or(0.0) as i32, + food: p.health.food.food, + saturation: p.health.food.saturation, + kind, + regeneration: effects.get("regeneration").is_some(), + hunger: effects.get("hunger").is_some(), + hardcore: self.level.hardcore, + damage_cooldown: p.health.hurt.cooldown > 0, + show_food: !mounted, + }; + for (name, x, y) in + self.health_hud + .layout(&inputs, w as i32, h as i32, std::time::Instant::now()) + { + batch.sprite(atlas, &name, x as f32, y as f32); } } if self.debug { @@ -4220,10 +4226,13 @@ impl Game<'_> { return 11; } if self.dim == Dim::End { - let sky = self.res.end_environment.sample(self.world.day_time, 0, 0); + let sky = self + .res + .end_environment + .sample(self.world.day_time, None, None); return (15.0 - 15.0 * sky.sky_light_level).round() as i32; } - let mut sky = self.res.environment.sample(self.world.day_time, 0, 0); + let mut sky = self.res.environment.sample(self.world.day_time, None, None); let (rain, thunder) = self.world.weather.levels(1.0); horizon_client::environment::apply_weather(&mut sky, rain, thunder); // Level.updateSkyBrightness: darkening from the sky light level. @@ -6923,6 +6932,8 @@ impl Game<'_> { game_time: self.world.game_time as f32, ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), + night_vision: self.night_vision_intensity(), + block_flicker: self.res.fog.state.block_light_flicker, }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } @@ -7749,6 +7760,7 @@ pub fn run() -> Result<()> { screen: Screen::Playing, window: None, renderer: None, + health_hud: health_hud::HealthHud::default(), started: now, previous: now, frames: 0, diff --git a/crates/horizon-client/src/game/health_hud.rs b/crates/horizon-client/src/game/health_hud.rs new file mode 100644 index 000000000..4e9aaee0a --- /dev/null +++ b/crates/horizon-client/src/game/health_hud.rs @@ -0,0 +1,226 @@ +//! `Hud.extractPlayerHealth`: armour, hearts, food. The layout is computed as +//! a list of sprites so it can be tested without drawing. +use std::time::Instant; + +/// `java.util.Random`, for the HUD's per-tick jitter. +pub(super) struct JavaRandom(i64); +impl JavaRandom { + pub fn new(seed: i64) -> Self { + Self((seed ^ 0x5_DEEC_E66D) & ((1 << 48) - 1)) + } + fn next(&mut self, bits: u32) -> i32 { + self.0 = (self.0.wrapping_mul(0x5_DEEC_E66D).wrapping_add(0xB)) & ((1 << 48) - 1); + (self.0 >> (48 - bits)) as i32 + } + pub fn next_int(&mut self, bound: i32) -> i32 { + let mut r = self.next(31); + let m = bound - 1; + if bound & m == 0 { + return ((i64::from(bound) * i64::from(r)) >> 31) as i32; + } + let mut u = r; + loop { + r = u % bound; + if u.wrapping_sub(r).wrapping_add(m) >= 0 { + return r; + } + u = self.next(31); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum HeartKind { + Normal, + Poisoned, + Withered, + Absorbing, +} +impl HeartKind { + fn prefix(self) -> &'static str { + match self { + Self::Normal => "", + Self::Poisoned => "poisoned_", + Self::Withered => "withered_", + Self::Absorbing => "absorbing_", + } + } +} + +/// State kept between frames (`Hud.lastHealth`, `displayHealth`, ...). +pub(super) struct HealthHud { + last_health: i32, + display_health: i32, + last_health_time: Instant, + health_blink_time: i64, +} +impl Default for HealthHud { + fn default() -> Self { + Self { + last_health: 0, + display_health: 0, + last_health_time: Instant::now(), + health_blink_time: 0, + } + } +} + +pub(super) struct HealthInputs { + pub tick: u64, + pub health: f32, + pub max_health: f32, + pub absorption: f32, + pub armor: i32, + pub food: i32, + pub saturation: f32, + pub kind: HeartKind, + pub regeneration: bool, + pub hunger: bool, + pub hardcore: bool, + /// `damageCooldownTime > 0`. + pub damage_cooldown: bool, + /// A mount with its own hearts replaces the food bar. + pub show_food: bool, +} + +fn heart_sprite(kind: HeartKind, hardcore: bool, half: bool, blink: bool) -> String { + let (hc, h) = ( + if hardcore { "hardcore_" } else { "" }, + if half { "half" } else { "full" }, + ); + let b = if blink { "_blinking" } else { "" }; + format!("gui/sprites/hud/heart/{}{hc}{h}{b}", kind.prefix()) +} + +impl HealthHud { + /// Sprites (name, x, y) in draw order for a screen of `w` x `h` GUI pixels. + pub fn layout( + &mut self, + i: &HealthInputs, + w: i32, + h: i32, + now: Instant, + ) -> Vec<(String, i32, i32)> { + let mut out = Vec::new(); + let tick = i64::try_from(i.tick).unwrap_or(i64::MAX); + let current = i.health.ceil() as i32; + let blink = self.health_blink_time > tick && (self.health_blink_time - tick) / 3 % 2 == 1; + if current < self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 20; + } else if current > self.last_health && i.damage_cooldown { + self.last_health_time = now; + self.health_blink_time = tick + 10; + } + if now.duration_since(self.last_health_time).as_millis() > 1000 { + self.display_health = current; + self.last_health_time = now; + } + self.last_health = current; + let old = self.display_health; + let mut random = JavaRandom::new(i64::from((i.tick as i32).wrapping_mul(312_871))); + let (x_left, x_right, y_base) = (w / 2 - 91, w / 2 + 91, h - 39); + let max_health = i.max_health.max(old.max(current) as f32); + let absorption = i.absorption.ceil() as i32; + let rows = ((max_health + absorption as f32) / 2.0 / 10.0).ceil() as i32; + let row_height = (10 - (rows - 2)).max(3); + let offset_index = if i.regeneration { + (i.tick as i32).rem_euclid((max_health + 5.0).ceil() as i32) + } else { + -1 + }; + if i.armor > 0 { + let y = y_base - (rows - 1) * row_height - 10; + for n in 0..10 { + let name = match (n * 2 + 1).cmp(&i.armor) { + std::cmp::Ordering::Less => "armor_full", + std::cmp::Ordering::Equal => "armor_half", + std::cmp::Ordering::Greater => "armor_empty", + }; + out.push((format!("gui/sprites/hud/{name}"), x_left + n * 8, y)); + } + } + let containers = (max_health / 2.0).ceil() as i32; + let absorb_containers = (absorption as f32 / 2.0).ceil() as i32; + let container = |hardcore: bool, blink: bool| { + format!( + "gui/sprites/hud/heart/container{}{}", + if hardcore { "_hardcore" } else { "" }, + if blink { "_blinking" } else { "" } + ) + }; + for c in (0..containers + absorb_containers).rev() { + let (row, column) = (c / 10, c % 10); + let x = x_left + column * 8; + let mut y = y_base - row * row_height; + if current + absorption <= 4 { + y += random.next_int(2); + } + if c < containers && c == offset_index { + y -= 2; + } + out.push((container(i.hardcore, blink), x, y)); + let halves = c * 2; + if c >= containers { + let ah = halves - containers * 2; + if ah < absorption { + let kind = if i.kind == HeartKind::Withered { + i.kind + } else { + HeartKind::Absorbing + }; + out.push(( + heart_sprite(kind, i.hardcore, ah + 1 == absorption, false), + x, + y, + )); + } + } + if blink && halves < old { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == old, true), + x, + y, + )); + } + if halves < current { + out.push(( + heart_sprite(i.kind, i.hardcore, halves + 1 == current, false), + x, + y, + )); + } + } + if i.show_food { + let suffix = if i.hunger { "_hunger" } else { "" }; + for n in 0..10 { + let mut y = y_base; + if i.saturation <= 0.0 && (i.tick as i32).rem_euclid(i.food * 3 + 1) == 0 { + y += random.next_int(3) - 1; + } + let x = x_right - n * 8 - 9; + out.push((format!("gui/sprites/hud/food_empty{suffix}"), x, y)); + if n * 2 + 1 < i.food { + out.push((format!("gui/sprites/hud/food_full{suffix}"), x, y)); + } + if n * 2 + 1 == i.food { + out.push((format!("gui/sprites/hud/food_half{suffix}"), x, y)); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn java_random_matches_reference() { + // new Random(42).nextInt(10) sequence: 0, 3, 8, 4, 0. + let mut r = JavaRandom::new(42); + let v: Vec = (0..5).map(|_| r.next_int(10)).collect(); + assert_eq!(v, [0, 3, 8, 4, 0]); + } +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index c13973e95..c7605f257 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -172,6 +172,7 @@ impl Game<'_> { lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) } pub(super) fn tick_particles(&mut self) { + self.res.fog.state.tick_flicker(); let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index e2d985417..07fbfcfac 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1096,6 +1096,29 @@ impl Game<'_> { (modifier, pulse.max(0.0)) } + /// `LightmapRenderStateExtractor`: the night vision effect's intensity + /// (`GameRenderer.nightVisionScale`), or conduit power's water vision. + pub(super) fn night_vision_intensity(&self) -> f32 { + use horizon_client::fog::FogType; + if let Some(e) = self.potions.effects.get("night_vision") { + // MobEffectInstance.endsWithin(200); -1 is infinite. + return if e.duration < 0 || e.duration > 200 { + 1.0 + } else { + 0.7 + (e.duration as f32 * std::f32::consts::PI * 0.2).sin() * 0.3 + }; + } + if self.potions.effects.get("conduit_power").is_some() + && let Some(eye) = self.eye_position() + { + let in_water = + horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) + == FogType::Water; + return self.res.fog.state.water_vision(in_water); + } + 0.0 + } + /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index ce51c2475..d58550502 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -80,6 +80,10 @@ pub struct Frame<'a> { /// The darkness effect on the lightmap: the brightness it takes off the /// gamma option and the pulsing scale subtracted from the light. pub darkness: (f32, f32), + /// Night vision (or conduit water vision) intensity on the lightmap. + pub night_vision: f32, + /// Torch flicker added to the block light factor of 1.4. + pub block_flicker: f32, } pub struct Renderer { instance: wgpu::Instance, @@ -1077,7 +1081,14 @@ impl Renderer { * bob * Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y) } - fn update_lightmap(&self, sky: &Sky, darkness: f32, gamma: f32) { + fn update_lightmap( + &self, + sky: &Sky, + darkness: f32, + gamma: f32, + night_vision: f32, + flicker: f32, + ) { // lightmap.fsh: per (block, sky) level. let brightness = |level: f32| level / (4.0 - 3.0 * level); let mut pixels = [0u8; 16 * 16 * 4]; @@ -1085,9 +1096,11 @@ impl Renderer { for b in 0..16 { let block_level = b as f32 / 15.0; let sky_level = s as f32 / 15.0; - let block_brightness = brightness(block_level) * 1.4; + let block_brightness = brightness(block_level) * (1.4 + flicker); let sky_brightness = brightness(sky_level) * sky.sky_light_factor; - let mut color = Vec3::from(sky.ambient_light_color); + // NightVisionColor defaults to 0x999999. + let mut color = + Vec3::from(sky.ambient_light_color).max(Vec3::splat(0.6 * night_vision)); color += Vec3::from(sky.sky_light_color) * sky_brightness; let parabolic = (2.0 * block_level - 1.0).powi(2); let block_color = Vec3::from(sky.block_light_tint).lerp(Vec3::ONE, 0.9 * parabolic); @@ -1193,6 +1206,8 @@ impl Renderer { &frame.sky, frame.darkness.1, (self.gamma - frame.darkness.0).max(0.0), + frame.night_vision, + frame.block_flicker, ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32;