Merge remote-tracking branch 'pr/753' into integ/mp-sh
This commit is contained in:
@@ -122,20 +122,6 @@ fn main() -> Result<()> {
|
||||
step("collision");
|
||||
let motion = MotionResources::load(&root, &assets)?;
|
||||
step("motion");
|
||||
for name in [
|
||||
"worldgen/blocks/block-properties.nbt",
|
||||
"worldgen/blocks/cached-collision.nbt",
|
||||
"worldgen/blocks/cached-support.nbt",
|
||||
"cached-collision.nbt",
|
||||
"occlusion.nbt",
|
||||
"movement-properties.nbt",
|
||||
] {
|
||||
let bytes = std::fs::read(root.join(name))?;
|
||||
let tree = horizon_world::nbt::read_named(&bytes, horizon_world::nbt::Limits::tables())?;
|
||||
step(&format!(" tree of {name}"));
|
||||
drop((tree, bytes));
|
||||
step(" dropped");
|
||||
}
|
||||
let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, 1234)?;
|
||||
step("worldgen");
|
||||
println!(
|
||||
|
||||
@@ -15,24 +15,18 @@ use horizon_world::{
|
||||
entity_obstruction::EntityIdentity,
|
||||
fluid::{FluidKind, FluidState},
|
||||
liquid_collision::LiquidCollisionWorld,
|
||||
nbt::{self, Limits},
|
||||
powder_snow_collision::{PowderSnowEntity, PowderSnowWorld},
|
||||
registry::BlockRegistry,
|
||||
registry::{BlockRegistry, BlockTableFile},
|
||||
world_movement::{
|
||||
CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision,
|
||||
resolve_world_movement,
|
||||
},
|
||||
};
|
||||
use std::{fs, io, path::Path, sync::Arc};
|
||||
use std::{io, path::Path, sync::Arc};
|
||||
|
||||
pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisionRegistry<'r>> {
|
||||
let data = nbt::read_named(
|
||||
&fs::read(root.join("cached-collision.nbt"))?,
|
||||
Limits::tables(),
|
||||
)?
|
||||
.0
|
||||
.tag;
|
||||
let cached = CachedCollisionRegistry::from_nbt(&data, registry)?;
|
||||
let file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?;
|
||||
let cached = CachedCollisionRegistry::from_table(file.table("collision")?)?;
|
||||
if !cached.has_canonical_identities() {
|
||||
return Err("scene collisions require canonical shape identities".into());
|
||||
}
|
||||
|
||||
@@ -65,17 +65,9 @@ impl LightTables {
|
||||
}
|
||||
/// Full tables with the vanilla occlusion shapes from `occlusion.nbt`.
|
||||
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> crate::Result<Self> {
|
||||
use horizon_world::{
|
||||
collision::CachedCollisionRegistry,
|
||||
nbt::{self, Limits},
|
||||
};
|
||||
let data = nbt::read_named(
|
||||
&std::fs::read(root.join("occlusion.nbt"))?,
|
||||
Limits::tables(),
|
||||
)?
|
||||
.0
|
||||
.tag;
|
||||
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
|
||||
use horizon_world::{collision::CachedCollisionRegistry, registry::BlockTableFile};
|
||||
let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?;
|
||||
let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?;
|
||||
let mut tables = Self::new(facts);
|
||||
let block = VoxelShape::block();
|
||||
let mut shapes: Vec<VoxelShape> = vec![VoxelShape::empty(), block.clone()];
|
||||
|
||||
@@ -117,13 +117,11 @@ pub fn load_visibility(
|
||||
use horizon_world::{
|
||||
block_render::{FaceVisibility, RenderDefinition, SkipRendering},
|
||||
collision::CachedCollisionRegistry,
|
||||
nbt::{self, Limits},
|
||||
registry::BlockTableFile,
|
||||
};
|
||||
use std::{collections::BTreeMap, fs};
|
||||
let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())?
|
||||
.0
|
||||
.tag;
|
||||
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
|
||||
let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?;
|
||||
let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?;
|
||||
let raw: BTreeMap<String, Value> =
|
||||
serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?;
|
||||
let definitions = raw
|
||||
|
||||
@@ -31,8 +31,7 @@ use horizon_world::{
|
||||
movement_restitution::{self, RestitutionInput, RestitutionWorld},
|
||||
movement_statistics::{self, MovementStat, MovementStatisticsWorld},
|
||||
movement_support::{self, MovementLocation},
|
||||
nbt::{self, Limits},
|
||||
registry::BlockStateId,
|
||||
registry::{BlockStateId, BlockTableFile},
|
||||
world_movement::{self, MovementRequest},
|
||||
worldgen::tags::TagDefinitions,
|
||||
};
|
||||
@@ -61,13 +60,8 @@ impl MotionResources {
|
||||
let attributes = Arc::new(Catalog::from_json(&serde_json::from_slice(&fs::read(
|
||||
root.join("attributes.json"),
|
||||
)?)?)?);
|
||||
let data = nbt::read_named(
|
||||
&fs::read(root.join("movement-properties.nbt"))?,
|
||||
Limits::tables(),
|
||||
)?
|
||||
.0
|
||||
.tag;
|
||||
let properties = MovementProperties::from_nbt(&data, assets.registry)?;
|
||||
let file = BlockTableFile::open(&root.join("movement-properties.nbt"), assets.registry)?;
|
||||
let properties = MovementProperties::from_table(file.table("movement")?)?;
|
||||
let bundle: BTreeMap<String, String> =
|
||||
serde_json::from_slice(&fs::read(root.join("block-tags.json"))?)?;
|
||||
let mut definitions = TagDefinitions::default();
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
//! collision shapes. Replacement with an item/fluid context is separate behavior.
|
||||
use crate::{
|
||||
DATA_VERSION,
|
||||
chunk::BlockState,
|
||||
collision::CachedCollisionRegistry,
|
||||
compression::invalid,
|
||||
nbt::Tag,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
registry::{BlockRegistry, BlockStateId, BlockTable},
|
||||
};
|
||||
use horizon_core::geometry::{Direction, ShapeError, ShapeOp, VoxelShape};
|
||||
use std::{
|
||||
@@ -112,21 +111,25 @@ pub struct BlockPropertiesRegistry<'r> {
|
||||
}
|
||||
impl<'r> BlockPropertiesRegistry<'r> {
|
||||
pub fn from_nbt(tag: &Tag, collisions: &CachedCollisionRegistry<'r>) -> io::Result<Self> {
|
||||
Self::from_table(
|
||||
BlockTable::check(tag, collisions.registry(), "block property")?,
|
||||
collisions,
|
||||
)
|
||||
}
|
||||
pub fn from_table(
|
||||
table: BlockTable<'_, '_>,
|
||||
collisions: &CachedCollisionRegistry<'r>,
|
||||
) -> io::Result<Self> {
|
||||
let registry = collisions.registry();
|
||||
if !std::ptr::eq(table.registry(), registry) {
|
||||
return Err(invalid(
|
||||
"block properties and collisions use other registries",
|
||||
));
|
||||
}
|
||||
let tag = table.tag();
|
||||
if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) {
|
||||
return Err(invalid("block properties DataVersion mismatch"));
|
||||
}
|
||||
let Some(Tag::List(states)) = tag.get("states") else {
|
||||
return Err(invalid("missing block property state identities"));
|
||||
};
|
||||
if states.len() != registry.len() {
|
||||
return Err(invalid("block property registry size mismatch"));
|
||||
}
|
||||
for (id, state) in states.iter().enumerate() {
|
||||
if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) {
|
||||
return Err(invalid("block property state identities differ"));
|
||||
}
|
||||
}
|
||||
let Some(Tag::Compound(blocks)) = tag.get("blocks") else {
|
||||
return Err(invalid("missing block definition properties"));
|
||||
};
|
||||
@@ -150,10 +153,8 @@ impl<'r> BlockPropertiesRegistry<'r> {
|
||||
},
|
||||
);
|
||||
}
|
||||
let occlusion = CachedCollisionRegistry::from_nbt(
|
||||
tag.get("occlusion")
|
||||
.ok_or_else(|| invalid("missing block occlusion shapes"))?,
|
||||
registry,
|
||||
let occlusion = CachedCollisionRegistry::from_table(
|
||||
table.nested("occlusion", "block occlusion shapes")?,
|
||||
)?;
|
||||
let mut result = Vec::with_capacity(registry.len());
|
||||
let mut faces = Vec::with_capacity(registry.len());
|
||||
|
||||
@@ -61,7 +61,7 @@ use crate::{
|
||||
collision::CachedCollisionRegistry,
|
||||
compression::invalid,
|
||||
nbt::Tag,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
registry::{BlockRegistry, BlockStateId, BlockTable},
|
||||
};
|
||||
use std::{collections::HashMap, io};
|
||||
/// Cached branch of BlockState.isFaceSturdy. Dynamic support-shape selection
|
||||
@@ -72,10 +72,14 @@ pub struct CachedBlockSupportRegistry<'r> {
|
||||
}
|
||||
impl<'r> CachedBlockSupportRegistry<'r> {
|
||||
pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
if tag.get("Kind") != Some(&Tag::String("block_support".into())) {
|
||||
Self::from_table(BlockTable::check(tag, registry, "support")?)
|
||||
}
|
||||
pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> {
|
||||
if table.get("Kind") != Some(&Tag::String("block_support".into())) {
|
||||
return Err(invalid("wrong cached support data kind"));
|
||||
}
|
||||
let shapes = CachedCollisionRegistry::from_nbt(tag, registry)?;
|
||||
let registry = table.registry();
|
||||
let shapes = CachedCollisionRegistry::from_table(table)?;
|
||||
let mut cache = HashMap::new();
|
||||
let mut states = Vec::with_capacity(registry.len());
|
||||
for id in 0..registry.len() {
|
||||
@@ -163,7 +167,11 @@ impl<E: std::fmt::Display> std::fmt::Display for SupportQueryError<E> {
|
||||
impl<E: std::error::Error + 'static> std::error::Error for SupportQueryError<E> {}
|
||||
impl<'r> BlockSupportRegistry<'r> {
|
||||
pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
let cached = CachedBlockSupportRegistry::from_nbt(tag, registry)?;
|
||||
Self::from_table(BlockTable::check(tag, registry, "support")?)
|
||||
}
|
||||
pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> {
|
||||
let registry = table.registry();
|
||||
let cached = CachedBlockSupportRegistry::from_table(table)?;
|
||||
let mut dynamic = HashMap::new();
|
||||
for id in 0..registry.len() {
|
||||
let id = BlockStateId(id as u32);
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
//! This module covers the cached branch only; uncached states remain explicit.
|
||||
use crate::{
|
||||
DATA_VERSION,
|
||||
chunk::{BlockSection, BlockState},
|
||||
chunk::BlockSection,
|
||||
compression::invalid,
|
||||
nbt::Tag,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
registry::{BlockRegistry, BlockStateId, BlockTable},
|
||||
};
|
||||
use horizon_core::geometry::{Axis, VoxelShape};
|
||||
use std::{collections::HashMap, io};
|
||||
@@ -35,20 +35,13 @@ impl<'r> CachedCollisionRegistry<'r> {
|
||||
self.registry
|
||||
}
|
||||
pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
Self::from_table(BlockTable::check(tag, registry, "collision")?)
|
||||
}
|
||||
pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> {
|
||||
let (tag, registry) = (table.tag(), table.registry());
|
||||
if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) {
|
||||
return Err(invalid("collision DataVersion mismatch"));
|
||||
}
|
||||
let Some(Tag::List(states)) = tag.get("states") else {
|
||||
return Err(invalid("missing collision state identities"));
|
||||
};
|
||||
if states.len() != registry.len() {
|
||||
return Err(invalid("collision registry size mismatch"));
|
||||
}
|
||||
for (id, state) in states.iter().enumerate() {
|
||||
if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) {
|
||||
return Err(invalid("collision state identities differ"));
|
||||
}
|
||||
}
|
||||
let Some(Tag::List(entries)) = tag.get("shapes") else {
|
||||
return Err(invalid("missing collision shapes"));
|
||||
};
|
||||
|
||||
@@ -8,8 +8,7 @@ use crate::{
|
||||
collision::CachedCollisionRegistry,
|
||||
compression::invalid,
|
||||
fluid::{FluidBlockBindings, FluidKind, FluidState},
|
||||
nbt::{self, Limits},
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
registry::{BlockRegistry, BlockStateId, BlockTableFile},
|
||||
worldgen::tags::TagDefinitions,
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape};
|
||||
@@ -787,14 +786,8 @@ fn build_with_gameplay<G: GameplayStateSource>(
|
||||
};
|
||||
|
||||
// Collision shapes.
|
||||
let collision_tag = nbt::read_named(
|
||||
&fs::read(root.join("cached-collision.nbt"))?,
|
||||
Limits::tables(),
|
||||
)
|
||||
.map_err(|e| invalid(e.to_string()))?
|
||||
.0
|
||||
.tag;
|
||||
let cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?;
|
||||
let collision_file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?;
|
||||
let cached = CachedCollisionRegistry::from_table(collision_file.table("collision")?)?;
|
||||
let mut shapes: Vec<VoxelShape> = Vec::new();
|
||||
let mut shape_ids = Vec::with_capacity(table.state_count());
|
||||
for id in 0..table.state_count() {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! Registry-bound block movement coefficients, identities and reloadable tags.
|
||||
use crate::{
|
||||
DATA_VERSION,
|
||||
chunk::BlockState,
|
||||
compression::invalid,
|
||||
movement_support::MovementBlockWorld,
|
||||
nbt::Tag,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
registry::{BlockRegistry, BlockStateId, BlockTable},
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
use std::{
|
||||
@@ -55,20 +54,13 @@ impl<'r> MovementProperties<'r> {
|
||||
}
|
||||
|
||||
pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
Self::from_table(BlockTable::check(tag, registry, "movement")?)
|
||||
}
|
||||
pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result<Self> {
|
||||
let (tag, registry) = (table.tag(), table.registry());
|
||||
if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) {
|
||||
return Err(invalid("movement properties DataVersion mismatch"));
|
||||
}
|
||||
let Some(Tag::List(states)) = tag.get("states") else {
|
||||
return Err(invalid("missing movement state identities"));
|
||||
};
|
||||
if states.len() != registry.len() {
|
||||
return Err(invalid("movement registry size mismatch"));
|
||||
}
|
||||
for (id, state) in states.iter().enumerate() {
|
||||
if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) {
|
||||
return Err(invalid("movement state identities differ"));
|
||||
}
|
||||
}
|
||||
let Some(Tag::Compound(blocks)) = tag.get("blocks") else {
|
||||
return Err(invalid("missing movement definitions"));
|
||||
};
|
||||
|
||||
@@ -124,13 +124,20 @@ impl std::fmt::Display for Error {
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
struct Reader<'a> {
|
||||
/// Hands a streamed list's elements to the caller one at a time (see
|
||||
/// [`read_named_streaming`]).
|
||||
type Visit<'s> = &'s mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>;
|
||||
|
||||
struct Reader<'a, 's> {
|
||||
bytes: &'a [u8],
|
||||
offset: usize,
|
||||
limits: Limits,
|
||||
nodes: usize,
|
||||
/// Lists with this key in the root compound or in a compound directly
|
||||
/// under it are streamed to the visitor instead of kept.
|
||||
stream: Option<(&'s str, Visit<'s>)>,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
impl<'a> Reader<'a, '_> {
|
||||
fn error(&self, reason: &'static str) -> Error {
|
||||
Error {
|
||||
offset: self.offset,
|
||||
@@ -266,7 +273,11 @@ impl<'a> Reader<'a> {
|
||||
break;
|
||||
}
|
||||
let name = self.string()?;
|
||||
let value = self.payload(id, depth + 1)?;
|
||||
let value = if id == 9 && depth <= 1 && self.streams(&name) {
|
||||
self.stream_list(depth + 1)?
|
||||
} else {
|
||||
self.payload(id, depth + 1)?
|
||||
};
|
||||
map.insert(name, value); // Java maps retain the last duplicate key.
|
||||
}
|
||||
Tag::Compound(map)
|
||||
@@ -290,6 +301,82 @@ impl<'a> Reader<'a> {
|
||||
_ => return Err(self.error("unknown tag type")),
|
||||
})
|
||||
}
|
||||
fn streams(&self, name: &JavaString) -> bool {
|
||||
self.stream
|
||||
.as_ref()
|
||||
.is_some_and(|(key, _)| name.0.iter().copied().eq(key.encode_utf16()))
|
||||
}
|
||||
/// A list's payload handed to the visitor element by element; the tree
|
||||
/// keeps it empty. Elements the visitor leaves are read and dropped.
|
||||
fn stream_list(&mut self, depth: usize) -> Result<Tag, Error> {
|
||||
if self.nodes >= self.limits.max_nodes {
|
||||
return Err(self.error("node limit exceeded"));
|
||||
}
|
||||
self.nodes += 1;
|
||||
if depth >= self.limits.max_depth {
|
||||
return Err(self.error("depth limit exceeded"));
|
||||
}
|
||||
let element_id = self.byte()?;
|
||||
let len = self.count(0)?;
|
||||
if len > 0 && (element_id == 0 || element_id > 12) {
|
||||
return Err(self.error("invalid list element type"));
|
||||
}
|
||||
if len > self.bytes.len().saturating_sub(self.offset) {
|
||||
return Err(self.error("truncated list"));
|
||||
}
|
||||
let (key, visit) = self.stream.take().expect("streams() checked the visitor");
|
||||
let mut elements = ListElements {
|
||||
reader: self,
|
||||
element_id,
|
||||
depth: depth + 1,
|
||||
len,
|
||||
left: len,
|
||||
};
|
||||
let rest = visit(&mut elements).and_then(|()| {
|
||||
while elements.next_element()?.is_some() {}
|
||||
Ok(())
|
||||
});
|
||||
self.stream = Some((key, visit));
|
||||
rest.map(|()| Tag::List(Vec::new()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The elements of a list [`read_named_streaming`] streams, read one at a
|
||||
/// time.
|
||||
pub struct ListElements<'r, 'a, 's> {
|
||||
reader: &'r mut Reader<'a, 's>,
|
||||
element_id: u8,
|
||||
depth: usize,
|
||||
len: usize,
|
||||
left: usize,
|
||||
}
|
||||
impl ListElements<'_, '_, '_> {
|
||||
/// The list's length, as its header gives it.
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
/// The next element, unwrapped as [`read_named`] unwraps mixed-list
|
||||
/// elements; `None` past the last.
|
||||
pub fn next_element(&mut self) -> Result<Option<Tag>, Error> {
|
||||
if self.left == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.left -= 1;
|
||||
let mut value = self.reader.payload(self.element_id, self.depth)?;
|
||||
if let Tag::Compound(map) = &mut value {
|
||||
if map.len() == 1 && map.contains_key(&JavaString::default()) {
|
||||
value = map.remove(&JavaString::default()).unwrap();
|
||||
}
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
/// An error at the current position in the input.
|
||||
pub fn error(&self, reason: &'static str) -> Error {
|
||||
self.reader.error(reason)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a file root (type, modified-UTF name, payload), returning bytes consumed.
|
||||
@@ -299,6 +386,35 @@ pub fn read_named(bytes: &[u8], limits: Limits) -> Result<(NamedTag, usize), Err
|
||||
offset: 0,
|
||||
limits,
|
||||
nodes: 0,
|
||||
stream: None,
|
||||
};
|
||||
let id = reader.byte()?;
|
||||
let name = if id == 0 {
|
||||
JavaString::default()
|
||||
} else {
|
||||
reader.string()?
|
||||
};
|
||||
let tag = reader.payload(id, 0)?;
|
||||
Ok((NamedTag { name, tag }, reader.offset))
|
||||
}
|
||||
|
||||
/// [`read_named`], except that lists keyed `key` in the root compound or in
|
||||
/// a compound directly under it are not kept: `visit` reads each one's
|
||||
/// elements as they come, and the tree holds it as an empty list. Per-state
|
||||
/// tables check hundreds of thousands of state identities this way without
|
||||
/// holding them as a tree (crate::registry::BlockTableFile).
|
||||
pub fn read_named_streaming(
|
||||
bytes: &[u8],
|
||||
limits: Limits,
|
||||
key: &str,
|
||||
visit: &mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>,
|
||||
) -> Result<(NamedTag, usize), Error> {
|
||||
let mut reader = Reader {
|
||||
bytes,
|
||||
offset: 0,
|
||||
limits,
|
||||
nodes: 0,
|
||||
stream: Some((key, visit)),
|
||||
};
|
||||
let id = reader.byte()?;
|
||||
let name = if id == 0 {
|
||||
@@ -317,6 +433,7 @@ pub fn read_network(bytes: &[u8], limits: Limits) -> Result<(Tag, usize), Error>
|
||||
offset: 0,
|
||||
limits,
|
||||
nodes: 0,
|
||||
stream: None,
|
||||
};
|
||||
let id = reader.byte()?;
|
||||
let tag = reader.payload(id, 0)?;
|
||||
@@ -659,6 +776,50 @@ impl Snbt<'_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn streamed_lists_reach_the_visitor_and_stay_empty_in_the_tree() {
|
||||
let list = |n: i32| Tag::List((0..n).map(Tag::Int).collect());
|
||||
let root = NamedTag {
|
||||
name: "".into(),
|
||||
tag: Tag::compound([
|
||||
("states", list(3)),
|
||||
("inner", Tag::compound([("states", list(2))])),
|
||||
(
|
||||
"deep",
|
||||
Tag::compound([("inner", Tag::compound([("states", list(1))]))]),
|
||||
),
|
||||
("other", list(4)),
|
||||
]),
|
||||
};
|
||||
let bytes = write_named(&root, Limits::default()).unwrap();
|
||||
let mut seen = Vec::new();
|
||||
let (read, used) = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| {
|
||||
let mut values = vec![l.len() as i32];
|
||||
// Elements left unread are skipped.
|
||||
if let Some(Tag::Int(v)) = l.next_element()? {
|
||||
values.push(v);
|
||||
}
|
||||
seen.push(values);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(used, bytes.len());
|
||||
// Compounds are written in key order: `inner` before `states`.
|
||||
assert_eq!(seen, [vec![2, 0], vec![3, 0]]);
|
||||
assert_eq!(read.tag.get("states"), Some(&Tag::List(Vec::new())));
|
||||
assert_eq!(
|
||||
read.tag.get("inner").unwrap().get("states"),
|
||||
Some(&Tag::List(Vec::new()))
|
||||
);
|
||||
// Only the root and its direct children stream.
|
||||
assert_eq!(read.tag.get("deep"), root.tag.get("deep"));
|
||||
assert_eq!(read.tag.get("other"), root.tag.get("other"));
|
||||
// A visitor's error stops the read.
|
||||
let failed = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| {
|
||||
Err(l.error("refused"))
|
||||
});
|
||||
assert_eq!(failed.unwrap_err().reason, "refused");
|
||||
}
|
||||
#[test]
|
||||
fn wire_node_budget_includes_mixed_list_wrappers() {
|
||||
let tag = Tag::List(vec![Tag::Int(1), Tag::Byte(2)]);
|
||||
let limits = Limits {
|
||||
|
||||
@@ -132,3 +132,120 @@ impl BlockRegistry {
|
||||
.ok_or_else(|| invalid("invalid block property value"))
|
||||
}
|
||||
}
|
||||
|
||||
/// A per-state table (`occlusion.nbt`, `cached-collision.nbt`, ...) whose
|
||||
/// `states` list, the identity of every state it describes in id order, has
|
||||
/// been checked against `registry`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct BlockTable<'t, 'r> {
|
||||
tag: &'t Tag,
|
||||
registry: &'r BlockRegistry,
|
||||
/// How many levels, from this one down, [`BlockTableFile::read`] checked
|
||||
/// while reading: their `states` lists are kept empty in the tree.
|
||||
read_checked: u8,
|
||||
}
|
||||
impl<'t, 'r> BlockTable<'t, 'r> {
|
||||
/// Checks that `tag`'s `states` names the registry's states in id order.
|
||||
pub fn check(tag: &'t Tag, registry: &'r BlockRegistry, what: &str) -> io::Result<Self> {
|
||||
Self {
|
||||
tag,
|
||||
registry,
|
||||
read_checked: 0,
|
||||
}
|
||||
.checked(what)
|
||||
}
|
||||
fn checked(self, what: &str) -> io::Result<Self> {
|
||||
let Some(Tag::List(states)) = self.tag.get("states") else {
|
||||
return Err(invalid(format!("missing {what} state identities")));
|
||||
};
|
||||
if self.read_checked == 0 {
|
||||
if states.len() != self.registry.len() {
|
||||
return Err(invalid(format!("{what} registry size mismatch")));
|
||||
}
|
||||
for (id, state) in states.iter().enumerate() {
|
||||
if self.registry.state(BlockStateId(id as u32))
|
||||
!= Some(&BlockState::from_nbt(state)?)
|
||||
{
|
||||
return Err(invalid(format!("{what} state identities differ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
/// The table nested under `key` (`block-properties.nbt`'s `occlusion`),
|
||||
/// with its own `states`, checked the same way.
|
||||
pub fn nested(&self, key: &str, what: &str) -> io::Result<Self> {
|
||||
Self {
|
||||
tag: self
|
||||
.tag
|
||||
.get(key)
|
||||
.ok_or_else(|| invalid(format!("missing {what}")))?,
|
||||
registry: self.registry,
|
||||
read_checked: self.read_checked.saturating_sub(1),
|
||||
}
|
||||
.checked(what)
|
||||
}
|
||||
pub fn tag(&self) -> &'t Tag {
|
||||
self.tag
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<&'t Tag> {
|
||||
self.tag.get(key)
|
||||
}
|
||||
pub fn registry(&self) -> &'r BlockRegistry {
|
||||
self.registry
|
||||
}
|
||||
}
|
||||
|
||||
/// A per-state table read from its file with its state identities checked
|
||||
/// while reading, so they never exist as a tree: for 190,000 states (a big
|
||||
/// modpack) that tree took 300-600 MB per table.
|
||||
pub struct BlockTableFile<'r> {
|
||||
tag: Tag,
|
||||
registry: &'r BlockRegistry,
|
||||
}
|
||||
impl<'r> BlockTableFile<'r> {
|
||||
/// [`Self::read`] of the file at `path`.
|
||||
pub fn open(path: &std::path::Path, registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
Self::read(&bytes, registry).map_err(|e| invalid(format!("{}: {e}", path.display())))
|
||||
}
|
||||
/// Reads `bytes`, checking every `states` list of the root compound and
|
||||
/// of the compounds directly under it against `registry`.
|
||||
pub fn read(bytes: &[u8], registry: &'r BlockRegistry) -> io::Result<Self> {
|
||||
let mut visit = |states: &mut crate::nbt::ListElements<'_, '_, '_>| {
|
||||
if states.len() != registry.len() {
|
||||
return Err(states.error("table registry size mismatch"));
|
||||
}
|
||||
let mut id = 0u32;
|
||||
while let Some(tag) = states.next_element()? {
|
||||
let state =
|
||||
BlockState::from_nbt(&tag).map_err(|_| states.error("invalid table state"))?;
|
||||
if registry.state(BlockStateId(id)) != Some(&state) {
|
||||
return Err(states.error("table state identities differ"));
|
||||
}
|
||||
id += 1;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let (named, _) = crate::nbt::read_named_streaming(
|
||||
bytes,
|
||||
crate::nbt::Limits::tables(),
|
||||
"states",
|
||||
&mut visit,
|
||||
)
|
||||
.map_err(|e| invalid(e.to_string()))?;
|
||||
Ok(Self {
|
||||
tag: named.tag,
|
||||
registry,
|
||||
})
|
||||
}
|
||||
/// The table, checked (`what` names it in errors).
|
||||
pub fn table(&self, what: &str) -> io::Result<BlockTable<'_, 'r>> {
|
||||
BlockTable {
|
||||
tag: &self.tag,
|
||||
registry: self.registry,
|
||||
read_checked: 2,
|
||||
}
|
||||
.checked(what)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ use crate::{
|
||||
block_support::BlockSupportRegistry,
|
||||
block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule},
|
||||
collision::CachedCollisionRegistry,
|
||||
nbt::{self, Limits, Tag},
|
||||
registry::BlockRegistry,
|
||||
registry::{BlockRegistry, BlockTableFile},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
@@ -102,24 +101,21 @@ impl BlockBehavior {
|
||||
if !dir.join("block-properties.nbt").exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = |name: &str| -> Result<Tag, GeneratorError> {
|
||||
Ok(
|
||||
nbt::read_named(&fs::read(dir.join(name))?, Limits::tables())
|
||||
.map_err(|e| resource(format!("{name}: {e:?}")))?
|
||||
.0
|
||||
.tag,
|
||||
)
|
||||
let read = |name: &str| -> Result<BlockTableFile<'static>, GeneratorError> {
|
||||
BlockTableFile::open(&dir.join(name), registry)
|
||||
.map_err(|e| resource(format!("{name}: {e}")))
|
||||
};
|
||||
let json = |name: &str| -> Result<Value, GeneratorError> {
|
||||
Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?)
|
||||
};
|
||||
let collisions =
|
||||
CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?;
|
||||
let properties =
|
||||
BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?;
|
||||
let support = Arc::new(BlockSupportRegistry::from_nbt(
|
||||
&read("cached-support.nbt")?,
|
||||
registry,
|
||||
CachedCollisionRegistry::from_table(read("cached-collision.nbt")?.table("collision")?)?;
|
||||
let properties = BlockPropertiesRegistry::from_table(
|
||||
read("block-properties.nbt")?.table("block property")?,
|
||||
&collisions,
|
||||
)?;
|
||||
let support = Arc::new(BlockSupportRegistry::from_table(
|
||||
read("cached-support.nbt")?.table("support")?,
|
||||
)?);
|
||||
let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?);
|
||||
let rules = json("survival-rules.json")?
|
||||
|
||||
@@ -267,3 +267,75 @@ fn registry_scan_binding_requires_complete_canonical_metadata() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table read from its bytes checks its state identities while reading and
|
||||
/// keeps none of them, yet loads the same shapes as the tree; a nested table
|
||||
/// (`block-properties.nbt`'s `occlusion`) is checked the same way.
|
||||
#[test]
|
||||
fn streamed_tables_check_states_while_reading() {
|
||||
use horizon_world::{
|
||||
nbt::{self, Limits, NamedTag},
|
||||
registry::{BlockTable, BlockTableFile},
|
||||
};
|
||||
let (registry_tag, collision_tag) = fixture();
|
||||
let registry = BlockRegistry::from_nbt(®istry_tag).unwrap();
|
||||
let bytes = |tag: &Tag| {
|
||||
let root = NamedTag {
|
||||
name: "".into(),
|
||||
tag: tag.clone(),
|
||||
};
|
||||
nbt::write_named(&root, Limits::tables()).unwrap()
|
||||
};
|
||||
let file = BlockTableFile::read(&bytes(&collision_tag), ®istry).unwrap();
|
||||
let table = file.table("collision").unwrap();
|
||||
assert_eq!(table.get("states"), Some(&Tag::List(Vec::new())));
|
||||
let streamed = CachedCollisionRegistry::from_table(table).unwrap();
|
||||
let tree = CachedCollisionRegistry::from_nbt(&collision_tag, ®istry).unwrap();
|
||||
for id in 0..3 {
|
||||
let id = BlockStateId(id);
|
||||
assert_eq!(
|
||||
streamed.cached_shape(id).unwrap().map(|s| s.boxes()),
|
||||
tree.cached_shape(id).unwrap().map(|s| s.boxes())
|
||||
);
|
||||
}
|
||||
|
||||
let mut outer = Tag::compound([("occlusion", collision_tag.clone())]);
|
||||
let Tag::Compound(map) = &mut outer else {
|
||||
unreachable!()
|
||||
};
|
||||
map.insert(
|
||||
"states".into(),
|
||||
collision_tag.get("states").unwrap().clone(),
|
||||
);
|
||||
let file = BlockTableFile::read(&bytes(&outer), ®istry).unwrap();
|
||||
let nested = file
|
||||
.table("outer")
|
||||
.unwrap()
|
||||
.nested("occlusion", "occlusion")
|
||||
.unwrap();
|
||||
assert_eq!(nested.get("states"), Some(&Tag::List(Vec::new())));
|
||||
CachedCollisionRegistry::from_table(nested).unwrap();
|
||||
// Checked only as a tree, an emptied list is refused.
|
||||
assert!(BlockTable::check(nested.tag(), ®istry, "occlusion").is_err());
|
||||
|
||||
// Other states, a different count or no states at all are refused.
|
||||
let with_states = |edit: &dyn Fn(&mut Vec<Tag>)| {
|
||||
let mut tag = collision_tag.clone();
|
||||
let Some(Tag::List(states)) = tag.get_mut("states") else {
|
||||
unreachable!()
|
||||
};
|
||||
edit(states);
|
||||
tag
|
||||
};
|
||||
let swapped = with_states(&|s| s.swap(1, 2));
|
||||
assert!(BlockTableFile::read(&bytes(&swapped), ®istry).is_err());
|
||||
let short = with_states(&|s| drop(s.pop()));
|
||||
assert!(BlockTableFile::read(&bytes(&short), ®istry).is_err());
|
||||
let mut swapped = swapped;
|
||||
let Tag::Compound(map) = &mut swapped else {
|
||||
unreachable!()
|
||||
};
|
||||
map.remove(&"states".into());
|
||||
let file = BlockTableFile::read(&bytes(&swapped), ®istry).unwrap();
|
||||
assert!(file.table("collision").is_err());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user