use super::*;
#[test]
fn global_bits() {
assert_eq!(
GLOBAL_BITS,
if super::super::PROTOCOL >= 777 {
16
} else {
15
}
);
assert_eq!(ceil_log2(65), 7);
assert_eq!(ceil_log2(64), 6);
assert_eq!(ceil_log2(1), 0);
}
fn overworld() -> World {
let mut w = World::new(WorldConfig::default());
w.apply_registry(
"minecraft:dimension_type",
[("minecraft:overworld", None)].into_iter(),
);
w.enter_dimension("minecraft:overworld", 0, 8);
w
}
#[test]
fn day_clock_follows_the_dimension() {
let mut w = overworld();
assert_eq!(w.day_clock(), None, "no world_clock registry yet");
w.apply_registry(
"minecraft:world_clock",
[("minecraft:overworld", None), ("minecraft:the_end", None)].into_iter(),
);
assert_eq!(w.day_clock(), Some(0));
w.apply_registry(
"minecraft:dimension_type",
[
("minecraft:overworld", None),
("minecraft:the_nether", None),
("minecraft:the_end", None),
]
.into_iter(),
);
w.enter_dimension("minecraft:the_end", 2, 8);
assert_eq!(w.day_clock(), Some(1));
w.enter_dimension("minecraft:the_nether", 1, 8);
assert_eq!(w.day_clock(), None);
let mut c = ghast_protocol::nbt::Compound::default();
c.0.push(("min_y".into(), Tag::Int(0)));
c.0.push(("height".into(), Tag::Int(256)));
c.0.push(("default_clock".into(), Tag::String("the_end".into())));
let nbt = AnonNbt::from_tag(&Tag::Compound(c)).unwrap();
let t = DimensionType::from_nbt("x:custom", &nbt).unwrap();
assert_eq!(t.default_clock.as_deref(), Some("minecraft:the_end"));
}
fn chunk(cx: i32, cz: i32, top: u16, rest: u16) -> Bytes {
use bytes::BufMut;
use ghast_protocol::codec::McWrite;
let mut d = bytes::BytesMut::new();
for s in 0..24 {
d.put_i16(if s == 7 { 4096 } else { 0 });
d.put_i16(0);
if s == 7 {
d.put_u8(4);
d.put_varint(2);
d.put_varint(i32::from(rest));
d.put_varint(i32::from(top));
for w in 0..256 {
d.put_u64(if w >= 240 { 0x1111_1111_1111_1111 } else { 0 });
}
} else {
d.put_u8(0);
d.put_varint(0);
}
d.put_u8(0);
d.put_varint(0);
}
let mut b = bytes::BytesMut::new();
b.put_i32(cx);
b.put_i32(cz);
b.put_varint(0);
b.put_varint(d.len() as i32);
b.put_slice(&d);
b.put_varint(0);
b.freeze()
}
fn sec(w: &World, cx: i32, cz: i32) -> &Section {
&w.column(cx, cz).unwrap().sections()[7]
}
fn same_storage(a: &Section, b: &Section) -> bool {
use crate::paletted::Shared;
match (a, b) {
(Section::Shared1(x), Section::Shared1(y)) => Shared::ptr_eq(x, y),
(Section::Shared2(x), Section::Shared2(y)) => Shared::ptr_eq(x, y),
(Section::Shared4(x), Section::Shared4(y)) => Shared::ptr_eq(x, y),
(Section::Shared8(x), Section::Shared8(y)) => Shared::ptr_eq(x, y),
(Section::SharedDirect(x), Section::SharedDirect(y)) => Shared::ptr_eq(x, y),
_ => false,
}
}
fn chunk_with(cx: i32, cz: i32, palette: &[u16], index: impl Fn(usize) -> usize) -> Bytes {
use bytes::BufMut;
use ghast_protocol::codec::McWrite;
assert!((2..=16).contains(&palette.len()));
let mut d = bytes::BytesMut::new();
for s in 0..24 {
d.put_i16(if s == 7 { 4096 } else { 0 });
d.put_i16(0);
if s == 7 {
d.put_u8(4);
d.put_varint(palette.len() as i32);
for &p in palette {
d.put_varint(i32::from(p));
}
for w in 0..256 {
let mut x = 0u64;
for k in 0..16 {
x |= (index(w * 16 + k) as u64 & 15) << (4 * k);
}
d.put_u64(x);
}
} else {
d.put_u8(0);
d.put_varint(0);
}
d.put_u8(0);
d.put_varint(0);
}
let mut b = bytes::BytesMut::new();
b.put_i32(cx);
b.put_i32(cz);
b.put_varint(0);
b.put_varint(d.len() as i32);
b.put_slice(&d);
b.put_varint(0);
b.freeze()
}
fn array(w: &World, cx: i32, cz: i32) -> &Arc<[Section]> {
&w.column(cx, cz).unwrap().sections
}
fn update(w: &mut World, x: i32, y: i32, z: i32, raw: u16) -> Applied {
w.apply_block_change(&BlockChange {
location: ghast_protocol::BlockPos { x, y, z },
r#type: i32::from(raw),
})
}
fn update_many(
w: &mut World,
(cx, sy, cz): (i32, i32, i32),
recs: &[(i32, i32, i32, u16)],
) -> Applied {
w.apply_multi_block_change(&MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: cx,
z: cz,
y: sy,
},
records: recs
.iter()
.map(|&(x, y, z, s)| (i64::from(s) << 12) | i64::from((x << 8) | (z << 4) | y))
.collect(),
})
}
fn assert_same(plain: &World, w: &World) {
assert_eq!(plain.columns().len(), w.columns().len());
for (p, c) in plain.columns().iter() {
let d = w.column(p.x, p.z).expect("same columns");
assert_eq!(c.sections().len(), d.sections().len());
for (j, (a, b)) in c.sections().iter().zip(d.sections()).enumerate() {
if let (Section::Uniform(x), Section::Uniform(y)) = (a, b) {
assert_eq!(x, y, "{p:?} section {j}");
continue;
}
for i in 0..4096 {
assert_eq!(a.get(i), b.get(i), "{p:?} section {j} block {i}");
}
}
let bes = |c: &Column| {
let mut v: Vec<_> = c.block_entities().map(|(pos, _)| pos).collect();
v.sort_unstable();
v
};
assert_eq!(bes(c), bes(d), "{p:?} block entities");
}
}
const STONE: u16 = 1;
const DIRT: u16 = 10;
#[test]
fn worlds_share_one_section_and_one_array() {
let cache = SharedChunks::new();
let (mut a, mut b, mut plain) = (overworld(), overworld(), overworld());
a.set_shared_chunks(Some(cache.clone()));
b.set_shared_chunks(Some(cache.clone()));
let body = chunk(0, 0, STONE, DIRT);
for w in [&mut a, &mut b, &mut plain] {
assert_eq!(w.apply_map_chunk_body(&body).unwrap(), Applied::Changed);
}
assert!(sec(&a, 0, 0).is_shared() && !sec(&plain, 0, 0).is_shared());
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)), "decoded once");
assert!(Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)), "one array");
assert_eq!((cache.entries(), cache.sections()), (1, 1));
assert_eq!((cache.column_entries(), cache.columns()), (1, 1));
assert!(matches!(sec(&a, 0, 0), Section::Shared1(s) if s.holders() == 1));
assert_eq!(Arc::strong_count(array(&a, 0, 0)), 2);
assert!(!a.column(0, 0).unwrap().sections()[0].is_shared());
for (x, z) in [(1, 1), (5, 9)] {
for w in [&a, &b] {
assert_eq!(w.block_state(x, 63, z).unwrap().id(), STONE);
assert_eq!(w.block_state(x, 62, z).unwrap().id(), DIRT);
}
}
assert!(a.set_block_state(1, 63, 1, BlockState::AIR));
assert!(sec(&a, 0, 0).is_shared() && sec(&b, 0, 0).is_shared());
assert!(!same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert!(!Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)));
assert_eq!(a.block_state(1, 63, 1), Some(BlockState::AIR));
assert_eq!(b.block_state(1, 63, 1).unwrap().id(), STONE);
assert_eq!((cache.entries(), cache.sections()), (2, 2));
assert_eq!((cache.column_entries(), cache.columns()), (2, 2));
let before = Arc::as_ptr(array(&b, 0, 0));
assert!(b.set_block_state(5, 63, 5, BlockState::from_id(STONE).unwrap()));
assert_eq!(Arc::as_ptr(array(&b, 0, 0)), before);
assert_eq!((cache.entries(), cache.column_entries()), (2, 2));
assert!(b.set_block_state(2, 62, 2, BlockState::AIR));
assert_eq!((cache.entries(), cache.sections()), (2, 2));
assert_eq!((cache.column_entries(), cache.columns()), (2, 2));
assert_eq!(a.block_state(2, 62, 2).unwrap().id(), DIRT);
assert_eq!(b.block_state(2, 62, 2), Some(BlockState::AIR));
assert_eq!(b.block_state(1, 63, 1).unwrap().id(), STONE);
for i in 0..4096 {
let (x, y, z) = (i & 15, 48 + (i >> 8), (i >> 4) & 15);
let p = plain.block_state(x, y, z);
if (x, y, z) != (1, 63, 1) {
assert_eq!(a.block_state(x, y, z), p);
}
if (x, y, z) != (2, 62, 2) {
assert_eq!(b.block_state(x, y, z), p);
}
}
assert!(a.set_block_state(2, 62, 2, BlockState::AIR));
assert!(b.set_block_state(1, 63, 1, BlockState::AIR));
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert!(Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)));
assert_eq!((cache.entries(), cache.column_entries()), (1, 1));
drop((a, b));
assert_eq!((cache.entries(), cache.column_entries()), (0, 0));
}
#[test]
fn the_same_updates_keep_one_copy() {
let cache = SharedChunks::new();
let mut plain = overworld();
let mut ws = [overworld(), overworld(), overworld()];
for w in &mut ws {
w.set_shared_chunks(Some(cache.clone()));
}
let body = chunk(0, 0, STONE, DIRT);
plain.apply_map_chunk_body(&body).unwrap();
for w in &mut ws {
w.apply_map_chunk_body(&body).unwrap();
}
type Step = Box<dyn Fn(&mut World) -> Applied>;
let mut steps: Vec<Step> = vec![
Box::new(|w| update(w, 3, 63, 3, 0)),
Box::new(|w| update(w, 3, 62, 3, 7)),
Box::new(|w| update_many(w, (0, 3, 0), &[(1, 2, 3, 9), (4, 15, 6, 0), (1, 2, 4, 9)])),
Box::new(|w| update(w, 8, 64, 8, STONE)),
Box::new(|w| update_many(w, (0, 2, 0), &[(0, 0, 0, 5), (15, 15, 15, 6)])),
Box::new(|w| update(w, 3, 63, 3, STONE)),
];
for k in 0..40u16 {
steps.push(Box::new(move |w| {
update(w, i32::from(k % 16), 50, i32::from(k / 16), 100 + k)
}));
}
steps.push(Box::new(|w| {
let recs: Vec<_> = (0..300)
.map(|k| (k % 16, 5, (k / 16) % 16, 400 + k as u16))
.collect();
update_many(w, (0, 3, 0), &recs)
}));
let mut widths = std::collections::BTreeSet::new();
widths.insert(sec(&ws[0], 0, 0).bits());
for step in &steps {
let r = step(&mut plain);
assert_eq!(r, Applied::Changed);
for w in &mut ws {
assert_eq!(step(w), r);
}
for w in &ws {
assert_same(&plain, w);
assert!(Arc::ptr_eq(array(w, 0, 0), array(&ws[0], 0, 0)));
}
for j in 6..=8 {
let s = &array(&ws[0], 0, 0)[j];
assert!(
s.is_shared() || matches!(s, Section::Uniform(_)),
"{j}: {s:?}"
);
}
widths.insert(sec(&ws[0], 0, 0).bits());
assert_eq!(cache.entries(), cache.sections());
assert!(cache.sections() <= 3, "{}", cache.sections());
assert_eq!((cache.column_entries(), cache.columns()), (1, 1));
}
assert_eq!(widths.into_iter().collect::<Vec<_>>(), [1, 2, 4, 8, 16]);
drop(ws);
assert_eq!((cache.entries(), cache.column_entries()), (0, 0));
}
#[test]
fn updates_in_another_order_are_still_exact() {
let cache = SharedChunks::new();
let (mut a, mut b) = (overworld(), overworld());
let (mut pa, mut pb) = (overworld(), overworld());
a.set_shared_chunks(Some(cache.clone()));
b.set_shared_chunks(Some(cache.clone()));
let body = chunk(0, 0, STONE, DIRT);
for w in [&mut a, &mut b, &mut pa, &mut pb] {
w.apply_map_chunk_body(&body).unwrap();
}
for w in [&mut a, &mut pa] {
update(w, 1, 60, 1, 7);
update(w, 2, 60, 2, 8);
}
update(&mut b, 2, 60, 2, 8);
update(&mut pb, 2, 60, 2, 8);
assert!(!same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert_same(&pb, &b);
update(&mut b, 1, 60, 1, 7);
update(&mut pb, 1, 60, 1, 7);
assert_same(&pa, &a);
assert_same(&pb, &b);
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert!(Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)));
for (w, first, second) in [(&mut a, 20, 21), (&mut pa, 20, 21)] {
update(w, 9, 61, 9, first);
update(w, 9, 61, 9, second);
}
for (w, first, second) in [(&mut b, 21, 20), (&mut pb, 21, 20)] {
update(w, 9, 61, 9, first);
update(w, 9, 61, 9, second);
}
assert_eq!(a.block_state(9, 61, 9).unwrap().id(), 21);
assert_eq!(b.block_state(9, 61, 9).unwrap().id(), 20);
assert!(!same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert_same(&pa, &a);
assert_same(&pb, &b);
assert!(a.set_block_state(9, 61, 9, BlockState::AIR));
assert!(pa.set_block_state(9, 61, 9, BlockState::AIR));
assert_eq!(b.block_state(9, 61, 9).unwrap().id(), 20);
assert_same(&pb, &b);
for w in [&mut a, &mut b, &mut pa, &mut pb] {
update(w, 9, 61, 9, 0);
}
assert_same(&pa, &a);
assert_same(&pb, &b);
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert_eq!((cache.entries(), cache.column_entries()), (1, 1));
}
#[test]
fn a_sole_holder_changes_its_storage_in_place_under_a_new_key() {
let cache = SharedChunks::new();
let (mut a, mut b, mut plain) = (overworld(), overworld(), overworld());
a.set_shared_chunks(Some(cache.clone()));
b.set_shared_chunks(Some(cache.clone()));
let body = chunk(0, 0, STONE, DIRT);
a.apply_map_chunk_body(&body).unwrap();
plain.apply_map_chunk_body(&body).unwrap();
let storage = |w: &World| match sec(w, 0, 0) {
Section::Shared1(s) => std::ptr::from_ref::<crate::paletted::Packed1>(s).cast::<u8>(),
Section::Shared2(s) => std::ptr::from_ref::<crate::paletted::Packed2>(s).cast::<u8>(),
other => panic!("{other:?}"),
};
let (before, before_array) = (storage(&a), Arc::as_ptr(array(&a, 0, 0)));
update(&mut a, 4, 60, 4, STONE);
update(&mut plain, 4, 60, 4, STONE);
assert_eq!(storage(&a), before, "changed in place");
assert_eq!(Arc::as_ptr(array(&a, 0, 0)), before_array);
assert_eq!((cache.entries(), cache.column_entries()), (1, 1));
assert_same(&plain, &a);
b.apply_map_chunk_body(&body).unwrap();
assert!(!same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert!(!Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)));
assert_eq!(b.block_state(4, 60, 4).unwrap().id(), DIRT);
assert_eq!(a.block_state(4, 60, 4).unwrap().id(), STONE);
assert_eq!((cache.entries(), cache.column_entries()), (2, 2));
update(&mut b, 4, 60, 4, STONE);
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert!(Arc::ptr_eq(array(&a, 0, 0), array(&b, 0, 0)));
assert_eq!((cache.entries(), cache.column_entries()), (1, 1));
let shared = storage(&a);
update(&mut a, 5, 60, 5, STONE);
assert_ne!(storage(&a), shared);
assert_eq!(storage(&b), shared);
assert_eq!(b.block_state(5, 60, 5).unwrap().id(), DIRT);
let before = storage(&a);
update(&mut a, 6, 60, 6, 33);
update(&mut plain, 5, 60, 5, STONE);
update(&mut plain, 6, 60, 6, 33);
assert_ne!(storage(&a), before);
assert_same(&plain, &a);
assert_eq!((cache.entries(), cache.column_entries()), (2, 2));
drop((a, b));
assert_eq!((cache.entries(), cache.column_entries()), (0, 0));
}
#[test]
fn sections_a_world_owns_stay_its_own() {
let cache = SharedChunks::new();
let other = SharedChunks::new();
let body = chunk(0, 0, STONE, DIRT);
let mut a = overworld();
a.apply_map_chunk_body(&body).unwrap();
a.set_shared_chunks(Some(cache.clone()));
update(&mut a, 1, 60, 1, STONE);
assert!(!sec(&a, 0, 0).is_shared());
assert_eq!(a.block_state(1, 60, 1).unwrap().id(), STONE);
assert_eq!((cache.entries(), cache.column_entries()), (0, 0));
update(&mut a, 1, 70, 1, STONE);
assert!(array(&a, 0, 0)[8].is_shared());
assert_eq!((cache.entries(), cache.column_entries()), (1, 0));
let (mut b, mut c) = (overworld(), overworld());
b.set_shared_chunks(Some(other.clone()));
c.set_shared_chunks(Some(other.clone()));
b.apply_map_chunk_body(&body).unwrap();
c.apply_map_chunk_body(&body).unwrap();
b.set_shared_chunks(Some(cache.clone()));
update(&mut b, 2, 60, 2, STONE);
assert!(!sec(&b, 0, 0).is_shared() && sec(&c, 0, 0).is_shared());
assert_eq!(b.block_state(2, 60, 2).unwrap().id(), STONE);
assert_eq!(c.block_state(2, 60, 2).unwrap().id(), DIRT);
assert_eq!((other.entries(), other.sections()), (1, 1));
c.set_shared_chunks(None);
let mut d = overworld();
d.set_shared_chunks(Some(other.clone()));
d.apply_map_chunk_body(&body).unwrap();
assert!(Arc::ptr_eq(array(&c, 0, 0), array(&d, 0, 0)));
update(&mut c, 3, 60, 3, STONE);
assert!(!sec(&c, 0, 0).is_shared() && sec(&d, 0, 0).is_shared());
assert_eq!(d.block_state(3, 60, 3).unwrap().id(), DIRT);
assert_eq!(c.block_state(3, 60, 3).unwrap().id(), STONE);
let mut e = overworld();
e.apply_map_chunk_body(&body).unwrap();
let copy = e.column(0, 0).unwrap().clone();
update(&mut e, 4, 60, 4, STONE);
assert_eq!(copy.sections()[7].get(block_index(4, 60 + 64, 4)), DIRT);
assert_eq!(e.block_state(4, 60, 4).unwrap().id(), STONE);
}
#[test]
fn section_updates_drop_block_entities_like_an_unshared_world() {
let cache = SharedChunks::new();
let config = WorldConfig::default().with_block_entities(true);
let make = |shared: bool| {
let mut w = World::new(config);
w.apply_registry(
"minecraft:dimension_type",
[("minecraft:overworld", None)].into_iter(),
);
w.enter_dimension("minecraft:overworld", 0, 8);
w.set_shared_chunks(shared.then(|| cache.clone()));
w.apply_map_chunk_body(&chunk(0, 0, STONE, DIRT)).unwrap();
for (x, y, z) in [(1, 50, 1), (2, 50, 2), (3, 50, 3), (4, 70, 4)] {
let r = w.apply_tile_entity_data(&TileEntityData {
location: ghast_protocol::BlockPos { x, y, z },
action: 1,
nbt_data: Some(AnonNbt::from_bytes(Bytes::from_static(&[10, 0])).unwrap()),
});
assert_eq!(r, Applied::Changed);
}
w
};
let (mut plain, mut a, mut b) = (make(false), make(true), make(true));
let recs = [
(1, 2, 1, 5),
(2, 2, 2, DIRT),
(3, 2, 3, 5),
(3, 2, 3, DIRT),
(9, 9, 9, 6),
];
for w in [&mut plain, &mut a, &mut b] {
assert_eq!(update_many(w, (0, 3, 0), &recs), Applied::Changed);
assert_eq!(update(w, 4, 70, 4, STONE), Applied::Changed);
}
assert_eq!(plain.column(0, 0).unwrap().block_entities().count(), 1);
assert!(plain.block_entity(2, 50, 2).is_some());
assert_same(&plain, &a);
assert_same(&plain, &b);
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
let before = Arc::as_ptr(array(&a, 0, 0));
let recs = [(7, 7, 7, 5), (7, 7, 7, DIRT)];
for w in [&mut plain, &mut a] {
assert_eq!(update_many(w, (0, 3, 0), &recs), Applied::Changed);
}
assert_eq!(Arc::as_ptr(array(&a, 0, 0)), before);
assert_same(&plain, &a);
for w in [&mut plain, &mut a] {
assert_eq!(update_many(w, (0, 40, 0), &recs), Applied::Ignored);
assert_eq!(update_many(w, (0, -9, 0), &recs), Applied::Ignored);
assert_eq!(update_many(w, (0, 3, 0), &[]), Applied::Ignored);
assert_eq!(update_many(w, (5, 3, 0), &recs), Applied::Ignored);
}
}
#[test]
fn block_entity_data_is_copied_out_of_the_packet() {
let config = WorldConfig::default().with_block_entities(true);
let mut w = World::new(config);
w.apply_registry(
"minecraft:dimension_type",
[("minecraft:overworld", None)].into_iter(),
);
w.enter_dimension("minecraft:overworld", 0, 8);
let mut body = chunk(0, 0, STONE, DIRT).to_vec();
body.pop();
body.extend_from_slice(&[1, (3 << 4) | 4, 0, 50, 7, 10, 0]);
let body = Bytes::from(body);
w.apply_map_chunk_body(&body).unwrap();
let mut buffer = vec![0u8; 4096];
buffer[1000..1002].copy_from_slice(&[10, 0]);
let buffer = Bytes::from(buffer);
let r = w.apply_tile_entity_data(&TileEntityData {
location: ghast_protocol::BlockPos { x: 5, y: 51, z: 6 },
action: 1,
nbt_data: Some(AnonNbt::from_bytes(buffer.slice(1000..1002)).unwrap()),
});
assert_eq!(r, Applied::Changed);
let outside = |held: &Bytes, of: &Bytes| {
let (p, start) = (held.as_ptr() as usize, of.as_ptr() as usize);
p < start || p >= start + of.len()
};
for (pos, source) in [((3, 50, 4), &body), ((5, 51, 6), &buffer)] {
let Some(BlockEntity::Nbt { nbt, .. }) = w.block_entity(pos.0, pos.1, pos.2) else {
panic!("no block entity at {pos:?}");
};
assert_eq!(&nbt[..], &[10, 0]);
assert!(outside(nbt, source), "{pos:?} holds the packet buffer");
}
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
fn below(&mut self, n: u64) -> u64 {
(self.next() >> 33) % n
}
}
#[derive(Debug, Clone)]
enum Op {
Chunk(i32, u8),
Unload(i32),
Update(i32, i32, i32, u16),
Many(i32, i32, Vec<(i32, i32, i32, u16)>),
BlockEntity(i32, i32, i32),
}
impl Op {
fn random(r: &mut Rng) -> Op {
let state = |r: &mut Rng| match r.below(4) {
0 => 0,
1 => [STONE, DIRT][r.below(2) as usize],
_ => r.below(40) as u16,
};
let cx = r.below(2) as i32;
match r.below(20) {
0 => Op::Chunk(cx, r.below(4) as u8),
1 => Op::Unload(cx),
2 => Op::BlockEntity(cx * 16 + r.below(3) as i32, 50, r.below(3) as i32),
3..=9 => {
let most = if r.below(8) == 0 { 400 } else { 6 };
let n = 1 + r.below(most) as usize;
let side = if r.below(3) == 0 { 2 } else { 16 };
let recs = (0..n)
.map(|_| {
(
r.below(side) as i32,
r.below(side) as i32,
r.below(side) as i32,
state(r),
)
})
.collect();
Op::Many(cx, 1 + r.below(4) as i32, recs)
}
_ => Op::Update(
cx * 16 + r.below(3) as i32,
30 + r.below(50) as i32,
r.below(3) as i32,
state(r),
),
}
}
fn apply(&self, w: &mut World) -> Result<Applied, WorldError> {
Ok(match self {
Op::Chunk(cx, 0) => w.apply_map_chunk_body(&chunk(*cx, 0, STONE, DIRT))?,
Op::Chunk(cx, 1) => w.apply_map_chunk_body(&chunk(*cx, 0, DIRT, STONE))?,
Op::Chunk(cx, 2) => {
let palette: Vec<u16> = (0..16).map(|k| 50 + k).collect();
w.apply_map_chunk_body(&chunk_with(*cx, 0, &palette, |i| (i * 7) % 16))?
}
Op::Chunk(cx, _) => {
w.apply_map_chunk_body(&chunk_with(*cx, 0, &[STONE, DIRT], |i| i % 3))?
}
Op::Unload(cx) => w.apply_unload_chunk(&UnloadChunk {
chunk_z: 0,
chunk_x: *cx,
}),
Op::Update(x, y, z, s) => update(w, *x, *y, *z, *s),
Op::Many(cx, sy, recs) => update_many(w, (*cx, *sy, 0), recs),
Op::BlockEntity(x, y, z) => w.apply_tile_entity_data(&TileEntityData {
location: ghast_protocol::BlockPos {
x: *x,
y: *y,
z: *z,
},
action: 1,
nbt_data: Some(AnonNbt::from_bytes(Bytes::from_static(&[10, 0])).unwrap()),
}),
})
}
}
fn bot(cache: Option<&SharedChunks>) -> World {
let mut w = World::new(WorldConfig::default().with_block_entities(true));
w.apply_registry(
"minecraft:dimension_type",
[("minecraft:overworld", None)].into_iter(),
);
w.enter_dimension("minecraft:overworld", 0, 8);
w.set_shared_chunks(cache.cloned());
w
}
#[test]
fn random_packets_read_like_unshared_worlds() {
let (cache, other) = (SharedChunks::new(), SharedChunks::new());
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
let mut shared: Vec<World> = (0..4).map(|_| bot(Some(&cache))).collect();
let mut plain: Vec<World> = (0..4).map(|_| bot(None)).collect();
let (mut met, mut most) = (0usize, 0usize);
for step in 0..2500 {
let op = Op::random(&mut r);
let mask = if r.below(4) == 0 { r.below(16) } else { 15 };
for k in 0..4 {
if mask & (1 << k) == 0 {
continue;
}
let want = op.apply(&mut plain[k]).map_err(|e| e.to_string());
let got = op.apply(&mut shared[k]).map_err(|e| e.to_string());
assert_eq!(got, want, "step {step} world {k}: {op:?}");
}
if r.below(200) == 0 {
let k = r.below(4) as usize;
let to = [None, Some(&cache), Some(&other)][r.below(3) as usize];
shared[k].set_shared_chunks(to.cloned());
}
for k in 0..4 {
assert_same(&plain[k], &shared[k]);
}
for k in 1..4 {
if let (Some(a), Some(b)) = (shared[0].column(0, 0), shared[k].column(0, 0)) {
met += usize::from(Arc::ptr_eq(&a.sections, &b.sections));
}
}
most = most.max(cache.sections());
assert!(cache.sections() <= 4 * 2 * 5, "{}", cache.sections());
}
assert!(met > 300 && most > 3, "{met} {most}");
drop(shared);
assert_eq!((cache.entries(), cache.columns()), (0, 0));
assert_eq!((other.entries(), other.columns()), (0, 0));
assert!(cache.column_entries() + other.column_entries() <= 8);
}
#[test]
fn random_packets_on_threads_read_like_unshared_worlds() {
let cache = SharedChunks::new();
std::thread::scope(|s| {
for t in 0..4u64 {
let cache = cache.clone();
s.spawn(move || {
let mut r = Rng(0x1234_5678_9abc_def1 + t / 2);
let (mut shared, mut plain) = (bot(Some(&cache)), bot(None));
for step in 0..4000 {
let op = Op::random(&mut r);
let want = op.apply(&mut plain).map_err(|e| e.to_string());
let got = op.apply(&mut shared).map_err(|e| e.to_string());
assert_eq!(got, want, "thread {t} step {step}: {op:?}");
if step % 16 == 0 {
assert_same(&plain, &shared);
}
}
assert_same(&plain, &shared);
});
}
});
assert_eq!(cache.entries(), 0);
assert_eq!(cache.columns(), 0);
}
#[test]
fn unload_frees_the_entry() {
let cache = SharedChunks::new();
let (mut a, mut b) = (overworld(), overworld());
a.set_shared_chunks(Some(cache.clone()));
b.set_shared_chunks(Some(cache.clone()));
for w in [&mut a, &mut b] {
w.apply_map_chunk_body(&chunk(0, 0, STONE, DIRT)).unwrap();
w.apply_map_chunk_body(&chunk(1, 0, DIRT, STONE)).unwrap();
}
assert_eq!(cache.entries(), 2);
assert!(cache.heap_bytes() > 2 * 512);
let unload = |w: &mut World, x| {
w.apply_unload_chunk(&UnloadChunk {
chunk_z: 0,
chunk_x: x,
})
};
assert_eq!(unload(&mut a, 0), Applied::Changed);
assert_eq!(cache.entries(), 2, "b still holds (0, 0)");
assert_eq!(unload(&mut b, 0), Applied::Changed);
assert_eq!(cache.entries(), 1);
b.clear();
assert_eq!(cache.entries(), 1, "a still holds (1, 0)");
drop(a);
assert_eq!((cache.entries(), cache.sections()), (0, 0));
let mut c = overworld();
c.set_shared_chunks(Some(SharedChunks::new()));
c.apply_map_chunk_body(&chunk(0, 0, STONE, DIRT)).unwrap();
c.set_shared_chunks(None);
assert!(sec(&c, 0, 0).is_shared());
assert_eq!(c.block_state(3, 63, 3).unwrap().id(), STONE);
drop(c);
}
#[test]
fn a_later_full_chunk_replaces_shared_sections() {
let cache = SharedChunks::new();
let (mut a, mut b) = (overworld(), overworld());
a.set_shared_chunks(Some(cache.clone()));
b.set_shared_chunks(Some(cache.clone()));
a.apply_map_chunk_body(&chunk(0, 0, STONE, DIRT)).unwrap();
b.apply_map_chunk_body(&chunk(0, 0, STONE, DIRT)).unwrap();
a.apply_map_chunk_body(&chunk(0, 0, DIRT, STONE)).unwrap();
assert_eq!(cache.entries(), 2);
assert_eq!(a.block_state(4, 63, 4).unwrap().id(), DIRT);
assert_eq!(b.block_state(4, 63, 4).unwrap().id(), STONE);
assert!(!same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
b.apply_map_chunk_body(&chunk(0, 0, DIRT, STONE)).unwrap();
assert!(same_storage(sec(&a, 0, 0), sec(&b, 0, 0)));
assert_eq!(cache.entries(), 1);
b.apply_map_chunk_body(&chunk(3, -2, DIRT, STONE)).unwrap();
assert!(same_storage(sec(&a, 0, 0), sec(&b, 3, -2)));
assert_eq!(cache.entries(), 1);
}
#[test]
fn malformed_sections_are_not_stored() {
let cache = SharedChunks::new();
let mut a = overworld();
a.set_shared_chunks(Some(cache.clone()));
let mut body = chunk(0, 0, STONE, DIRT).to_vec();
let at = body
.windows(4)
.position(|w| w == [4, 2, DIRT as u8, STONE as u8])
.unwrap();
body[at + 1] = 1;
body.remove(at + 3);
let n = body.len();
let err = a.apply_map_chunk_body(&Bytes::from(body));
assert!(err.is_err(), "{n} {err:?}");
assert!(a.column(0, 0).is_none());
assert_eq!(cache.entries(), 0);
}
#[test]
fn batch_size_matches_vanilla_formula() {
let mut b = ChunkBatchSize::default();
assert_eq!(b.desired_chunks_per_tick(), 3.5);
b.on_batch_start(0);
let v = b.on_batch_finished(10, 1_000_000);
let agg = (2_000_000.0 + 2_000_000.0 / 3.0) / 2.0;
assert_eq!(v, (7_000_000.0 / agg) as f32);
assert_eq!(b.on_batch_finished(0, 5), v);
}