Merge pull request #706 from ludovic111/perf/chunk-block-entity-cache

Chunk packets: keep each section's block entity blocks with its bytes
This commit is contained in:
Ludovic Marie
2026-10-17 16:31:21 +02:00
committed by GitHub
+108 -32
View File
@@ -116,12 +116,16 @@ struct Heights {
struct Encoded {
section: std::sync::Weak<Section>,
non_air: bool,
/// LevelChunkSection.write, and whether it holds block entity blocks.
wire: Option<(Arc<[u8]>, bool)>,
/// LevelChunkSection.write, and its block entity blocks.
wire: Option<(Arc<[u8]>, Entities)>,
/// The section's light as the wire's two DataLayers, when not uniform.
light: Option<Arc<Layers>>,
}
/// A section's blocks that have a block entity type, as (index, state) in
/// index order (y, then z, then x).
type Entities = Arc<[(u16, u16)]>;
/// One section's light as DataLayers (two blocks per byte, the even one in
/// the low nibble), and whether each holds any light.
struct Layers {
@@ -299,14 +303,14 @@ impl ChunkEncoder {
}
/// A section on the wire, from the cache or encoded now.
fn section_wire(&self, section: &Arc<Section>) -> (Arc<[u8]>, bool) {
fn section_wire(&self, section: &Arc<Section>) -> (Arc<[u8]>, Entities) {
if let Some(wire) = self.cached(section, |e| e.wire.clone()) {
return wire;
}
let (encoded, entities) = self.section(section);
let mut w = horizon_protocol::buf::Writer::new();
encoded.write(&mut w);
let wire: (Arc<[u8]>, bool) = (w.data.into(), entities);
let wire: (Arc<[u8]>, Entities) = (w.data.into(), entities.into());
self.cached(section, |e| e.wire = Some(wire.clone()));
wire
}
@@ -334,9 +338,9 @@ impl ChunkEncoder {
.is_none_or(|f| f & NON_AIR == 0)
}
fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) {
fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, Vec<(u16, u16)>) {
let mut values = Vec::with_capacity(BLOCKS);
let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false);
let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, Vec::new());
let mut count = |state: u16, n: i16| {
let f = self.flags.get(usize::from(state)).copied().unwrap_or(0);
if f & NON_AIR != 0 {
@@ -350,12 +354,16 @@ impl ChunkEncoder {
// One block everywhere (all air, mostly): what from_values would give.
let uniform = section.blocks.uniform();
if let Some(v) = uniform {
entities = count(v as u16, BLOCKS as i16);
if count(v as u16, BLOCKS as i16) {
entities = (0..BLOCKS as u16).map(|i| (i, v as u16)).collect();
}
} else {
let mut unpacked = [0u16; BLOCKS];
section.unpack(&mut unpacked);
for &v in &unpacked {
entities |= count(v, 1);
for (i, &v) in unpacked.iter().enumerate() {
if count(v, 1) {
entities.push((i as u16, v));
}
values.push(i32::from(v));
}
}
@@ -441,29 +449,30 @@ impl ChunkEncoder {
.skip(self.sections.start)
.take(self.sections.len())
{
let (encoded, has_entities) = self.section_wire(s);
if has_entities {
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let state = s.get(crate::chunk::index(x, y, z));
if let Some(kind) = self.entity_type(state) {
let wy = MIN_Y + (i as i32) * 16 + y;
let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z);
entity_infos.push(BlockEntityInfo {
packed_xz: ((x << 4) | z) as i8,
y: wy as i16,
kind,
// BlockEntityInfo.create: an empty update tag is not sent.
tag: block_entities
.get(&pos)
.and_then(entity_tag)
.unwrap_or(Tag::End),
});
}
}
}
}
let (encoded, entities) = self.section_wire(s);
// The section's block entity blocks, kept with its bytes, in the
// order a scan of every block would find them.
for &(index, state) in entities.iter() {
let Some(kind) = self.entity_type(state) else {
continue;
};
let (x, y, z) = (
i32::from(index & 15),
i32::from(index >> 8),
i32::from(index >> 4 & 15),
);
let wy = MIN_Y + (i as i32) * 16 + y;
let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z);
entity_infos.push(BlockEntityInfo {
packed_xz: ((x << 4) | z) as i8,
y: wy as i16,
kind,
// BlockEntityInfo.create: an empty update tag is not sent.
tag: block_entities
.get(&pos)
.and_then(entity_tag)
.unwrap_or(Tag::End),
});
}
buffer.extend_from_slice(&encoded);
}
@@ -679,6 +688,73 @@ mod tests {
assert_eq!(block_entity_type("minecraft:stone"), None);
}
#[test]
fn block_entities_come_from_the_cached_section_in_scan_order() {
let builtin = Builtin::parse(
r#"{"minecraft:block_entity_type": {"entries": {
"minecraft:chest": {"protocol_id": 1},
"minecraft:sign": {"protocol_id": 7}}}}"#,
)
.unwrap();
let states = [
"minecraft:air",
"minecraft:stone",
"minecraft:chest",
"minecraft:oak_sign",
]
.map(|n| (Arc::<str>::from(n), false));
let encoder = ChunkEncoder::new(states, &builtin, &[], &[]);
let mut chunk = Chunk::empty(2, -3);
for (x, y, z, state) in [(15, 3, 0, 2), (0, 3, 15, 3), (4, 3, 4, 1), (7, 40, 2, 2)] {
chunk.set(x, MIN_Y + y, z, state);
}
// Every block of a section looked at, as the scan did before the cache.
let scan = |chunk: &Chunk| {
let mut found = Vec::new();
for (i, s) in chunk.sections.iter().enumerate() {
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let state = s.get(crate::chunk::index(x, y, z));
if let Some(kind) = encoder.entity_type(state) {
found.push((x, MIN_Y + i as i32 * 16 + y, z, kind));
}
}
}
}
}
// Then the order the packet gives them, as encode_blocks does.
java_hash_order(&mut found, |e| {
(chunk.x * 16 + e.0, e.1, chunk.z * 16 + e.2)
});
found
};
let sent = |chunk: &Chunk| {
let packet = encoder.encode(chunk, &HashMap::new());
let infos = packet.chunk.block_entities;
infos
.iter()
.map(|e| {
let xz = e.packed_xz as u8;
(
i32::from(xz >> 4),
i32::from(e.y),
i32::from(xz & 15),
e.kind,
)
})
.collect::<Vec<_>>()
};
let expected = scan(&chunk);
assert_eq!(expected.len(), 3);
assert_eq!(sent(&chunk), expected);
// From the cache the second time, and after an edit.
assert_eq!(sent(&chunk), expected);
chunk.set(15, MIN_Y + 3, 0, 0);
chunk.set(9, MIN_Y + 3, 9, 3);
assert_eq!(sent(&chunk), scan(&chunk));
}
fn encoder() -> ChunkEncoder {
let states = ["minecraft:air", "minecraft:stone", "minecraft:water"]
.map(|n| (Arc::<str>::from(n), n.ends_with("water")));