Merge pull request #567 from ludovic111/perf/villager-poi-index
Villagers search an index of POI blocks instead of scanning every block
This commit is contained in:
@@ -132,6 +132,7 @@ pub mod particles;
|
||||
pub mod patrol;
|
||||
pub mod perf_overlay;
|
||||
pub mod pick_item;
|
||||
pub mod poi_sections;
|
||||
pub mod pose;
|
||||
pub mod post;
|
||||
pub mod projectiles;
|
||||
|
||||
@@ -924,8 +924,35 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize {
|
||||
}
|
||||
n
|
||||
}
|
||||
/// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in
|
||||
/// scan order: y, then z, then x. Only the indexed POI blocks of the sections
|
||||
/// are visited (`PoiManager.getInChunk`).
|
||||
fn chunk_pois(
|
||||
w: &MobWorld,
|
||||
(qx, qz): (i32, i32),
|
||||
y0: i32,
|
||||
y1: i32,
|
||||
mut visit: impl FnMut(Poi, [i32; 3]),
|
||||
) {
|
||||
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
|
||||
return;
|
||||
};
|
||||
let kind = |state: u32| poi_of_state(w, horizon_world::registry::BlockStateId(state));
|
||||
let min = crate::chunk::MIN_Y;
|
||||
for s in (y0 - min) >> 4..=(y1 - min) >> 4 {
|
||||
let section = &chunk.sections[s as usize];
|
||||
for &(i, poi) in w.world.pois.get((qx, s, qz), section, kind).iter() {
|
||||
let i = i32::from(i);
|
||||
let y = min + s * 16 + (i >> 8);
|
||||
if (y0..=y1).contains(&y) {
|
||||
visit(poi, [qx * 16 + (i & 15), y, qz * 16 + (i >> 4 & 15)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `PoiManager.getInRange` with `HAS_SPACE`, nearest first (`distSqr` to the
|
||||
/// block, ties in scan order), filtered by `accept`.
|
||||
/// block, ties in scan order: chunk by chunk, z then x, and y, z, x within),
|
||||
/// filtered by `accept`.
|
||||
fn pois_in_range(
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
@@ -940,62 +967,24 @@ fn pois_in_range(
|
||||
let chunks = radius.div_euclid(16) + 1;
|
||||
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
|
||||
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
|
||||
// Sections whose palette holds no POI state are skipped whole, as
|
||||
// PoiManager only visits sections with records: the same positions in
|
||||
// the same order, without reading and naming every block of the sphere.
|
||||
let kind = |state: u32| poi_of_state(w, horizon_world::registry::BlockStateId(state));
|
||||
for qz in cz - chunks..=cz + chunks {
|
||||
for qx in cx - chunks..=cx + chunks {
|
||||
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
|
||||
continue;
|
||||
};
|
||||
let holds: Vec<bool> = chunk
|
||||
.sections
|
||||
.iter()
|
||||
.map(|s| s.blocks.maybe_has(|v| kind(v).is_some()))
|
||||
.collect();
|
||||
for y in y0..=y1 {
|
||||
if !holds[((y - crate::chunk::MIN_Y) >> 4) as usize] {
|
||||
continue;
|
||||
chunk_pois(w, (qx, qz), y0, y1, |poi, p| {
|
||||
if (p[0] - c[0]).abs() > radius
|
||||
|| (p[2] - c[2]).abs() > radius
|
||||
|| dist_sqr(p, c) > r2
|
||||
|| !poi_matches(m, f, poi)
|
||||
|| tickets(m, w, p) >= poi.max_tickets()
|
||||
{
|
||||
return;
|
||||
}
|
||||
for z in qz * 16..qz * 16 + 16 {
|
||||
for x in qx * 16..qx * 16 + 16 {
|
||||
if (x - c[0]).abs() > radius || (z - c[2]).abs() > radius {
|
||||
continue;
|
||||
}
|
||||
let d = i64::from(x - c[0]).pow(2)
|
||||
+ i64::from(y - c[1]).pow(2)
|
||||
+ i64::from(z - c[2]).pow(2);
|
||||
if d > r2 {
|
||||
continue;
|
||||
}
|
||||
let state = chunk.block(x & 15, y, z & 15);
|
||||
if w.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
let Some(poi) = kind(state.0) else {
|
||||
continue;
|
||||
};
|
||||
if !poi_matches(m, f, poi) {
|
||||
continue;
|
||||
}
|
||||
let p = [x, y, z];
|
||||
if tickets(m, w, p) >= poi.max_tickets() {
|
||||
continue;
|
||||
}
|
||||
if accept(p) {
|
||||
found.push((poi, p));
|
||||
}
|
||||
}
|
||||
if accept(p) {
|
||||
found.push((poi, p));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
found.sort_by_key(|(_, p)| {
|
||||
i64::from(p[0] - c[0]).pow(2)
|
||||
+ i64::from(p[1] - c[1]).pow(2)
|
||||
+ i64::from(p[2] - c[2]).pow(2)
|
||||
});
|
||||
found.sort_by_key(|&(_, p)| dist_sqr(p, c));
|
||||
found
|
||||
}
|
||||
/// `PoiManager.exists(pos, predicate)`.
|
||||
@@ -3389,26 +3378,23 @@ fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 {
|
||||
manhattan_sq(a, b)
|
||||
}
|
||||
/// Every bed head within `radius` (`PoiManager.getInRange(HOME, ..., ANY)`),
|
||||
/// in scan order.
|
||||
/// in the order of a scan of the cube: y, then z, then x.
|
||||
fn homes_in_range(m: &Mob, w: &MobWorld, radius: i32) -> Vec<[i32; 3]> {
|
||||
let c = block_of(m.position);
|
||||
let r2 = i64::from(radius) * i64::from(radius);
|
||||
let mut out = Vec::new();
|
||||
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
|
||||
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
|
||||
for y in y0..=y1 {
|
||||
for z in c[2] - radius..=c[2] + radius {
|
||||
for x in c[0] - radius..=c[0] + radius {
|
||||
let p = [x, y, z];
|
||||
if dist_sqr(p, c) <= r2
|
||||
&& w.world.loaded(x, z)
|
||||
&& poi_at(w, x, y, z) == Some(Poi::Home)
|
||||
{
|
||||
for qz in (c[2] - radius) >> 4..=(c[2] + radius) >> 4 {
|
||||
for qx in (c[0] - radius) >> 4..=(c[0] + radius) >> 4 {
|
||||
chunk_pois(w, (qx, qz), y0, y1, |poi, p| {
|
||||
if poi == Poi::Home && dist_sqr(p, c) <= r2 {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_unstable_by_key(|p| (p[1], p[2], p[0]));
|
||||
out
|
||||
}
|
||||
/// `MoveToSkySeeingSpot.hasNoBlocksAbove`.
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! The points of interest of each resident section (`PoiSection`), so a
|
||||
//! search visits the few POI blocks of the sections in range instead of
|
||||
//! reading every block of them.
|
||||
//!
|
||||
//! Vanilla keeps its records up to date from `onBlockStateChange`; here a
|
||||
//! section's list is rebuilt from its blocks after any edit. Resident
|
||||
//! sections are immutable behind `Arc` and edited through `Arc::make_mut`, so
|
||||
//! a weak reference tells an edited or replaced section from the one the list
|
||||
//! was built from (see `random_tick_sections`), without keeping its blocks.
|
||||
use crate::{chunk::Section, fast_hash::FxHashMap};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
/// A section's POIs: the block index in the section (`y << 8 | z << 4 | x`)
|
||||
/// and its kind, in ascending index order.
|
||||
pub type SectionPois<T> = Arc<[(u16, T)]>;
|
||||
|
||||
struct Cached<T> {
|
||||
section: Weak<Section>,
|
||||
pois: SectionPois<T>,
|
||||
}
|
||||
/// Cached POI lists by section, `(chunk x, section index, chunk z)`.
|
||||
pub struct PoiSections<T> {
|
||||
sections: Mutex<Lists<T>>,
|
||||
}
|
||||
struct Lists<T> {
|
||||
by_section: FxHashMap<(i32, i32, i32), Cached<T>>,
|
||||
/// Size above which lists of sections no longer resident are dropped.
|
||||
prune_at: usize,
|
||||
}
|
||||
const MIN_PRUNE: usize = 4096;
|
||||
impl<T> Default for PoiSections<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sections: Mutex::new(Lists {
|
||||
by_section: FxHashMap::default(),
|
||||
prune_at: MIN_PRUNE,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T: Copy> PoiSections<T> {
|
||||
/// The POIs of `section`, whose block states `kind` classifies. `kind`
|
||||
/// must give the same answer for a state on every call.
|
||||
pub fn get(
|
||||
&self,
|
||||
key: (i32, i32, i32),
|
||||
section: &Arc<Section>,
|
||||
mut kind: impl FnMut(u32) -> Option<T>,
|
||||
) -> SectionPois<T> {
|
||||
let mut lists = self.sections.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(cached) = lists.by_section.get(&key)
|
||||
&& cached.section.as_ptr() == Arc::as_ptr(section)
|
||||
{
|
||||
return cached.pois.clone();
|
||||
}
|
||||
let pois: SectionPois<T> = if section.blocks.maybe_has(|v| kind(v).is_some()) {
|
||||
let mut states = [0u16; 4096];
|
||||
section.unpack(&mut states);
|
||||
states
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, &state)| kind(u32::from(state)).map(|poi| (i as u16, poi)))
|
||||
.collect()
|
||||
} else {
|
||||
Arc::from([])
|
||||
};
|
||||
if lists.by_section.len() >= lists.prune_at {
|
||||
lists.by_section.retain(|_, c| c.section.strong_count() > 0);
|
||||
lists.prune_at = (lists.by_section.len() * 2).max(MIN_PRUNE);
|
||||
}
|
||||
lists.by_section.insert(
|
||||
key,
|
||||
Cached {
|
||||
section: Arc::downgrade(section),
|
||||
pois: pois.clone(),
|
||||
},
|
||||
);
|
||||
pois
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::chunk::{Chunk, MIN_Y};
|
||||
|
||||
#[test]
|
||||
fn lists_follow_edits_and_replacement() {
|
||||
let index = PoiSections::<u8>::default();
|
||||
let kind = |v: u32| (v == 5 || v == 6).then_some(v as u8);
|
||||
let mut chunk = Arc::new(Chunk::empty(0, 0));
|
||||
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
|
||||
Arc::make_mut(&mut chunk).set(3, MIN_Y + 2, 1, 6);
|
||||
Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 5);
|
||||
let found = index.get((0, 0, 0), &chunk.sections[0], kind);
|
||||
assert_eq!(&*found, &[(0, 5), (2 << 8 | 1 << 4 | 3, 6)]);
|
||||
// Unchanged: the cached list, not a rescan.
|
||||
let again = index.get((0, 0, 0), &chunk.sections[0], |_| panic!("rescanned"));
|
||||
assert!(Arc::ptr_eq(&found, &again));
|
||||
// An edit in place (no other owner) still invalidates the list.
|
||||
Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 1);
|
||||
assert_eq!(
|
||||
&*index.get((0, 0, 0), &chunk.sections[0], kind),
|
||||
&[(2 << 8 | 1 << 4 | 3, 6)]
|
||||
);
|
||||
// So does replacing the section, or the chunk.
|
||||
Arc::make_mut(&mut chunk).sections[0] = Arc::new(Section::default());
|
||||
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
|
||||
let mut other = Chunk::empty(0, 0);
|
||||
other.set(1, MIN_Y, 1, 5);
|
||||
chunk = Arc::new(other);
|
||||
assert_eq!(
|
||||
&*index.get((0, 0, 0), &chunk.sections[0], kind),
|
||||
&[(1 << 4 | 1, 5)]
|
||||
);
|
||||
// An unused palette entry alone yields no POI.
|
||||
Arc::make_mut(&mut chunk).set(1, MIN_Y, 1, 2);
|
||||
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unloaded_sections_are_dropped() {
|
||||
let index = PoiSections::<u8>::default();
|
||||
let kind = |v: u32| (v == 5).then_some(5);
|
||||
let kept = Arc::new(Section::default());
|
||||
index.get((0, 0, 0), &kept, kind);
|
||||
for i in 0..MIN_PRUNE as i32 {
|
||||
index.get((1, i, 0), &Arc::new(Section::default()), kind);
|
||||
}
|
||||
let lists = index.sections.lock().unwrap();
|
||||
assert!(lists.by_section.len() <= 2);
|
||||
assert!(lists.by_section.contains_key(&(0, 0, 0)));
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,8 @@ pub struct World {
|
||||
/// Every block position written since the log was last drained, kept
|
||||
/// only while the world is open to the network (see `lan`).
|
||||
pub block_log: Option<Vec<(i32, i32, i32)>>,
|
||||
/// The villager POIs of each section (`PoiManager`'s sections).
|
||||
pub pois: crate::poi_sections::PoiSections<crate::mobs::villager_brain::Poi>,
|
||||
}
|
||||
/// ServerLevel weather state (advanceWeatherCycle).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
@@ -130,6 +132,7 @@ impl World {
|
||||
day_time: 1000,
|
||||
weather: Weather::default(),
|
||||
block_log: None,
|
||||
pois: Default::default(),
|
||||
}
|
||||
}
|
||||
/// A controlled blockstate scene for the native scene probes: material
|
||||
|
||||
Reference in New Issue
Block a user