diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2a4969221..66d06aa84 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> { nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, + others_index: None, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d36e0adec..5a1ef99e8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -390,6 +390,7 @@ impl Game<'_> { player, others, others_grid: None, + others_index: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -402,7 +403,7 @@ impl Game<'_> { end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, - teams: self.mob_teams(), + teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), difficulty: self.local_difficulty( self.player @@ -503,9 +504,22 @@ impl Game<'_> { let mut keep = Vec::with_capacity(mobs.len()); let mut grid = horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); + // All but the snapshot is the same for every mob of the tick, so + // build it once: the player view and the teams scan every UUID. + let base = self.mob_world_base(&[]); + // Each mob keeps its snapshot slot all tick; the first slot of an + // id answers, as a scan would. + let mut index = horizon_client::fast_hash::FxHashMap::::default(); + for (i, s) in snapshot.iter().enumerate() { + index.entry(s.id).or_insert(i as u32); + } for i in 0..mobs.len() { - let mut w = self.mob_world_base(&snapshot); - w.others_grid = Some(&grid); + let mut w = MobWorld { + others: &snapshot, + others_grid: Some(&grid), + others_index: Some(&index), + ..base.clone() + }; let m = &mut mobs[i]; w.nearest_player = super::natural_spawning::nearest_player( &players, diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 68aabbbc6..6dda8e0ac 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -9,6 +9,7 @@ use horizon_client::{ mobs::{ Mob, MobWorld, Species, data::{self, MobData}, + seen_grid::SeenGrid, spawn_rules::{Dimension, SpawnLevel}, spawn_selection::{ self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest, @@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. pub(super) pending_ids: std::cell::RefCell>, + /// The game's mobs by box, built once a pass has asked more than + /// [`SCANNED_QUERIES`] box queries (the mobs do not change while it + /// holds the game); the first ones scan, as the build costs a few scans. + pub(super) boxes: std::cell::OnceCell, + pub(super) box_queries: std::cell::Cell, +} +const SCANNED_QUERIES: u32 = 8; +/// A mob not removed: its index in `Game::mobs`, box, alive, and whether +/// it is a living shulker. +type MobBox = (usize, Aabb, bool, bool); +fn mob_box(i: usize, m: &Mob) -> MobBox { + let alive = m.alive(); + ( + i, + m.bounds(), + alive, + alive && m.species() == Species::Shulker, + ) +} +/// The boxes of the game's mobs not removed, and a grid over them. +pub(super) struct MobBoxes { + entries: Vec, + grid: SeenGrid, +} +impl MobBoxes { + fn new(mobs: &[Mob]) -> Self { + let entries: Vec<_> = mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)) + .collect(); + let grid = SeenGrid::new(entries.iter().map(|e| e.1)); + Self { entries, grid } + } + /// The entries whose boxes meet `area` (and possibly a few more). + fn near(&self, area: Aabb) -> impl Iterator + '_ { + let mut near = Vec::new(); + let indexed = self.grid.candidates(area, &mut near); + let all = (!indexed).then(|| self.entries.iter()); + near.into_iter() + .map(|i| self.entries[i as usize]) + .chain(all.into_iter().flatten().copied()) + } } impl GameLevel<'_, '_> { + /// The mobs not removed whose boxes may meet `area` (callers test them). + fn mobs_near(&self, area: Aabb) -> Box + '_> { + let asked = self.box_queries.get() + 1; + self.box_queries.set(asked); + if asked <= SCANNED_QUERIES && self.boxes.get().is_none() { + return Box::new( + self.game + .mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)), + ); + } + Box::new( + self.boxes + .get_or_init(|| MobBoxes::new(&self.game.mobs)) + .near(area), + ) + } fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; Some(self.game.res.biomes().get(chunk.biome(x, y, z))) @@ -224,12 +289,9 @@ impl NaturalLevel for GameLevel<'_, '_> { // getEntityCollisions(null, box): living shulkers are solid. let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) - && !self.game.mobs.iter().any(|m| { - m.species() == Species::Shulker - && m.alive() - && !m.removed - && m.bounds().intersects(grown) - }) + && !self + .mobs_near(grown) + .any(|(_, b, _, shulker)| shulker && b.intersects(grown)) && !self .pending_ids .borrow() @@ -244,10 +306,8 @@ impl NaturalLevel for GameLevel<'_, '_> { !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self - .game - .mobs - .iter() - .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .any(|(_, b, alive, _)| alive && b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") @@ -289,10 +349,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self - .game - .mobs - .iter() - .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds)) .count(); let pending = self .pending_ids @@ -311,6 +369,8 @@ impl<'a> Game<'a> { players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), + boxes: Default::default(), + box_queries: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 99dae39a5..e01d6ed03 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -431,20 +431,18 @@ impl Game<'_> { self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). - pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { + pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> { let board = &self.score.board; if board.teams.is_empty() { return Default::default(); } horizon_client::mobs::Teams { - player: self.player_team().cloned(), + player: self.player_team(), mobs: self .persist .uuids .iter() - .filter_map(|(id, uuid)| { - Some((*id, board.players_team(&uuid_text(*uuid))?.clone())) - }) + .filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?))) .collect(), } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e87032f07..945269610 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1406,6 +1406,7 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +#[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, @@ -1420,6 +1421,8 @@ pub struct MobWorld<'a> { pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, + /// Where each id stands in `others`, when the caller keeps one. + pub others_index: Option<&'a crate::fast_hash::FxHashMap>, pub daylight: bool, pub game_time: i64, pub day_time: i64, @@ -1438,22 +1441,23 @@ pub struct MobWorld<'a> { pub world_seed: i64, /// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world). pub sea_level: i32, - /// The scoreboard teams of the player and the mobs (collision rules). - pub teams: Teams, + /// The scoreboard teams of the player and the mobs (collision rules), + /// shared: the mob ticks build them once a tick, not once a mob. + pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] -pub struct Teams { - pub player: Option, - pub mobs: HashMap, +pub struct Teams<'a> { + pub player: Option<&'a crate::scoreboard::Team>, + pub mobs: HashMap, } -impl Teams { - pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> { +impl<'a> Teams<'a> { + pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> { match who { - Who::Player => self.player.as_ref(), - Who::Mob(id) => self.mobs.get(&id), + Who::Player => self.player, + Who::Mob(id) => self.mobs.get(&id).copied(), } } } @@ -2139,3 +2143,286 @@ mod elytra_tests { assert!((wings.angles[1] - 0.08726646).abs() < 0.00001); } } +#[cfg(test)] +mod teams_tests { + use super::*; + use crate::save::uuid_text; + use crate::scoreboard::{Scoreboard, Team}; + + /// A board where every other mob is on the player's team, as with a + /// datapack that colours its mobs' names. + fn board(mobs: u32) -> (Scoreboard, HashMap) { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Steve", "red"); + let uuids: HashMap = (0..mobs) + .map(|id| (id, [id as i32, 7, -(id as i32), 11])) + .collect(); + for (id, uuid) in &uuids { + if id % 2 == 0 { + board.add_to_team(&uuid_text(*uuid), "red"); + } + } + (board, uuids) + } + /// `Game::mob_teams` as built for each mob before: owned clones of the teams. + fn owned(board: &Scoreboard, uuids: &HashMap) -> HashMap { + uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone()))) + .collect() + } + fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap) -> Teams<'a> { + Teams { + player: board.players_team("Steve"), + mobs: uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?))) + .collect(), + } + } + + #[test] + fn borrowed_teams_answer_as_the_clones() { + let (board, uuids) = board(40); + let teams = borrowed(&board, &uuids); + let old = owned(&board, &uuids); + for id in 0..41 { + assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}"); + } + assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red")); + } + + /// One tick's worth of team building: once per mob (before) against once. + #[test] + #[ignore] + fn teams_cost() { + for mobs in [100u32, 250, 500] { + let (board, uuids) = board(mobs); + let t = std::time::Instant::now(); + for _ in 0..mobs { + std::hint::black_box(owned(&board, &uuids)); + } + let before = t.elapsed(); + let t = std::time::Instant::now(); + let reps = 20; + for _ in 0..reps { + std::hint::black_box(borrowed(&board, &uuids)); + } + let after = t.elapsed() / reps; + println!( + "{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms", + before.as_secs_f64() * 1e3, + after.as_secs_f64() * 1e3 + ); + } + } +} +#[cfg(test)] +mod sensor_scan_tests { + use super::*; + use horizon_core::geometry::Vec3; + use serde_json::json; + + fn kind() -> Arc { + Arc::new(MobType { + id: "minecraft:cow".into(), + species: Species::Cow, + width: 0.9, + height: 1.4, + eye_height: 1.3, + category: "creature".into(), + max_health: 10.0, + speed: 0.2, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model: Arc::new(Part::parse("root", &json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }) + } + /// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a + /// server's farms; their snapshot and its grid. + fn herd(n: u32, side: f64) -> (Vec, seen_grid::SeenGrid) { + let kind = kind(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut pen = Vec3::ZERO; + let seen: Vec = (0..n) + .map(|id| { + if id % 20 == 0 { + pen = Vec3::new(next(side), 64.0, next(side)); + } + let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0)); + Mob::new(id, kind.clone(), at, 0.0).seen(None) + }) + .collect(); + let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds)); + (seen, grid) + } + /// `NearestLivingEntitySensor` over every mob, as the brains ran it. + fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec { + seen.iter() + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec { + let mut near = Vec::new(); + assert!(grid.candidates(area, &mut near)); + near.iter() + .map(|&i| &seen[i as usize]) + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + + #[test] + fn the_grid_finds_what_the_scan_finds() { + let (seen, grid) = herd(600, 160.0); + for me in &seen { + let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)); + assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area)); + } + } + + /// `MobWorld::seen` once per mob (a target, a breeding partner...), by + /// scan as before and by the tick's id index. + #[test] + #[ignore] + fn lookup_cost() { + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 256.0); + let index: crate::fast_hash::FxHashMap = seen + .iter() + .enumerate() + .map(|(i, s)| (s.id, i as u32)) + .collect(); + let wanted: Vec = (0..n).map(|i| (i * 7919) % n).collect(); + let t = std::time::Instant::now(); + let a: usize = wanted + .iter() + .filter_map(|&id| seen.iter().find(|s| s.id == id)) + .map(|s| s.id as usize) + .sum(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let b: usize = wanted + .iter() + .filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize])) + .map(|s| s.id as usize) + .sum(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms", + std::mem::size_of::() + ); + } + } + + /// Natural spawning's `isUnobstructed` box test against every mob (real + /// `Mob`s), by scan and by a grid built once for the pass. + #[test] + #[ignore] + fn spawn_box_cost() { + let kind = kind(); + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 384.0); + let mobs: Vec = seen + .iter() + .map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0)) + .collect(); + let mut seed = 7u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let queries: Vec = (0..100) + .map(|_| { + let (x, z) = (next(384.0), next(384.0)); + Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9)) + }) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = queries + .iter() + .map(|&q| { + mobs.iter() + .any(|m| m.alive() && !m.removed && m.bounds().intersects(q)) + }) + .collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let boxes: Vec = mobs.iter().map(|m| m.bounds()).collect(); + let grid = seen_grid::SeenGrid::new(boxes.iter().copied()); + let build = t.elapsed().as_secs_f64() * 1e3; + let mut near = Vec::new(); + let b: Vec = queries + .iter() + .map(|&q| { + assert!(grid.candidates(q, &mut near)); + near.iter().any(|&i| boxes[i as usize].intersects(q)) + }) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)" + ); + } + } + + /// One tick of sensing: a twentieth of the mobs fire their sensor. + #[test] + #[ignore] + fn sensor_cost() { + for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] { + let (seen, grid) = herd(n, side); + let time = |f: &dyn Fn(&Seen, Aabb) -> usize| { + let t = std::time::Instant::now(); + let mut found = 0; + for me in &seen { + found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0))); + } + (t.elapsed().as_secs_f64() * 1e3 / 20.0, found) + }; + let (before, a) = time(&|me, area| scan(&seen, me, area).len()); + let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len()); + assert_eq!(a, b); + println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms"); + } + } +} diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9920235a9..331870b4a 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 6afacb53a..dc80c6ea4 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -441,7 +441,7 @@ impl Goal for PufferfishPuff { .as_ref() .is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. - let mob = cx.w.others.iter().any(|s| { + let mob = cx.w.others_near(area).any(|s| { s.id != m.id && s.alive && !matches!( diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 13e6c8a44..fcfba832e 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -391,12 +391,11 @@ impl Goal for LeaveBlock { let target = cx.w.world.block(x, y, z); let below = cx.w.world.block(x, y - 1, z); let bf = cx.w.facts.get(below); - let free = !cx.w.others.iter().any(|s| { - s.bounds.intersects(Aabb::new( - Vec3::new(f64::from(x), f64::from(y), f64::from(z)), - Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), - )) - }); + let block = Aabb::new( + Vec3::new(f64::from(x), f64::from(y), f64::from(z)), + Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), + ); + let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block)); if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 9419a23ba..c12f9e7ee 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1,7 +1,11 @@ //! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, //! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; -use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + jmath, + random::RandomSource, +}; use std::sync::Arc; pub const MOVE: u8 = 1; @@ -970,8 +974,7 @@ impl Goal for LookAtPlayer { let (id, only) = (m.id, self.only); let at = Vec3::new(m.position.x, m.eye_y(), m.position.z); let candidates: Vec<(u32, Vec3)> = - cx.w.others - .iter() + cx.w.others_near(area) .filter(|s| s.id != id && s.alive && s.bounds.intersects(area)) .filter(|s| only.is_none_or(|o| s.species == o)) .map(|s| (s.id, s.position)) @@ -1902,7 +1905,12 @@ impl Goal for FollowParent { let species = m.species(); let pos = m.position; let mut best: Option<(u32, f64)> = None; - for s in cx.w.others.iter().filter(|s| { + // Every position in range puts the box's bottom face in this area. + let area = Aabb::new( + Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0), + Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0), + ); + for s in cx.w.others_near(area).filter(|s| { s.alive && s.species == species && !s.baby diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index d4d67660b..c41c34f11 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -68,7 +68,10 @@ impl Goal for DefendVillage { if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 { return false; } - let bad = cx.w.others.iter().any(|s| { + // A position inside `b` puts the box's bottom face there (one block + // wider, as the box test is strict). + let near = b.inflate(Vec3::new(1.0, 1.0, 1.0)); + let bad = cx.w.others_near(near).any(|s| { s.species == Species::Villager && s.alive && s.player_rep <= -100 diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 238653dad..eeb2c42f2 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index ef71b8f77..49bac4d9f 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { velocity: fling(p.position), }); } - for s in w.others.iter() { + for s in w.others_near(area) { if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) { continue; } diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 5b8500c0d..d401ea6da 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 41353fc83..518347e77 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index cc4110dd7..79bbaa30c 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -226,7 +226,13 @@ impl MobWorld<'_> { .chain(all.into_iter().flatten()) } pub fn seen(&self, id: u32) -> Option<&Seen> { - self.others.iter().find(|s| s.id == id) + match self.others_index { + Some(index) => index + .get(&id) + .and_then(|&i| self.others.get(i as usize)) + .filter(|s| s.id == id), + None => self.others.iter().find(|s| s.id == id), + } } /// Living mobs of the given species within `range` of `from`, nearest first. pub fn nearby<'s>( @@ -235,9 +241,15 @@ impl MobWorld<'_> { range: f64, pred: impl Fn(&Seen) -> bool + 's, ) -> impl Iterator + 's { + // A position within `range` puts the box's bottom face in this area + // (one block wider, as the box test is strict). + let r = range + 1.0; + let area = Aabb::new( + Vec3::new(from.x - r, from.y - r, from.z - r), + Vec3::new(from.x + r, from.y + r, from.z + r), + ); let mut v: Vec<&Seen> = self - .others - .iter() + .others_near(area) .filter(|s| { s.alive && (s.position.x - from.x).abs() <= range