Save worlds in the vanilla 26.3 layout with entities, ticks, light and heightmaps
Worlds now use 26.3's layout and files: dimensions/minecraft/<dim>/{region,
entities}, level.dat with singleplayer_uuid, players/data/<uuid>.dat and the
saved-data files for weather, world clocks (day time), world generation
settings and game rules. Older Horizon saves are migrated on open.
Chunks are written like SerializableChunkData: vanilla's short palette form
for default states, SkyLight/BlockLight layers, the four FULL heightmaps,
block_ticks/fluid_ticks from the tick scheduler, chest/trapped chest/barrel
and furnace block entity IDs, and everything Horizon does not simulate
(unknown block entities, structure references, post-processing) kept from
the loaded chunk. Partially generated vanilla chunks are regenerated
instead of loading as holes.
Mobs, item entities, experience orbs, arrows and falling blocks are saved
per chunk in entities/*.mca with vanilla NBT (entity_nbt.rs), keeping each
loaded entity's UUID and unknown fields; entity types Horizon does not
simulate are written back unchanged. Entities leave the world with their
chunk and come back when it loads.
examples/save_parity re-encodes every chunk of a vanilla-saved world and
compares blocks, biomes, heightmaps, light, block entities and ticks
(identical on three reference worlds apart from vanilla's stale worldgen
light). A Horizon save of a vanilla world opens in the vanilla server with
its mobs, items, arrows and unknown entities.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,265 @@
|
||||
//! Differential save test: load every full chunk of a world written by the
|
||||
//! vanilla 26.3 server, light it, encode it again with Horizon's chunk writer
|
||||
//! and compare the result with the original NBT: block states, biomes,
|
||||
//! heightmaps, light layers (by value), block entities and scheduled ticks.
|
||||
//!
|
||||
//! cargo run --profile fast -p horizon-client --example save_parity -- \
|
||||
//! RESOURCES DIMENSION_DIR [--nether]
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
biome::Biomes,
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, MIN_Y, SECTIONS},
|
||||
light::{LightTables, light_chunk},
|
||||
save::{self, SaveTables},
|
||||
};
|
||||
use horizon_core::position::ChunkPos;
|
||||
use horizon_world::{
|
||||
chunk::BlockState,
|
||||
nbt::{Limits, NamedTag, Tag},
|
||||
region::RegionFile,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
/// Block state names per section index, decoded independently of Horizon.
|
||||
fn block_names(tag: &Tag) -> BTreeMap<i64, Vec<String>> {
|
||||
let mut out = BTreeMap::new();
|
||||
let Some(Tag::List(sections)) = tag.get("sections") else {
|
||||
return out;
|
||||
};
|
||||
for s in sections {
|
||||
let Some(Tag::Byte(y)) = s.get("Y") else {
|
||||
continue;
|
||||
};
|
||||
let Some(states) = s.get("block_states") else {
|
||||
continue;
|
||||
};
|
||||
let Some(Tag::List(palette)) = states.get("palette") else {
|
||||
continue;
|
||||
};
|
||||
let names: Vec<String> = palette
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let st = BlockState::from_nbt(p).expect("palette entry");
|
||||
format!("{}{:?}", st.name, st.properties)
|
||||
})
|
||||
.collect();
|
||||
let bits = (usize::BITS - (names.len().max(1) - 1).leading_zeros()).max(4);
|
||||
let per = 64 / bits as usize;
|
||||
let data = match states.get("data") {
|
||||
Some(Tag::LongArray(d)) => d.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let blocks = (0..4096)
|
||||
.map(|i| {
|
||||
if names.len() == 1 {
|
||||
return names[0].clone();
|
||||
}
|
||||
let v = (data[i / per] as u64 >> ((i % per) as u32 * bits)) & ((1 << bits) - 1);
|
||||
names[v as usize].clone()
|
||||
})
|
||||
.collect();
|
||||
out.insert(i64::from(*y), blocks);
|
||||
}
|
||||
out
|
||||
}
|
||||
fn light(tag: &Tag, key: &str) -> HashMap<i64, Vec<u8>> {
|
||||
let mut out = HashMap::new();
|
||||
if let Some(Tag::List(sections)) = tag.get("sections") {
|
||||
for s in sections {
|
||||
if let (Some(Tag::Byte(y)), Some(Tag::ByteArray(a))) = (s.get("Y"), s.get(key)) {
|
||||
out.insert(i64::from(*y), a.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Light value with vanilla's reading of missing layers.
|
||||
fn value(
|
||||
layers: &HashMap<i64, Vec<u8>>,
|
||||
sy: i64,
|
||||
i: usize,
|
||||
sky: bool,
|
||||
empty: bool,
|
||||
top: i64,
|
||||
) -> u8 {
|
||||
let nibble = |a: &Vec<u8>, i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15;
|
||||
if let Some(a) = layers.get(&sy) {
|
||||
return nibble(a, i);
|
||||
}
|
||||
if !sky || !empty {
|
||||
return 0;
|
||||
}
|
||||
((sy + 1)..=top)
|
||||
.find_map(|y| layers.get(&y))
|
||||
.map_or(15, |a| nibble(a, i & 255))
|
||||
}
|
||||
fn count(tag: &Tag, key: &str) -> usize {
|
||||
match tag.get(key) {
|
||||
Some(Tag::List(l)) => l.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let root = PathBuf::from(
|
||||
args.first()
|
||||
.ok_or("usage: save_parity RESOURCES DIMENSION_DIR")?,
|
||||
);
|
||||
let dim = PathBuf::from(args.get(1).ok_or("missing dimension directory")?);
|
||||
let sky_light = !args.iter().any(|a| a == "--nether");
|
||||
let assets = Assets::load(&root)?;
|
||||
let facts = BlockFacts::load(&root, assets.registry)?;
|
||||
let biomes = Biomes::load(&root)?;
|
||||
let lights = LightTables::load(&root, assets.registry, &facts)?;
|
||||
let tables = SaveTables::new(&assets).with_block_entities(&facts);
|
||||
let mut originals: HashMap<(i32, i32), NamedTag> = HashMap::new();
|
||||
let mut chunks: HashMap<(i32, i32), Chunk> = HashMap::new();
|
||||
for entry in std::fs::read_dir(dim.join("region"))? {
|
||||
let mut region = RegionFile::open(entry?.path())?;
|
||||
let positions: Vec<ChunkPos> = region.chunks().map(|(p, _)| p).collect();
|
||||
for p in positions {
|
||||
let Some(record) = region.read(p)? else {
|
||||
continue;
|
||||
};
|
||||
let tag = record.nbt(Limits::default())?;
|
||||
if tag.tag.get("isLightOn") != Some(&Tag::Byte(1)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = save::decode_with(&tag, assets.registry, &biomes, Some(&tables)) {
|
||||
chunks.insert((c.x, c.z), c);
|
||||
originals.insert((p.x, p.z), tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keys: Vec<_> = chunks
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|&(x, z)| {
|
||||
(-1..=1).all(|dz| (-1..=1).all(|dx| chunks.contains_key(&(x + dx, z + dz))))
|
||||
})
|
||||
.collect();
|
||||
keys.sort_unstable();
|
||||
let (
|
||||
mut blocks_bad,
|
||||
mut biomes_bad,
|
||||
mut heightmaps_bad,
|
||||
mut light_bad,
|
||||
mut light_total,
|
||||
mut other_bad,
|
||||
) = (0, 0, 0, 0u64, 0u64, 0);
|
||||
for &(x, z) in &keys {
|
||||
let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| {
|
||||
std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1)))
|
||||
});
|
||||
let mut chunk = chunks[&(x, z)].clone();
|
||||
chunk.sections = light_chunk(®ion, &lights, sky_light);
|
||||
chunk.lit = true;
|
||||
let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light);
|
||||
let theirs = &originals[&(x, z)];
|
||||
let (a, b) = (&ours.tag, &theirs.tag);
|
||||
// Block states: compare every non-empty vanilla section.
|
||||
let (na, nb) = (block_names(a), block_names(b));
|
||||
for (y, vb) in &nb {
|
||||
match na.get(y) {
|
||||
Some(va) if va == vb => {}
|
||||
Some(va) => {
|
||||
let n = va.iter().zip(vb).filter(|(p, q)| p != q).count();
|
||||
if blocks_bad < 5 {
|
||||
let i = va.iter().zip(vb).position(|(p, q)| p != q).unwrap_or(0);
|
||||
eprintln!(
|
||||
"chunk {x} {z} section {y}: {n} blocks differ, e.g. {} vs {}",
|
||||
va[i], vb[i]
|
||||
);
|
||||
}
|
||||
blocks_bad += 1;
|
||||
}
|
||||
None if vb.iter().all(|s| s.starts_with("minecraft:air")) => {}
|
||||
None => blocks_bad += 1,
|
||||
}
|
||||
}
|
||||
let biome_of = |t: &Tag| -> Vec<Tag> {
|
||||
match t.get("sections") {
|
||||
Some(Tag::List(l)) => l.iter().filter_map(|s| s.get("biomes").cloned()).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
};
|
||||
if biome_of(a) != biome_of(b) {
|
||||
biomes_bad += 1;
|
||||
}
|
||||
for kind in [
|
||||
"WORLD_SURFACE",
|
||||
"OCEAN_FLOOR",
|
||||
"MOTION_BLOCKING",
|
||||
"MOTION_BLOCKING_NO_LEAVES",
|
||||
] {
|
||||
let get = |t: &Tag| t.get("Heightmaps").and_then(|h| h.get(kind)).cloned();
|
||||
if get(a) != get(b) {
|
||||
if heightmaps_bad < 5 {
|
||||
eprintln!("chunk {x} {z}: heightmap {kind} differs");
|
||||
}
|
||||
heightmaps_bad += 1;
|
||||
}
|
||||
}
|
||||
for (key, sky) in [("SkyLight", true), ("BlockLight", false)] {
|
||||
if sky && !sky_light {
|
||||
continue;
|
||||
}
|
||||
let (la, lb) = (light(a, key), light(b, key));
|
||||
let top = i64::from((MIN_Y >> 4) + SECTIONS as i32);
|
||||
for si in 0..SECTIONS {
|
||||
let sy = i64::from((MIN_Y >> 4) + si as i32);
|
||||
let empty = chunk.sections[si].is_uniform(tables_air(&assets));
|
||||
for i in 0..4096 {
|
||||
light_total += 1;
|
||||
if value(&la, sy, i, sky, empty, top) != value(&lb, sy, i, sky, empty, top) {
|
||||
light_bad += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for key in ["block_entities", "block_ticks", "fluid_ticks"] {
|
||||
if count(a, key) != count(b, key) {
|
||||
if other_bad < 5 {
|
||||
eprintln!(
|
||||
"chunk {x} {z}: {key} {} vs {}",
|
||||
count(a, key),
|
||||
count(b, key)
|
||||
);
|
||||
}
|
||||
other_bad += 1;
|
||||
}
|
||||
}
|
||||
for key in [
|
||||
"structures",
|
||||
"PostProcessing",
|
||||
"InhabitedTime",
|
||||
"Status",
|
||||
"DataVersion",
|
||||
"yPos",
|
||||
] {
|
||||
if a.get(key) != b.get(key) {
|
||||
if other_bad < 5 {
|
||||
eprintln!("chunk {x} {z}: {key} differs");
|
||||
}
|
||||
other_bad += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"{} chunks: {blocks_bad} sections with different blocks, {biomes_bad} chunks with different biomes, \
|
||||
{heightmaps_bad} different heightmaps, {light_bad} of {light_total} light values differ, {other_bad} other differences",
|
||||
keys.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn tables_air(assets: &Assets) -> u16 {
|
||||
assets
|
||||
.registry
|
||||
.default_state("minecraft:air")
|
||||
.map_or(0, |s| s.0 as u16)
|
||||
}
|
||||
@@ -98,6 +98,10 @@ pub struct Chunk {
|
||||
pub fresh: bool,
|
||||
/// Block entities read from a save, moved into the world on arrival.
|
||||
pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>,
|
||||
/// Saved data Horizon keeps but does not simulate (save.rs).
|
||||
pub saved: Option<Arc<crate::save::ChunkExtras>>,
|
||||
/// Entities read from a save (vanilla entity NBT), spawned on arrival.
|
||||
pub entities: Vec<horizon_world::nbt::Tag>,
|
||||
}
|
||||
impl Chunk {
|
||||
pub fn empty(x: i32, z: i32) -> Self {
|
||||
@@ -110,6 +114,8 @@ impl Chunk {
|
||||
lit: false,
|
||||
fresh: false,
|
||||
block_entities: Vec::new(),
|
||||
saved: None,
|
||||
entities: Vec::new(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Vanilla 26.3 entity NBT (`Entity.saveWithoutId` and the subclasses'
|
||||
//! `addAdditionalSaveData`) for the entities Horizon simulates: mobs, item
|
||||
//! entities, experience orbs, arrows and falling blocks. Encoding starts from
|
||||
//! the compound the entity was loaded with, when there is one, so fields
|
||||
//! Horizon does not model (variants, attributes, equipment, custom names)
|
||||
//! survive a Horizon save.
|
||||
use crate::{
|
||||
entities::{Arrow, ExperienceOrb, ItemEntity},
|
||||
mobs::{Mob, MobType},
|
||||
save::{doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag},
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
fn string(s: &str) -> Tag {
|
||||
Tag::String(s.into())
|
||||
}
|
||||
/// Entity type ID (`id`).
|
||||
pub fn kind(tag: &Tag) -> Option<String> {
|
||||
text(tag.get("id"))
|
||||
}
|
||||
pub fn position(tag: &Tag) -> Option<Vec3> {
|
||||
read_doubles::<3>(tag.get("Pos")).map(|p| Vec3::new(p[0], p[1], p[2]))
|
||||
}
|
||||
pub fn uuid(tag: &Tag) -> Option<[i32; 4]> {
|
||||
uuid_from_tag(tag.get("UUID"))
|
||||
}
|
||||
fn motion(tag: &Tag) -> Vec3 {
|
||||
read_doubles::<3>(tag.get("Motion")).map_or(Vec3::ZERO, |m| Vec3::new(m[0], m[1], m[2]))
|
||||
}
|
||||
fn rotation(tag: &Tag) -> [f32; 2] {
|
||||
read_doubles::<2>(tag.get("Rotation")).map_or([0.0; 2], |r| [r[0] as f32, r[1] as f32])
|
||||
}
|
||||
fn flag(tag: &Tag, key: &str) -> bool {
|
||||
number(tag.get(key)).unwrap_or(0) != 0
|
||||
}
|
||||
/// `Entity.saveWithoutId` fields every entity has, over the loaded compound.
|
||||
struct Base<'a> {
|
||||
id: &'a str,
|
||||
uuid: [i32; 4],
|
||||
position: Vec3,
|
||||
motion: Vec3,
|
||||
rotation: [f32; 2],
|
||||
on_ground: bool,
|
||||
fall_distance: f64,
|
||||
}
|
||||
impl Base<'_> {
|
||||
fn tag(&self, raw: Option<&Tag>) -> Tag {
|
||||
let mut tag = match raw {
|
||||
Some(t @ Tag::Compound(_)) => t.clone(),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
};
|
||||
for (key, value) in [
|
||||
("id", string(self.id)),
|
||||
("UUID", Tag::IntArray(self.uuid.to_vec())),
|
||||
("Pos", doubles(&[self.position.x, self.position.y, self.position.z])),
|
||||
("Motion", doubles(&[self.motion.x, self.motion.y, self.motion.z])),
|
||||
("Rotation", floats(&self.rotation)),
|
||||
("OnGround", Tag::Byte(i8::from(self.on_ground))),
|
||||
("fall_distance", Tag::Double(self.fall_distance.to_bits())),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
for (key, value) in [("Fire", Tag::Short(-1)), ("Air", Tag::Short(300)), ("Invulnerable", Tag::Byte(0)), ("PortalCooldown", Tag::Int(0))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
tag
|
||||
}
|
||||
}
|
||||
|
||||
/// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics).
|
||||
pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let base = Base {
|
||||
id: &m.kind.id,
|
||||
uuid,
|
||||
position: m.position,
|
||||
motion: m.velocity,
|
||||
rotation: [m.yaw, m.head_pitch],
|
||||
on_ground: m.on_ground,
|
||||
fall_distance: m.fall_distance,
|
||||
};
|
||||
let mut tag = base.tag(raw);
|
||||
for (key, value) in [
|
||||
("Health", Tag::Float(m.health.max(0.0).to_bits())),
|
||||
("HurtTime", Tag::Short(m.hurt_time.clamp(0, i32::from(i16::MAX)) as i16)),
|
||||
("DeathTime", Tag::Short(m.death_time.clamp(0, i32::from(i16::MAX)) as i16)),
|
||||
("PersistenceRequired", Tag::Byte(i8::from(m.persistent))),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
let Tag::Compound(map) = &mut tag else { return tag };
|
||||
for (key, value) in [
|
||||
("AbsorptionAmount", Tag::Float(0)),
|
||||
("FallFlying", Tag::Byte(0)),
|
||||
("CanPickUpLoot", Tag::Byte(0)),
|
||||
("LeftHanded", Tag::Byte(0)),
|
||||
("Brain", Tag::compound([("memories", Tag::Compound(Compound::new()))])),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
let id = m.kind.id.as_str();
|
||||
if m.kind.category == "creature" {
|
||||
for (key, value) in [("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), ("InLove", Tag::Int(0)), ("AgeLocked", Tag::Byte(0))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
match id {
|
||||
"minecraft:creeper" => {
|
||||
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3)), ("powered", Tag::Byte(0)), ("ignited", Tag::Byte(0))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
// Skeletons are spawned holding a bow (finalizeSpawn); a mob loaded
|
||||
// from NBT keeps only its saved equipment.
|
||||
"minecraft:skeleton" | "minecraft:stray" | "minecraft:bogged" => {
|
||||
map.entry("equipment".into()).or_insert_with(|| Tag::compound([("mainhand", Tag::compound([("id", string("minecraft:bow")), ("count", Tag::Int(1))]))]));
|
||||
}
|
||||
"minecraft:zombie" => {
|
||||
for (key, value) in [("IsBaby", Tag::Byte(0)), ("CanBreakDoors", Tag::Byte(0)), ("DrownedConversionTime", Tag::Int(-1)), ("InWaterTime", Tag::Int(-1))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
"minecraft:sheep" => {
|
||||
for (key, value) in [("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -> Option<Mob> {
|
||||
let kind = types.get(&self::kind(tag)?)?.clone();
|
||||
let position = position(tag)?;
|
||||
let [yaw, pitch] = rotation(tag);
|
||||
let mut m = Mob::new(id, kind, position, yaw);
|
||||
m.velocity = motion(tag);
|
||||
m.head_pitch = pitch;
|
||||
m.on_ground = flag(tag, "OnGround");
|
||||
m.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0);
|
||||
if let Some(h) = float(tag.get("Health")) {
|
||||
m.health = h as f32;
|
||||
}
|
||||
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
|
||||
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
|
||||
m.persistent = flag(tag, "PersistenceRequired");
|
||||
// A mob saved mid-death finishes dying; one saved dead is dropped.
|
||||
if m.health <= 0.0 && m.death_time == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `ItemEntity`: Health, Age, PickupDelay, Item.
|
||||
pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let base = Base {
|
||||
id: "minecraft:item",
|
||||
uuid,
|
||||
position: e.position,
|
||||
motion: e.velocity,
|
||||
rotation: [0.0, 0.0],
|
||||
on_ground: e.on_ground,
|
||||
fall_distance: 0.0,
|
||||
};
|
||||
let mut tag = base.tag(raw);
|
||||
for (key, value) in [
|
||||
("Item", item_to_nbt(&e.stack)),
|
||||
("Age", Tag::Short(e.age.min(i16::MAX as u32) as i16)),
|
||||
("PickupDelay", Tag::Short(e.pickup_delay.min(i16::MAX as u32) as i16)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
map.entry("Health".into()).or_insert(Tag::Short(5));
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemEntity> {
|
||||
let stack = item_from_nbt(tag.get("Item")?)?;
|
||||
let position = position(tag)?;
|
||||
Some(ItemEntity {
|
||||
id,
|
||||
stack,
|
||||
position,
|
||||
previous: position,
|
||||
velocity: motion(tag),
|
||||
on_ground: flag(tag, "OnGround"),
|
||||
// Age -32768 marks items that never despawn; Horizon counts upwards.
|
||||
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
|
||||
pickup_delay: number(tag.get("PickupDelay")).unwrap_or(0).clamp(0, 32767) as u32,
|
||||
bob_offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// `ExperienceOrb`: Health, Age, Value, Count.
|
||||
pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
|
||||
let base = Base {
|
||||
id: "minecraft:experience_orb",
|
||||
uuid,
|
||||
position: o.position,
|
||||
motion: o.velocity,
|
||||
rotation: [0.0, 0.0],
|
||||
on_ground: o.on_ground,
|
||||
fall_distance: 0.0,
|
||||
};
|
||||
let mut tag = base.tag(None);
|
||||
for (key, value) in [
|
||||
("Health", Tag::Short(5)),
|
||||
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
|
||||
("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)),
|
||||
("Count", Tag::Int(1)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// One Horizon orb per counted orb (vanilla merges orbs of equal value).
|
||||
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
|
||||
let Some(position) = position(tag) else { return Vec::new() };
|
||||
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
|
||||
let orb = ExperienceOrb {
|
||||
position,
|
||||
previous: position,
|
||||
velocity: motion(tag),
|
||||
value: number(tag.get("Value")).unwrap_or(1).max(1) as u32,
|
||||
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
|
||||
on_ground: flag(tag, "OnGround"),
|
||||
};
|
||||
vec![orb; count]
|
||||
}
|
||||
|
||||
/// `AbstractArrow`: damage, crit, inGround, life, pickup, item.
|
||||
pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag {
|
||||
let v = a.velocity;
|
||||
let horizontal = (v.x * v.x + v.z * v.z).sqrt();
|
||||
let rotation = [(v.x.atan2(v.z).to_degrees()) as f32, (v.y.atan2(horizontal).to_degrees()) as f32];
|
||||
let base = Base {
|
||||
id: "minecraft:arrow",
|
||||
uuid,
|
||||
position: a.position,
|
||||
motion: a.velocity,
|
||||
rotation,
|
||||
on_ground: false,
|
||||
fall_distance: 0.0,
|
||||
};
|
||||
let mut tag = base.tag(None);
|
||||
for (key, value) in [
|
||||
("damage", Tag::Double(a.base_damage.to_bits())),
|
||||
("crit", Tag::Byte(i8::from(a.critical))),
|
||||
("inGround", Tag::Byte(i8::from(a.stuck))),
|
||||
("life", Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 })),
|
||||
// Pickup: allowed for the player's arrows, disallowed for mobs'.
|
||||
("pickup", Tag::Byte(i8::from(a.from_player))),
|
||||
("shake", Tag::Byte(0)),
|
||||
("PierceLevel", Tag::Byte(0)),
|
||||
("HasBeenShot", Tag::Byte(1)),
|
||||
("SoundEvent", string("minecraft:entity.arrow.hit")),
|
||||
("item", Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))])),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
if let Some(owner) = owner {
|
||||
put(&mut tag, "Owner", Tag::IntArray(owner.to_vec()));
|
||||
}
|
||||
tag
|
||||
}
|
||||
pub fn arrow_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option<Arrow> {
|
||||
let position = position(tag)?;
|
||||
let stuck = flag(tag, "inGround");
|
||||
Some(Arrow {
|
||||
from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player || number(tag.get("pickup")) == Some(1),
|
||||
critical: flag(tag, "crit"),
|
||||
position,
|
||||
previous: position,
|
||||
velocity: motion(tag),
|
||||
stuck,
|
||||
age: if stuck { number(tag.get("life")).unwrap_or(0).max(0) as u32 } else { 0 },
|
||||
base_damage: float(tag.get("damage")).unwrap_or(2.0),
|
||||
})
|
||||
}
|
||||
|
||||
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
|
||||
pub fn falling_block_to_nbt(state: Tag, position: Vec3, motion: Vec3, time: u32, uuid: [i32; 4]) -> Tag {
|
||||
let base = Base {
|
||||
id: "minecraft:falling_block",
|
||||
uuid,
|
||||
position,
|
||||
motion,
|
||||
rotation: [0.0, 0.0],
|
||||
on_ground: false,
|
||||
fall_distance: 0.0,
|
||||
};
|
||||
let mut tag = base.tag(None);
|
||||
for (key, value) in [
|
||||
("BlockState", state),
|
||||
("Time", Tag::Int(time as i32)),
|
||||
("DropItem", Tag::Byte(1)),
|
||||
("HurtEntities", Tag::Byte(0)),
|
||||
("CancelDrop", Tag::Byte(0)),
|
||||
("FallHurtAmount", Tag::Float(0)),
|
||||
("FallHurtMax", Tag::Int(40)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
tag
|
||||
}
|
||||
/// (block state tag, position, motion, time)
|
||||
pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, u32)> {
|
||||
Some((tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0).max(0) as u32))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::items::ItemStack;
|
||||
|
||||
#[test]
|
||||
fn item_entities_round_trip() {
|
||||
let e = ItemEntity {
|
||||
id: 7,
|
||||
stack: ItemStack { item: Arc::from("minecraft:diamond_pickaxe"), count: 1, damage: 5 },
|
||||
position: Vec3::new(100.5, 64.0, -31.5),
|
||||
previous: Vec3::ZERO,
|
||||
velocity: Vec3::new(0.0, -0.04, 0.0),
|
||||
on_ground: true,
|
||||
age: 120,
|
||||
pickup_delay: 10,
|
||||
bob_offset: 0.0,
|
||||
};
|
||||
let tag = item_entity_to_nbt(&e, [1, 2, 3, 4], None);
|
||||
assert_eq!(kind(&tag).as_deref(), Some("minecraft:item"));
|
||||
assert_eq!(uuid(&tag), Some([1, 2, 3, 4]));
|
||||
let back = item_entity_from_nbt(&tag, 9, 0.0).unwrap();
|
||||
assert_eq!(back.stack.damage, 5);
|
||||
assert_eq!((back.age, back.pickup_delay, back.on_ground), (120, 10, true));
|
||||
assert_eq!(back.position.x, 100.5);
|
||||
}
|
||||
#[test]
|
||||
fn unknown_fields_survive() {
|
||||
let raw = Tag::compound([("id", string("minecraft:item")), ("CustomName", string("x")), ("Pos", doubles(&[0.5, 64.0, 0.5])), ("Item", Tag::compound([("id", string("minecraft:stone")), ("count", Tag::Int(3))]))]);
|
||||
let e = item_entity_from_nbt(&raw, 1, 0.0).unwrap();
|
||||
let tag = item_entity_to_nbt(&e, [0; 4], Some(&raw));
|
||||
assert_eq!(text(tag.get("CustomName")).as_deref(), Some("x"));
|
||||
assert_eq!(number(tag.get("Health")), Some(5));
|
||||
}
|
||||
#[test]
|
||||
fn orbs_expand_their_count() {
|
||||
let o = ExperienceOrb { position: Vec3::new(1.0, 2.0, 3.0), previous: Vec3::ZERO, velocity: Vec3::ZERO, value: 7, age: 3, on_ground: false };
|
||||
let mut tag = orb_to_nbt(&o, [0; 4]);
|
||||
put(&mut tag, "Count", Tag::Int(3));
|
||||
let back = orbs_from_nbt(&tag);
|
||||
assert_eq!(back.len(), 3);
|
||||
assert_eq!(back[0].value, 7);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
|
||||
//! block interaction, inventory and HUD.
|
||||
mod control;
|
||||
mod persist;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -387,6 +388,7 @@ struct Game<'a> {
|
||||
/// Control replies waiting for a rendered frame or a benchmark deadline.
|
||||
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
|
||||
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
|
||||
persist: persist::EntityMemory,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Dim {
|
||||
@@ -403,13 +405,6 @@ impl Dim {
|
||||
fn from_id(id: &str) -> Self {
|
||||
if id == "minecraft:the_nether" { Self::Nether } else { Self::Overworld }
|
||||
}
|
||||
/// Region folder inside the world (vanilla's DIM-1 for the Nether).
|
||||
fn folder(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Overworld => None,
|
||||
Self::Nether => Some("DIM-1"),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn facing_offset(facing: &str) -> [i32; 3] {
|
||||
match facing {
|
||||
@@ -700,7 +695,7 @@ impl Game<'_> {
|
||||
fn sync_tick_chunks(&mut self) {
|
||||
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
for k in loaded.difference(&self.tick_chunks.clone()) {
|
||||
let _ = self.block_ticks.add_empty_chunk(horizon_core::position::ChunkPos::new(k.0, k.1));
|
||||
self.register_chunk_ticks(*k);
|
||||
}
|
||||
for k in self.tick_chunks.difference(&loaded) {
|
||||
self.block_ticks.remove_chunk(horizon_core::position::ChunkPos::new(k.0, k.1));
|
||||
@@ -1374,6 +1369,7 @@ impl Game<'_> {
|
||||
self.tick_using();
|
||||
self.tick_mining()?;
|
||||
self.tick_items();
|
||||
self.spawn_loaded_entities();
|
||||
self.tick_mobs()?;
|
||||
self.tick_experience();
|
||||
self.tick_hand();
|
||||
@@ -2586,6 +2582,7 @@ impl Game<'_> {
|
||||
.filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z)
|
||||
.map(|(p, e)| (*p, e.clone()))
|
||||
.collect();
|
||||
self.attach_save_data(&mut c);
|
||||
Arc::new(c)
|
||||
}
|
||||
fn tick_mobs(&mut self) -> Result<()> {
|
||||
@@ -2852,6 +2849,8 @@ impl Game<'_> {
|
||||
/// Load (or create) a world folder under saves/ and start streaming it.
|
||||
fn open_world(&mut self, folder: &str, name: Option<&str>, seed: Option<i64>, creative: bool) -> Result<()> {
|
||||
let save_root = std::env::current_dir()?.join("saves").join(folder);
|
||||
horizon_client::save::migrate_legacy(&save_root)?;
|
||||
self.persist = Default::default();
|
||||
let level = Level::read(&save_root).unwrap_or_else(|| Level {
|
||||
name: name.unwrap_or(folder).to_owned(),
|
||||
// WorldOptions.randomSeed when no seed was given.
|
||||
@@ -2950,11 +2949,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Streaming and region storage for one dimension of a world.
|
||||
fn make_streaming(&self, world_root: &std::path::Path, dim: Dim, seed: i64) -> Result<(Streaming, Arc<SaveDir>)> {
|
||||
let region_root = match dim.folder() {
|
||||
Some(f) => world_root.join(f),
|
||||
None => world_root.to_owned(),
|
||||
};
|
||||
let save = Arc::new(SaveDir::new(region_root));
|
||||
let save = Arc::new(SaveDir::new(horizon_client::save::dimension_dir(world_root, dim.id())));
|
||||
let res = &*self.res;
|
||||
let mut streaming = if self.options.test_terrain && dim == Dim::Overworld {
|
||||
let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?);
|
||||
@@ -2978,6 +2973,7 @@ impl Game<'_> {
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks: Vec<_> = keys.iter().filter_map(|k| self.world.chunks.get(k)).map(|c| self.with_entities(c)).collect();
|
||||
self.save.save(&chunks, &self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_dimension_entities()?;
|
||||
// Coordinates scale by 8 between the Overworld and the Nether.
|
||||
let scale = match (self.dim, target) {
|
||||
(Dim::Overworld, Dim::Nether) => 1.0 / 8.0,
|
||||
@@ -4080,6 +4076,8 @@ impl Game<'_> {
|
||||
.map(|c| self.with_entities(c))
|
||||
.collect();
|
||||
self.save.save(&chunks, &self.res.assets.registry, &self.res.biomes)?;
|
||||
self.save_entities()?;
|
||||
self.level.selected_slot = self.selected as i32;
|
||||
let level = &mut self.level;
|
||||
level.creative = self.creative;
|
||||
level.time = self.world.game_time;
|
||||
@@ -4318,6 +4316,7 @@ impl Game<'_> {
|
||||
.cloned()
|
||||
.collect();
|
||||
let modified: Vec<_> = dirty.iter().map(|c| self.with_entities(c)).collect();
|
||||
self.unload_entities(&unloaded);
|
||||
for c in &unloaded {
|
||||
self.world.block_entities.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
|
||||
}
|
||||
@@ -4803,6 +4802,7 @@ pub fn run() -> Result<()> {
|
||||
frame_stats: Default::default(),
|
||||
pending_screenshot: None,
|
||||
pending_bench: None,
|
||||
persist: Default::default(),
|
||||
};
|
||||
if let Some(path) = &game.options.control {
|
||||
let server = horizon_client::control::Server::start(path)
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Saving and loading the game state that lives outside chunk blocks:
|
||||
//! entities (`entities/*.mca`, per chunk like vanilla's `EntityStorage`) and
|
||||
//! scheduled block/fluid ticks (chunk `block_ticks`/`fluid_ticks`).
|
||||
use super::{FallingBlock, Game};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
chunk::Chunk,
|
||||
entity_nbt,
|
||||
save::{ChunkExtras, random_uuid},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
position::ChunkPos,
|
||||
random::RandomSource,
|
||||
ticks::ChunkTicks,
|
||||
};
|
||||
use horizon_world::{chunk::BlockState, nbt::Tag, registry::BlockStateId};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
/// What Horizon remembers about loaded entities to save them faithfully.
|
||||
#[derive(Default)]
|
||||
pub struct EntityMemory {
|
||||
/// UUIDs of mobs and item entities by Horizon entity ID.
|
||||
uuids: HashMap<u32, [i32; 4]>,
|
||||
/// The compound each mob or item entity was loaded with.
|
||||
raw: HashMap<u32, Tag>,
|
||||
/// Entities of types Horizon does not simulate, kept per chunk and
|
||||
/// written back unchanged.
|
||||
unknown: HashMap<(i32, i32), Vec<Tag>>,
|
||||
}
|
||||
|
||||
fn chunk_of(p: Vec3) -> (i32, i32) {
|
||||
((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Saved ticks and the save time for a chunk about to be written.
|
||||
pub(super) fn attach_save_data(&self, chunk: &mut Chunk) {
|
||||
let pos = ChunkPos::new(chunk.x, chunk.z);
|
||||
let time = self.world.game_time;
|
||||
let mut extras: ChunkExtras = chunk.saved.as_deref().cloned().unwrap_or_default();
|
||||
if let Some(t) = self.block_ticks.blocks.chunk(pos) {
|
||||
extras.block_ticks = t.pack(time);
|
||||
} else {
|
||||
extras.block_ticks.clear();
|
||||
}
|
||||
if let Some(t) = self.block_ticks.fluids.chunk(pos) {
|
||||
extras.fluid_ticks = t.pack(time);
|
||||
} else {
|
||||
extras.fluid_ticks.clear();
|
||||
}
|
||||
extras.last_update = time;
|
||||
chunk.saved = Some(Arc::new(extras));
|
||||
}
|
||||
/// Register a newly resident chunk with the tick scheduler, with the
|
||||
/// block and fluid ticks it was saved with.
|
||||
pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) {
|
||||
let pos = ChunkPos::new(key.0, key.1);
|
||||
let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone());
|
||||
let (blocks, fluids) = saved.as_deref().map_or((Vec::new(), Vec::new()), |s| (s.block_ticks.clone(), s.fluid_ticks.clone()));
|
||||
let loaded = !blocks.is_empty() || !fluids.is_empty();
|
||||
if self.block_ticks.add_chunk(pos, ChunkTicks::from_saved(blocks), ChunkTicks::from_saved(fluids)).is_ok() && loaded {
|
||||
let time = self.world.game_time;
|
||||
self.block_ticks.blocks.unpack_chunk(pos, time);
|
||||
self.block_ticks.fluids.unpack_chunk(pos, time);
|
||||
}
|
||||
// The saved list is consumed: later saves take the scheduler's ticks.
|
||||
if loaded && let Some(c) = self.world.chunks.get_mut(&key) {
|
||||
let c = Arc::make_mut(c);
|
||||
if let Some(s) = c.saved.as_mut() {
|
||||
let s = Arc::make_mut(s);
|
||||
s.block_ticks.clear();
|
||||
s.fluid_ticks.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Spawn the entities of chunks that finished loading.
|
||||
pub(super) fn spawn_loaded_entities(&mut self) {
|
||||
let loaded = std::mem::take(&mut self.world.loaded_entities);
|
||||
let player_uuid = self.level.player_uuid;
|
||||
for (key, tags) in loaded {
|
||||
for tag in tags {
|
||||
let kind = entity_nbt::kind(&tag).unwrap_or_default();
|
||||
let uuid = entity_nbt::uuid(&tag);
|
||||
match kind.as_str() {
|
||||
"minecraft:item" => {
|
||||
self.next_entity += 1;
|
||||
let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0;
|
||||
if let Some(e) = entity_nbt::item_entity_from_nbt(&tag, self.next_entity, bob) {
|
||||
self.remember(e.id, uuid, tag);
|
||||
self.dropped.push(e);
|
||||
}
|
||||
}
|
||||
"minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)),
|
||||
"minecraft:arrow" => {
|
||||
if let Some(a) = entity_nbt::arrow_from_nbt(&tag, player_uuid) {
|
||||
self.arrows.push(a);
|
||||
}
|
||||
}
|
||||
"minecraft:falling_block" => {
|
||||
if let Some((state, position, velocity, age)) = entity_nbt::falling_block_from_nbt(&tag)
|
||||
&& let Some(state) = self.state_from_nbt(&state)
|
||||
{
|
||||
self.falling.push(FallingBlock { state, position, previous: position, velocity, age });
|
||||
}
|
||||
}
|
||||
_ if self.res.mob_types.contains_key(&kind) => {
|
||||
self.next_entity += 1;
|
||||
if let Some(m) = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity) {
|
||||
self.remember(m.id, uuid, tag);
|
||||
self.mobs.push(m);
|
||||
}
|
||||
}
|
||||
_ => self.persist.unknown.entry(key).or_default().push(tag),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) {
|
||||
if let Some(u) = uuid {
|
||||
self.persist.uuids.insert(id, u);
|
||||
}
|
||||
self.persist.raw.insert(id, tag);
|
||||
}
|
||||
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
||||
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
|
||||
}
|
||||
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
|
||||
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
|
||||
let registry = self.res.assets.registry;
|
||||
let state = match tag.get("Name") {
|
||||
Some(Tag::String(name)) => BlockState {
|
||||
name: name.to_string_lossy(),
|
||||
properties: match tag.get("Properties") {
|
||||
Some(Tag::Compound(p)) => p
|
||||
.iter()
|
||||
.filter_map(|(k, v)| match v {
|
||||
Tag::String(v) => Some((k.to_string_lossy(), v.to_string_lossy())),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Default::default(),
|
||||
},
|
||||
},
|
||||
_ => BlockState::from_nbt(tag).ok()?,
|
||||
};
|
||||
registry.id(&state).or_else(|| registry.default_state(&state.name))
|
||||
}
|
||||
fn state_to_nbt(&self, state: BlockStateId) -> Tag {
|
||||
let registry = self.res.assets.registry;
|
||||
match registry.state(state) {
|
||||
Some(s) if registry.default_state(&s.name) == Some(state) => Tag::String(s.name.as_str().into()),
|
||||
Some(s) => s.to_nbt(),
|
||||
None => Tag::String("minecraft:air".into()),
|
||||
}
|
||||
}
|
||||
/// The entity NBT of every simulated entity in `keys`, plus the unknown
|
||||
/// entities kept for them. With `remove`, the entities leave the world
|
||||
/// (their chunks unload).
|
||||
fn entity_chunks(&mut self, keys: &HashSet<(i32, i32)>, remove: bool) -> Vec<((i32, i32), Vec<Tag>)> {
|
||||
let mut out: HashMap<(i32, i32), Vec<Tag>> = keys.iter().map(|k| (*k, Vec::new())).collect();
|
||||
let player_uuid = self.level.player_uuid;
|
||||
let mobs: Vec<usize> = (0..self.mobs.len()).filter(|&i| keys.contains(&chunk_of(self.mobs[i].position)) && self.mobs[i].alive()).collect();
|
||||
for i in mobs {
|
||||
let id = self.mobs[i].id;
|
||||
let uuid = self.uuid_for(id);
|
||||
let tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id));
|
||||
out.entry(chunk_of(self.mobs[i].position)).or_default().push(tag);
|
||||
}
|
||||
let items: Vec<usize> = (0..self.dropped.len()).filter(|&i| keys.contains(&chunk_of(self.dropped[i].position))).collect();
|
||||
for i in items {
|
||||
let id = self.dropped[i].id;
|
||||
let uuid = self.uuid_for(id);
|
||||
let tag = entity_nbt::item_entity_to_nbt(&self.dropped[i], uuid, self.persist.raw.get(&id));
|
||||
out.entry(chunk_of(self.dropped[i].position)).or_default().push(tag);
|
||||
}
|
||||
for o in &self.orbs {
|
||||
if keys.contains(&chunk_of(o.position)) {
|
||||
out.entry(chunk_of(o.position)).or_default().push(entity_nbt::orb_to_nbt(o, random_uuid()));
|
||||
}
|
||||
}
|
||||
for a in &self.arrows {
|
||||
if keys.contains(&chunk_of(a.position)) {
|
||||
let owner = if a.from_player { player_uuid } else { None };
|
||||
out.entry(chunk_of(a.position)).or_default().push(entity_nbt::arrow_to_nbt(a, random_uuid(), owner));
|
||||
}
|
||||
}
|
||||
for f in &self.falling {
|
||||
if keys.contains(&chunk_of(f.position)) {
|
||||
let tag = entity_nbt::falling_block_to_nbt(self.state_to_nbt(f.state), f.position, f.velocity, f.age, random_uuid());
|
||||
out.entry(chunk_of(f.position)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for key in keys {
|
||||
let unknown = if remove { self.persist.unknown.remove(key) } else { self.persist.unknown.get(key).cloned() };
|
||||
if let Some(list) = unknown {
|
||||
out.entry(*key).or_default().extend(list);
|
||||
}
|
||||
}
|
||||
if remove {
|
||||
let gone = |p: Vec3| keys.contains(&chunk_of(p));
|
||||
let mut removed: Vec<u32> = Vec::new();
|
||||
self.mobs.retain(|m| {
|
||||
let keep = !gone(m.position);
|
||||
if !keep {
|
||||
removed.push(m.id);
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.dropped.retain(|e| {
|
||||
let keep = !gone(e.position);
|
||||
if !keep {
|
||||
removed.push(e.id);
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.orbs.retain(|o| !gone(o.position));
|
||||
self.arrows.retain(|a| !gone(a.position));
|
||||
self.falling.retain(|f| !gone(f.position));
|
||||
for id in removed {
|
||||
self.persist.uuids.remove(&id);
|
||||
self.persist.raw.remove(&id);
|
||||
}
|
||||
}
|
||||
out.into_iter().collect()
|
||||
}
|
||||
/// Write the entities of every resident chunk (an autosave or quit).
|
||||
pub(super) fn save_entities(&mut self) -> Result<()> {
|
||||
self.spawn_loaded_entities();
|
||||
let keys: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
let chunks = self.entity_chunks(&keys, false);
|
||||
// Forget entities that no longer exist.
|
||||
let alive: HashSet<u32> = self.mobs.iter().map(|m| m.id).chain(self.dropped.iter().map(|e| e.id)).collect();
|
||||
self.persist.uuids.retain(|id, _| alive.contains(id));
|
||||
self.persist.raw.retain(|id, _| alive.contains(id));
|
||||
self.save.save_entities(chunks)
|
||||
}
|
||||
/// Save and remove the entities of chunks that unloaded.
|
||||
pub(super) fn unload_entities(&mut self, unloaded: &[Arc<Chunk>]) {
|
||||
if unloaded.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.spawn_loaded_entities();
|
||||
let keys: HashSet<(i32, i32)> = unloaded.iter().map(|c| (c.x, c.z)).collect();
|
||||
let chunks = self.entity_chunks(&keys, true);
|
||||
if let Err(e) = self.save.save_entities(chunks) {
|
||||
eprintln!("Horizon: failed to save entities: {e}");
|
||||
}
|
||||
}
|
||||
/// Leaving a dimension: its entities are saved with it.
|
||||
pub(super) fn save_dimension_entities(&mut self) -> Result<()> {
|
||||
self.spawn_loaded_entities();
|
||||
let keys: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
let chunks = self.entity_chunks(&keys, true);
|
||||
self.persist = EntityMemory::default();
|
||||
self.save.save_entities(chunks)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod crafting;
|
||||
pub mod creative;
|
||||
pub mod collisions;
|
||||
pub mod entities;
|
||||
pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod gfx;
|
||||
pub mod health;
|
||||
|
||||
+1118
-225
File diff suppressed because it is too large
Load Diff
@@ -277,6 +277,10 @@ impl Streaming {
|
||||
Done::Generated(mut chunk) => {
|
||||
let key = (chunk.x, chunk.z);
|
||||
world.block_entities.extend(std::mem::take(&mut chunk.block_entities));
|
||||
let entities = std::mem::take(&mut chunk.entities);
|
||||
if !entities.is_empty() {
|
||||
world.loaded_entities.push(((chunk.x, chunk.z), entities));
|
||||
}
|
||||
self.generating.remove(&key);
|
||||
self.finishing.remove(&key);
|
||||
self.decorated.insert(key);
|
||||
|
||||
@@ -21,6 +21,8 @@ pub struct World {
|
||||
/// Edits on lit chunks (position, old state, new state), relit
|
||||
/// incrementally by streaming.
|
||||
pub light_edits: Vec<((i32, i32, i32), u16, u16)>,
|
||||
/// Saved entities of chunks that just loaded, spawned by the game.
|
||||
pub loaded_entities: Vec<((i32, i32), Vec<horizon_world::nbt::Tag>)>,
|
||||
/// Chunks changed since the last save.
|
||||
pub modified: HashSet<(i32, i32)>,
|
||||
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
|
||||
@@ -94,6 +96,7 @@ impl World {
|
||||
dirty_sections: HashSet::new(),
|
||||
dirty_light: HashSet::new(),
|
||||
light_edits: Vec::new(),
|
||||
loaded_entities: Vec::new(),
|
||||
modified: HashSet::new(),
|
||||
block_entities: HashMap::new(),
|
||||
game_time: 0,
|
||||
|
||||
Reference in New Issue
Block a user