Minecraft: Java Edition 26.3 rewritten from scratch in Rust, checked against vanilla with 281 differential harnesses. Get it with the Horizon launcher.
Rust differential-testinggame-enginegamedevlinuxminecraftminecraft-javareimplementationrustvoxelvulkanwgpu
Pose mob models without allocating part names
Ludovic Mariec481f9c68aaf
diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rsindex 92215315f..405ba718e 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 crate::fast_hash::{FxHashMap, FxHashSet};use horizon_core::geometry::trig::Mth;use std::collections::HashMap;use std::f32::consts::{FRAC_PI_6, PI};@@ -101,15 +102,27 @@ impl AnimState {}pub fn end_tick(&mut self, _swinging: bool) {}}+/// A part name as `Poses` keys it: its Fx hash, so filling a pose map allocates+/// nothing (a mob farm resets one per layer per mob each frame). Names are short+/// and few per model; `no_two_part_names_share_a_key` checks every vanilla model.+#[inline]+pub(crate) fn key(name: &str) -> u64 {+ use std::hash::Hasher;+ let mut h = crate::fast_hash::FxHasher::default();+ h.write(name.as_bytes());+ // The length too, so "a" and "a\0" differ (str's own Hash adds a terminator).+ h.write_usize(name.len());+ h.finish()+}/// Part poses for one draw, keyed by part name.#[derive(Clone, Default)]pub struct Poses {- map: HashMap<String, [f32; 9]>,+ map: FxHashMap<u64, [f32; 9]>,dummy: [f32; 9],/// Parts with `skipDraw` set: their own cubes are not drawn, children are.- skipped: std::collections::HashSet<String>,+ skipped: FxHashSet<u64>,/// Parts with `visible` cleared: neither they nor their children draw.- hidden: std::collections::HashSet<String>,+ hidden: FxHashSet<u64>,}impl Poses {pub fn new(model: &Part) -> Self {@@ -120,9 +133,9 @@ impl Poses {/// Refills this for another model, keeping the map and the sets' capacity:/// a mob draws its body and every equipment layer each frame.pub fn reset(&mut self, model: &Part) {- fn walk(p: &Part, map: &mut HashMap<String, [f32; 9]>) {+ fn walk(p: &Part, map: &mut FxHashMap<u64, [f32; 9]>) {// ModelPart.createPartLookup fills its map with putIfAbsent: the first part keeps a name.- map.entry(p.name.clone()).or_insert(p.pose);+ map.entry(key(&p.name)).or_insert(p.pose);for c in &p.children {walk(c, map);}@@ -134,26 +147,26 @@ impl Poses {walk(model, &mut self.map);}pub fn get(&mut self, name: &str) -> &mut [f32; 9] {- match self.map.get_mut(name) {+ match self.map.get_mut(&key(name)) {Some(p) => p,None => &mut self.dummy,}}pub fn pose(&self, part: &Part) -> [f32; 9] {- self.map.get(&part.name).copied().unwrap_or(part.pose)+ self.map.get(&key(&part.name)).copied().unwrap_or(part.pose)}pub fn skip_draw(&mut self, name: &str) {- self.skipped.insert(name.to_owned());+ self.skipped.insert(key(name));}pub fn skips(&self, part: &Part) -> bool {self.skips_named(&part.name)}/// `skips` by the part's name.pub fn skips_named(&self, name: &str) -> bool {- self.skipped.contains(name)+ !self.skipped.is_empty() && self.skipped.contains(&key(name))}pub fn has(&self, name: &str) -> bool {- self.map.contains_key(name)+ self.map.contains_key(&key(name))}pub fn xrot(&mut self, n: &str, v: f32) {self.get(n)[3] = v;@@ -167,9 +180,9 @@ impl Poses {/// `ModelPart.visible = v`; a hidden part and its children do not draw.pub fn visible(&mut self, n: &str, v: bool) {if v {- self.hidden.remove(n);- } else if self.map.contains_key(n) {- self.hidden.insert(n.to_owned());+ self.hidden.remove(&key(n));+ } else if self.map.contains_key(&key(n)) {+ self.hidden.insert(key(n));}}pub fn is_hidden(&self, part: &Part) -> bool {@@ -177,7 +190,7 @@ impl Poses {}/// `is_hidden` by the part's name.pub fn is_hidden_named(&self, name: &str) -> bool {- self.hidden.contains(name)+ !self.hidden.is_empty() && self.hidden.contains(&key(name))}}/// The LivingEntityRenderState values setupAnim reads.@@ -1003,7 +1016,7 @@ mod flight_pose_tests {"left_leg",].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1011,13 +1024,13 @@ mod flight_pose_tests {};player_model_visibility(&mut p, 0, true);for part in ["body", "right_arm", "left_arm", "right_leg", "left_leg"] {- assert!(p.hidden.contains(part), "{part}");+ assert!(p.hidden.contains(&key(part)), "{part}");}- assert!(!p.hidden.contains("head") && !p.hidden.contains("hat"));+ assert!(!p.hidden.contains(&key("head")) && !p.hidden.contains(&key("hat")));// Back in another mode they all show, but for the layers the player hid.player_model_visibility(&mut p, 1 << 6, false);- assert!(!p.hidden.contains("body") && !p.hidden.contains("left_leg"));- assert!(p.hidden.contains("hat"));+ assert!(!p.hidden.contains(&key("body")) && !p.hidden.contains(&key("left_leg")));+ assert!(p.hidden.contains(&key("hat")));}#[test]fn blocking_arm_follows_the_head_with_limits_in_both_hands() {@@ -1030,7 +1043,7 @@ mod flight_pose_tests {let mut p = Poses {map: ["head", "right_arm", "left_arm"].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1087,7 +1100,7 @@ mod flight_pose_tests {"left_leg",].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1142,7 +1155,7 @@ mod flight_pose_tests {"body",].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1183,7 +1196,7 @@ mod flight_pose_tests {let make = || Poses {map: ["head", "right_arm", "left_arm", "right_leg", "left_leg"].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1289,7 +1302,7 @@ mod flight_pose_tests {let mut p = Poses {map: ["head", "right_arm", "left_arm"].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1310,7 +1323,7 @@ mod flight_pose_tests {let mut p = Poses {map: ["head", "right_arm", "left_arm"].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),@@ -1338,7 +1351,7 @@ mod flight_pose_tests {let make = || Poses {map: ["head", "right_arm", "left_arm"].into_iter()- .map(|n| (n.to_string(), [0.0; 9]))+ .map(|n| (key(n), [0.0; 9])).collect(),dummy: [0.0; 9],skipped: Default::default(),diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rsindex 4e3002bbc..2a5919ef6 100644--- a/crates/horizon-client/src/mobs/render.rs+++ b/crates/horizon-client/src/mobs/render.rs@@ -3084,6 +3084,170 @@ mod scroll_tests {]);}++ /// `anim::Poses` keys parts by a hash of their name: within any vanilla model, two+ /// different names never share one (they would share a pose).+ #[test]+ fn no_two_part_names_share_a_key() {+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../.local/horizon-client/26.3");+ if !root.join("entity-models.json").exists() {+ return;+ }+ fn names<'a>(p: &'a Part, out: &mut Vec<&'a str>) {+ out.push(&p.name);+ for c in &p.children {+ names(c, out);+ }+ }+ let types = super::super::MobTypes::load(&root).unwrap();+ let mut models = 0;+ for kind in types.types.values() {+ for model in std::iter::once(&kind.model).chain(kind.layers.values()) {+ let mut all = Vec::new();+ names(model, &mut all);+ let mut keys = std::collections::HashMap::new();+ for name in all {+ let other = *keys.entry(super::super::anim::key(name)).or_insert(name);+ assert_eq!(other, name, "{} shares a key", kind.id);+ }+ models += 1;+ }+ }+ assert!(models > 100);+ }++ /// The CPU cost of posing a mob farm (tools/stress_scenes.py `stress_mobs`): 1000 mobs of+ /// 8 kinds through `render_with`, as `mob_geometry` draws them each frame. Prints the median+ /// thread CPU time per frame (busy machines stretch wall time), the vertices and a hash of them (the same hash before and after a speed-up+ /// means the same picture). `cargo test --profile fast -p horizon-client --lib+ /// benchmark_mob_farm_geometry -- --ignored --nocapture`.+ #[test]+ #[ignore = "manual benchmark; needs the prepared resources"]+ fn benchmark_mob_farm_geometry() {+ use std::{hash::Hasher, hint::black_box, time::Instant};+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../.local/horizon-client/26.3");+ if !root.join("entity-models.json").exists() {+ return;+ }+ let types = super::super::MobTypes::load(&root).unwrap();+ let kinds = [+ "husk", "creeper", "cow", "pig", "sheep", "chicken", "villager", "spider",+ ]+ .map(|k| std::sync::Arc::new(types.types[&format!("minecraft:{k}")].clone()));+ let mobs: Vec<Mob> = (0..1000u32)+ .map(|i| {+ let (layer, row, col) = (i / 200, i / 20 % 10, i % 20);+ let at = horizon_core::geometry::Vec3::new(+ -14.25 + 1.5 * f64::from(col),+ 1.0 + 2.5 * f64::from(layer),+ 8.0 + 2.0 * f64::from(row),+ );+ let mut m = Mob::new(i + 1, kinds[i as usize % 8].clone(), at, 180.0);+ m.previous = at;+ m.age = i;+ m+ })+ .collect();+ let data = MobData {+ states: Vec::new(),+ placements: Default::default(),+ heightmaps: Default::default(),+ animations: Default::default(),+ biome_tags: Default::default(),+ entity_tags: Default::default(),+ villager_hats: Default::default(),+ cem: Default::default(),+ random_textures: Default::default(),+ emissive: Default::default(),+ blinks: Default::default(),+ pois: Default::default(),+ species_placements: Default::default(),+ };+ let atlas = |name: &str| {+ let h = name.len() as f32 / 64.0;+ Some([h, h, h + 0.25, h + 0.25])+ };+ let camera = glam::DVec3::new(0.5, 9.6, 0.5);+ let mut out = Vec::new();+ let frame = |out: &mut Vec<Vertex>| {+ out.clear();+ for m in &mobs {+ render_with(m, 0.5, camera, &atlas, 0xf0f0, &data, &[], out);+ }+ };+ frame(&mut out);+ let mut hash = std::collections::hash_map::DefaultHasher::new();+ hash.write(bytemuck::cast_slice(&out));+ // The thread's own CPU time where the platform gives it, else wall time.+ let timed = |f: &mut dyn FnMut()| {+ let (wall, cpu) = (Instant::now(), horizon_client_render::spans::thread_cpu());+ f();+ match (horizon_client_render::spans::thread_cpu(), cpu) {+ (Some(end), Some(start)) => (end - start).as_secs_f64() * 1000.0,+ _ => wall.elapsed().as_secs_f64() * 1000.0,+ }+ };+ let mut times = Vec::new();+ for _ in 0..30 {+ times.push(timed(&mut || frame(black_box(&mut out))));+ }+ times.sort_by(f64::total_cmp);+ println!(+ "mob farm: 1000 mobs, {} vertices, {:.3} ms/frame (median of 30, min {:.3}), hash {:016x}",+ out.len(),+ times[15],+ times[0],+ hash.finish()+ );+ // Where it goes: the body's poses alone (state, pose map, setupAnim), then the+ // body's vertices alone from those poses.+ let median = |mut f: Box<dyn FnMut() + '_>| {+ let mut t: Vec<f64> = (0..30).map(|_| timed(&mut f)).collect();+ t.sort_by(f64::total_cmp);+ t[15]+ };+ let posed: Vec<(std::sync::Arc<Part>, Poses)> = mobs+ .iter()+ .map(|m| {+ let model = m.kind.model.clone();+ let mut poses = Poses::new(&model);+ anim::setup(m, &anim::state(m, 0.5), &mut poses, &data.animations);+ (model, poses)+ })+ .collect();+ let poses_ms = median(Box::new(|| {+ for m in &mobs {+ let model = m.kind.model.clone();+ let mut poses = Poses::new(&model);+ anim::setup(m, &anim::state(m, 0.5), &mut poses, &data.animations);+ black_box(&poses);+ }+ }));+ let mut body = Vec::new();+ let draw_ms = median(Box::new(|| {+ body.clear();+ for (m, (model, poses)) in mobs.iter().zip(&posed) {+ let base = base_transform(m, 0.5, camera);+ draw(+ model,+ base,+ poses,+ [0.0, 0.0, 0.25, 0.25],+ u32::MAX,+ 0xf0f0,+ 0,+ &mut body,+ );+ }+ black_box(&body);+ }));+ println!(+ " body poses only {poses_ms:.3} ms; body vertices only {draw_ms:.3} ms ({} vertices)",+ body.len()+ );+ }}#[cfg(test)]