Merge branch 'parity-base' into parity/platform-maths

This commit is contained in:
Ludovic Marie
2026-10-13 05:15:09 +02:00
27 changed files with 13958 additions and 80 deletions
+9 -8
View File
@@ -121,10 +121,9 @@ pub fn upgrade_older_world(world: &Path) -> Result<()> {
let Some(root) = read_dat(&world.join("level.dat")) else {
return Ok(());
};
let version = root
.get("Data")
.and_then(|d| number(d.get("DataVersion")))
.unwrap_or(i64::from(DATA_VERSION));
let version = root.get("Data").map_or(i64::from(DATA_VERSION), |d| {
number(d.get("DataVersion")).unwrap_or(-1) // saves of 1.8 and before have none
});
if version >= i64::from(DATA_VERSION) {
return Ok(());
}
@@ -2243,10 +2242,12 @@ mod tests {
super::read_dat(&dir.join("level.dat"))
.and_then(|r| super::number(r.get("Data")?.get("DataVersion")))
};
// 1.16.5, older than the ported fixes: refused, left as it is.
super::write_dat(&dir.join("level.dat"), level(2586)).unwrap();
assert!(super::upgrade_older_world(&dir).is_err());
assert_eq!(version(&dir), Some(2586));
// 1.12.2 and 1.16.5: upgraded too, every server fix is ported.
for old in [1343, 2586] {
super::write_dat(&dir.join("level.dat"), level(old)).unwrap();
super::upgrade_older_world(&dir).unwrap();
assert_eq!(version(&dir), Some(i64::from(super::DATA_VERSION)));
}
// 1.21.1: upgraded to the current version.
super::write_dat(&dir.join("level.dat"), level(3955)).unwrap();
super::upgrade_older_world(&dir).unwrap();
+14 -5
View File
@@ -1,6 +1,8 @@
//! Upgrade a copy of a world saved by 1.20 to 26.2 to the 26.3 format, as
//! vanilla 26.3 does when it opens it and reads every file:
//! `datafix_world IN_WORLD OUT_WORLD` (used by tools/test_datafix_parity.py).
//! `datafix_world IN_WORLD OUT_WORLD [TARGET]` (used by tools/test_datafix_parity.py).
//! With a TARGET DataVersion only the data fixes up to it run, on a world in the
//! layout of before 1.16.
use horizon_world::datafix::files;
use std::{env, fs, io, path::Path, process::ExitCode};
@@ -20,9 +22,13 @@ fn copy(from: &Path, to: &Path) -> io::Result<()> {
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
let [input, output] = args.as_slice() else {
eprintln!("usage: datafix_world IN_WORLD OUT_WORLD");
return ExitCode::from(2);
let (input, output, target) = match args.as_slice() {
[input, output] => (input, output, None),
[input, output, target] => (input, output, target.parse::<i32>().ok()),
_ => {
eprintln!("usage: datafix_world IN_WORLD OUT_WORLD [TARGET]");
return ExitCode::from(2);
}
};
let output = Path::new(output);
let result = (|| {
@@ -30,7 +36,10 @@ fn main() -> ExitCode {
fs::remove_dir_all(output)?;
}
copy(Path::new(input), output)?;
files::upgrade_world(output)
match target {
Some(target) => files::upgrade_band(output, target).map(|()| target),
None => files::upgrade_world(output),
}
})();
match result {
Ok(version) => {
@@ -0,0 +1,199 @@
//! `BlockStateData`: the table that maps the 1.12 block states (`blockId << 4 | data`)
//! to 1.13 block states, and the 1.12 `Name` + `Properties` tags to those ids.
//! The table itself is `block_state_data.txt`, generated from vanilla's source by
//! `tools/gen_block_state_data.py`.
//!
//! Vanilla keeps one tag object per `register` call (and per defaulted id) and
//! `ChunkPalettedStorageFix` compares them by identity, so a state is an
//! *instance* here: `register` calls make instances, ids without a call share
//! the instance of the first call for their block.
use std::collections::HashMap;
use std::sync::OnceLock;
use super::dynamic::{as_str, key, string};
use crate::nbt::{Compound, Tag};
/// A block state: name and properties sorted by key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct State {
pub name: String,
pub props: Vec<(String, String)>,
}
impl State {
pub fn new(name: &str, props: &[(&str, &str)]) -> Self {
let mut props: Vec<(String, String)> = props
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect();
props.sort();
Self {
name: name.to_owned(),
props,
}
}
pub fn property(&self, name: &str) -> &str {
self.props
.iter()
.find(|(k, _)| k == name)
.map_or("", |(_, v)| v)
}
/// The NBT tag: `{Name}` or `{Name, Properties}`.
pub fn to_tag(&self) -> Tag {
let mut tag = Tag::compound([("Name", string(&self.name))]);
if !self.props.is_empty() {
let mut props = Compound::new();
for (k, v) in &self.props {
props.insert(key(k), string(v));
}
super::dynamic::set(&mut tag, "Properties", Tag::Compound(props));
}
tag
}
/// A tag read back as a state (`Name` and an optional `Properties` of strings only).
pub fn from_tag(tag: &Tag) -> Option<Self> {
let Tag::Compound(c) = tag else {
return None;
};
let name = as_str(c.get(&key("Name")))?;
let mut props = Vec::new();
let mut expected = 1;
if let Some(p) = c.get(&key("Properties")) {
expected += 1;
let Tag::Compound(p) = p else {
return None;
};
for (k, v) in p {
props.push((k.to_string_lossy(), as_str(Some(v))?));
}
}
if c.len() != expected {
return None;
}
props.sort();
Some(Self { name, props })
}
}
pub struct Data {
/// One entry per `register` call.
pub instances: Vec<State>,
/// `MAP`: the instance of each id (after the defaulting of `finalizeMaps`).
map: Vec<Option<u32>>,
id_by_old: HashMap<State, i32>,
id_by_old_name: HashMap<String, i32>,
}
fn parse_props(s: &str) -> Vec<(String, String)> {
if s.is_empty() {
return Vec::new();
}
s.split(';')
.map(|kv| {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
(k.to_owned(), v.to_owned())
})
.collect()
}
pub fn data() -> &'static Data {
static DATA: OnceLock<Data> = OnceLock::new();
DATA.get_or_init(|| {
let mut map: Vec<Option<u32>> = vec![None; 4096];
let mut defaults: Vec<Option<u32>> = vec![None; 256];
let mut instances = Vec::new();
let mut id_by_old = HashMap::new();
let mut id_by_old_name: HashMap<String, i32> = HashMap::new();
for line in include_str!("block_state_data.txt").lines() {
if line.starts_with('#') || line.is_empty() {
continue;
}
let f: Vec<&str> = line.split('\t').collect();
let id: usize = f[0].parse().expect("id");
let instance = instances.len() as u32;
instances.push(State {
name: f[1].to_owned(),
props: parse_props(f.get(2).copied().unwrap_or("")),
});
map[id] = Some(instance);
if defaults[id >> 4].is_none() {
defaults[id >> 4] = Some(instance);
}
for pair in f[3..].chunks(2) {
let old = State {
name: pair[0].to_owned(),
props: parse_props(pair.get(1).copied().unwrap_or("")),
};
id_by_old_name.entry(old.name.clone()).or_insert(id as i32);
id_by_old.insert(old, id as i32);
}
}
for (i, slot) in map.iter_mut().enumerate() {
if slot.is_none() {
*slot = defaults[i >> 4];
}
}
Data {
instances,
map,
id_by_old,
id_by_old_name,
}
})
}
impl Data {
/// `getTag(id)` as an instance.
pub fn instance(&self, id: i32) -> u32 {
let slot = usize::try_from(id)
.ok()
.filter(|i| *i < 4096)
.and_then(|i| self.map[i]);
slot.or(self.map[0]).expect("air is registered")
}
pub fn state(&self, instance: u32) -> &State {
&self.instances[instance as usize]
}
}
/// `BlockStateData.getTag`.
pub fn get_tag(id: i32) -> Tag {
let d = data();
d.state(d.instance(id)).to_tag()
}
/// `BlockStateData.upgradeBlockStateTag`.
pub fn upgrade_block_state_tag(old: &Tag) -> Tag {
let d = data();
match State::from_tag(old).and_then(|s| d.id_by_old.get(&s).copied()) {
Some(id) if (0..4096).contains(&id) => match d.map[id as usize] {
Some(i) => d.state(i).to_tag(),
None => old.clone(),
},
_ => old.clone(),
}
}
/// `BlockStateData.upgradeBlock(String)`.
pub fn upgrade_block_name(old: &str) -> String {
let d = data();
match d.id_by_old_name.get(old) {
Some(&id) if (0..4096).contains(&id) => match d.map[id as usize] {
Some(i) => d.state(i).name.clone(),
None => old.to_owned(),
},
_ => old.to_owned(),
}
}
/// `BlockStateData.upgradeBlock(int)`.
pub fn upgrade_block_id(id: i32) -> String {
let d = data();
match usize::try_from(id).ok().filter(|i| *i < 4096) {
Some(i) => match d.map[i] {
Some(inst) => d.state(inst).name.clone(),
None => "minecraft:air".to_owned(),
},
None => "minecraft:air".to_owned(),
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,771 @@
//! `ChunkPalettedStorageFix` (key 1451.1): the chunk sections of the 1.12 format
//! (`Blocks`, `Data`, `Add` byte arrays) become a palette and packed `BlockStates`,
//! with the block entities that carried block state (note blocks, flower pots,
//! beds, banners, skulls) folded into the states, as vanilla does.
//!
//! Vanilla compares block states by identity (`CrudeIncrementalIntIdentityHashBiMap`
//! and an identity set): states are instances here, numbered in one space with the
//! instances of the `BlockStateData` table.
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use super::block_state_data::{self as bsd, State};
use super::dynamic::{as_bool, as_byte_buffer, as_int, as_str, ceillog2, key, set};
use crate::nbt::Tag;
/// `MappingConstants`.
struct Consts {
/// Instances: the `BlockStateData` ones first, then the constants below.
states: Vec<State>,
air: u32,
pumpkin: u32,
snowy_podzol: u32,
snowy_grass: u32,
snowy_mycelium: u32,
upper: HashMap<&'static str, u32>,
flower_pot: HashMap<String, u32>,
skull: HashMap<String, u32>,
door: HashMap<String, u32>,
note_block: HashMap<String, u32>,
bed: HashMap<String, u32>,
banner: HashMap<String, u32>,
}
const DYE_COLORS: [&str; 16] = [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black",
];
fn consts() -> &'static Consts {
static C: OnceLock<Consts> = OnceLock::new();
C.get_or_init(|| {
let mut states = bsd::data().instances.clone();
let mut add = |name: &str, props: &[(&str, &str)]| -> u32 {
states.push(State::new(name, props));
(states.len() - 1) as u32
};
let air = add("minecraft:air", &[]);
let pumpkin = add("minecraft:pumpkin", &[]);
let snowy_podzol = add("minecraft:podzol", &[("snowy", "true")]);
let snowy_grass = add("minecraft:grass_block", &[("snowy", "true")]);
let snowy_mycelium = add("minecraft:mycelium", &[("snowy", "true")]);
let mut upper = HashMap::new();
for name in [
"minecraft:sunflower",
"minecraft:lilac",
"minecraft:tall_grass",
"minecraft:large_fern",
"minecraft:rose_bush",
"minecraft:peony",
] {
upper.insert(name, add(name, &[("half", "upper")]));
}
let mut flower_pot = HashMap::new();
let pots: [(&str, &str); 22] = [
("minecraft:air0", "minecraft:flower_pot"),
("minecraft:red_flower0", "minecraft:potted_poppy"),
("minecraft:red_flower1", "minecraft:potted_blue_orchid"),
("minecraft:red_flower2", "minecraft:potted_allium"),
("minecraft:red_flower3", "minecraft:potted_azure_bluet"),
("minecraft:red_flower4", "minecraft:potted_red_tulip"),
("minecraft:red_flower5", "minecraft:potted_orange_tulip"),
("minecraft:red_flower6", "minecraft:potted_white_tulip"),
("minecraft:red_flower7", "minecraft:potted_pink_tulip"),
("minecraft:red_flower8", "minecraft:potted_oxeye_daisy"),
("minecraft:yellow_flower0", "minecraft:potted_dandelion"),
("minecraft:sapling0", "minecraft:potted_oak_sapling"),
("minecraft:sapling1", "minecraft:potted_spruce_sapling"),
("minecraft:sapling2", "minecraft:potted_birch_sapling"),
("minecraft:sapling3", "minecraft:potted_jungle_sapling"),
("minecraft:sapling4", "minecraft:potted_acacia_sapling"),
("minecraft:sapling5", "minecraft:potted_dark_oak_sapling"),
("minecraft:red_mushroom0", "minecraft:potted_red_mushroom"),
(
"minecraft:brown_mushroom0",
"minecraft:potted_brown_mushroom",
),
("minecraft:deadbush0", "minecraft:potted_dead_bush"),
("minecraft:tallgrass2", "minecraft:potted_fern"),
("minecraft:cactus0", "minecraft:potted_cactus"),
];
for (k, name) in pots {
flower_pot.insert(k.to_owned(), add(name, &[]));
}
let mut skull = HashMap::new();
for (i, name, ty) in [
(0, "skeleton", "skull"),
(1, "wither_skeleton", "skull"),
(2, "zombie", "head"),
(3, "player", "head"),
(4, "creeper", "head"),
(5, "dragon", "head"),
] {
for facing in ["north", "east", "south", "west"] {
skull.insert(
format!("{i}{facing}"),
add(
&format!("minecraft:{name}_wall_{ty}"),
&[("facing", facing)],
),
);
}
for rot in 0..16 {
skull.insert(
format!("{i}{rot}"),
add(
&format!("minecraft:{name}_{ty}"),
&[("rotation", &rot.to_string())],
),
);
}
}
let mut door = HashMap::new();
for ty in [
"oak_door",
"iron_door",
"spruce_door",
"birch_door",
"jungle_door",
"acacia_door",
"dark_oak_door",
] {
let id = format!("minecraft:{ty}");
for facing in ["east", "north", "south", "west"] {
for half in ["lower", "upper"] {
for hinge in ["left", "right"] {
for open in ["false", "true"] {
for powered in ["false", "true"] {
door.insert(
format!("{id}{facing}{half}{hinge}{open}{powered}"),
add(
&id,
&[
("facing", facing),
("half", half),
("hinge", hinge),
("open", open),
("powered", powered),
],
),
);
}
}
}
}
}
}
let mut note_block = HashMap::new();
for i in 0..26 {
for powered in ["true", "false"] {
note_block.insert(
format!("{powered}{i}"),
add(
"minecraft:note_block",
&[("powered", powered), ("note", &i.to_string())],
),
);
}
}
let mut bed = HashMap::new();
for (id, color) in DYE_COLORS.iter().enumerate() {
if *color == "red" {
continue;
}
let name = format!("minecraft:{color}_bed");
for (facing, occupied, part) in [
("south", "false", "foot"),
("west", "false", "foot"),
("north", "false", "foot"),
("east", "false", "foot"),
("south", "false", "head"),
("west", "false", "head"),
("north", "false", "head"),
("east", "false", "head"),
("south", "true", "head"),
("west", "true", "head"),
("north", "true", "head"),
("east", "true", "head"),
] {
bed.insert(
format!("{facing}{occupied}{part}{id}"),
add(
&name,
&[("facing", facing), ("occupied", occupied), ("part", part)],
),
);
}
}
let mut banner = HashMap::new();
for (id, color) in DYE_COLORS.iter().enumerate() {
if *color == "white" {
continue;
}
let color_id = 15 - id;
for i in 0..16 {
banner.insert(
format!("{i}_{color_id}"),
add(
&format!("minecraft:{color}_banner"),
&[("rotation", &i.to_string())],
),
);
}
for facing in ["north", "south", "west", "east"] {
banner.insert(
format!("{facing}_{color_id}"),
add(
&format!("minecraft:{color}_wall_banner"),
&[("facing", facing)],
),
);
}
}
Consts {
states,
air,
pumpkin,
snowy_podzol,
snowy_grass,
snowy_mycelium,
upper,
flower_pot,
skull,
door,
note_block,
bed,
banner,
}
})
}
/// The block ids (`id >> 4`) whose blocks need a second look.
const FIX: [usize; 18] = [
2, 3, 110, 140, 144, 25, 86, 26, 176, 177, 175, 64, 71, 193, 194, 195, 196, 197,
];
const VIRTUAL: &[usize] = &[
54, 146, 25, 26, 51, 53, 67, 108, 109, 114, 128, 134, 135, 136, 156, 163, 164, 180, 203, 55,
85, 113, 188, 189, 190, 191, 192, 93, 94, 101, 102, 160, 106, 107, 183, 184, 185, 186, 187,
132, 139, 199,
];
fn is_virtual(block: usize) -> bool {
VIRTUAL.contains(&block)
}
/// `getSideMask`.
fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 {
let mut s = 0;
if north {
if east {
s |= 2;
} else if west {
s |= 128;
} else {
s |= 1;
}
} else if south {
if west {
s |= 32;
} else if east {
s |= 8;
} else {
s |= 16;
}
} else if east {
s |= 4;
} else if west {
s |= 64;
}
s
}
/// A `DataLayer`: 4 bits per block.
struct Nibbles(Vec<u8>);
impl Nibbles {
fn get(&self, x: usize, y: usize, z: usize) -> i32 {
let position = y << 8 | z << 4 | x;
let byte = self.0[position >> 1];
if position & 1 == 0 {
i32::from(byte & 15)
} else {
i32::from(byte >> 4 & 15)
}
}
}
struct Section {
y: i32,
has_data: bool,
/// The `listTag`: instances in the order they were first seen.
list: Vec<u32>,
seen: HashSet<u32>,
/// `palette`: instance by palette id.
palette: Vec<u32>,
palette_ids: HashMap<u32, i32>,
to_fix: Vec<(usize, Vec<usize>)>,
update: Vec<i32>,
buffer: Vec<i32>,
raw: Tag,
}
impl Section {
fn new(raw: Tag) -> Self {
let y = as_int(raw.get("Y"), 0);
let has_data = raw.get("Blocks").is_some();
Self {
y,
has_data,
list: Vec::new(),
seen: HashSet::new(),
palette: Vec::new(),
palette_ids: HashMap::new(),
to_fix: Vec::new(),
update: Vec::new(),
buffer: vec![0; 4096],
raw,
}
}
fn get_block(&self, pos: usize) -> u32 {
if pos <= 4095 {
self.palette
.get(self.buffer[pos] as usize)
.copied()
.unwrap_or_else(|| consts().air)
} else {
consts().air
}
}
fn set_block(&mut self, idx: usize, state: u32) {
if self.seen.insert(state) {
self.list.push(state);
}
let id = match self.palette_ids.get(&state) {
Some(id) => *id,
None => {
self.palette.push(state);
let id = (self.palette.len() - 1) as i32;
self.palette_ids.insert(state, id);
id
}
};
self.buffer[idx] = id;
}
fn add_fix(&mut self, block: usize, position: usize) {
match self.to_fix.iter_mut().find(|(b, _)| *b == block) {
Some((_, list)) => list.push(position),
None => self.to_fix.push((block, vec![position])),
}
}
fn upgrade(&mut self, mut sides: i32) -> i32 {
if !self.has_data {
return sides;
}
let blocks = as_byte_buffer(self.raw.get("Blocks")).unwrap_or_default();
let nibbles = |name: &str| {
as_byte_buffer(self.raw.get(name))
.map(Nibbles)
.unwrap_or_else(|| Nibbles(vec![0; 2048]))
};
let data = nibbles("Data");
let add_blocks = nibbles("Add");
let c = consts();
self.seen.insert(c.air);
self.palette.push(c.air);
self.palette_ids.insert(c.air, 0);
self.list.push(c.air);
let d = bsd::data();
for idx in 0..4096usize {
let (xx, yy, zz) = (idx & 15, idx >> 8 & 15, idx >> 4 & 15);
let id = add_blocks.get(xx, yy, zz) << 12
| i32::from(blocks.get(idx).copied().unwrap_or(0)) << 4
| data.get(xx, yy, zz);
let block = (id >> 4) as usize;
if FIX.contains(&block) {
self.add_fix(block, idx);
}
if is_virtual(block) {
let s = side_mask(xx == 0, xx == 15, zz == 0, zz == 15);
if s == 0 {
self.update.push(idx as i32);
} else {
sides |= s;
}
}
self.set_block(idx, d.instance(id));
}
sides
}
fn write(&self) -> Tag {
let mut section = self.raw.clone();
if !self.has_data {
return section;
}
let c = consts();
let palette: Vec<Tag> = self
.list
.iter()
.map(|s| {
let state = &c.states[*s as usize];
if state.name == "%%FILTER_ME%%" {
c.states[c.air as usize].to_tag()
} else {
state.to_tag()
}
})
.collect();
set(&mut section, "Palette", Tag::List(palette));
let bits = ceillog2(self.seen.len()).max(4) as usize;
let mut storage = vec![0i64; (4096 * bits).div_ceil(64)];
let mask = (1i64 << bits) - 1;
for (index, value) in self.buffer.iter().enumerate() {
let value = i64::from(*value);
let position = index * bits;
let start = position >> 6;
let end = ((index + 1) * bits - 1) >> 6;
let start_bit = position ^ (start << 6);
storage[start] = storage[start] & !(mask << start_bit) | (value & mask) << start_bit;
if start != end {
let shift = 64 - start_bit;
let wanted = bits - shift;
storage[end] =
((storage[end] as u64) >> wanted << wanted) as i64 | (value & mask) >> shift;
}
}
set(&mut section, "BlockStates", Tag::LongArray(storage));
for f in ["Blocks", "Data", "Add"] {
super::dynamic::remove(&mut section, f);
}
section
}
}
#[derive(Clone, Copy)]
enum Direction {
Down,
Up,
}
fn relative(pos: i64, direction: Direction) -> i64 {
let y = (pos >> 8)
+ if matches!(direction, Direction::Up) {
1
} else {
-1
};
if (0..=255).contains(&y) {
pos & 0xFF | y << 8
} else {
-1
}
}
struct UpgradeChunk {
sides: i32,
sections: Vec<Option<Section>>,
/// `Int2ObjectLinkedOpenHashMap`: insertion order, a repeated key keeps its place.
block_entities: Vec<(i64, Tag)>,
}
impl UpgradeChunk {
fn block_entity(&self, pos: i64) -> Option<&Tag> {
self.block_entities
.iter()
.find(|(k, _)| *k == pos)
.map(|(_, v)| v)
}
fn remove_block_entity(&mut self, pos: i64) -> Option<Tag> {
let i = self.block_entities.iter().position(|(k, _)| *k == pos)?;
Some(self.block_entities.remove(i).1)
}
fn section(&self, pos: i64) -> Option<&Section> {
self.sections.get((pos >> 12) as usize)?.as_ref()
}
fn get_block(&self, pos: i64) -> u32 {
if (0..=65535).contains(&pos) {
match self.section(pos) {
Some(s) => s.get_block((pos & 4095) as usize),
None => consts().air,
}
} else {
consts().air
}
}
fn set_block(&mut self, pos: i64, block: u32) {
if (0..=65535).contains(&pos)
&& let Some(Some(s)) = self.sections.get_mut((pos >> 12) as usize)
{
s.set_block((pos & 4095) as usize, block);
}
}
fn name(&self, pos: i64) -> &str {
&consts().states[self.get_block(pos) as usize].name
}
fn state(&self, pos: i64) -> &State {
&consts().states[self.get_block(pos) as usize]
}
}
/// `ChunkPalettedStorageFix.fix` over a chunk (`{Level: ...}`).
pub(super) fn fix(chunk: &mut Tag) {
let Some(level) = chunk.get_mut("Level") else {
return;
};
if !matches!(level.get("Sections"), Some(Tag::List(_))) {
return;
}
let new_level = upgrade_level(level);
*level = new_level;
}
fn upgrade_level(level: &Tag) -> Tag {
let c = consts();
let x0 = as_int(level.get("xPos"), 0) << 4;
let z0 = as_int(level.get("zPos"), 0) << 4;
let mut chunk = UpgradeChunk {
sides: 0,
sections: (0..16).map(|_| None).collect(),
block_entities: Vec::new(),
};
if let Some(Tag::List(entities)) = level.get("TileEntities") {
for entity in entities {
let x = i64::from(as_int(entity.get("x"), 0).wrapping_sub(x0) & 15);
let y = i64::from(as_int(entity.get("y"), 0));
let z = i64::from(as_int(entity.get("z"), 0).wrapping_sub(z0) & 15);
let k = (y << 8) | (z << 4) | x;
match chunk.block_entities.iter_mut().find(|(key, _)| *key == k) {
Some((_, v)) => *v = entity.clone(),
None => chunk.block_entities.push((k, entity.clone())),
}
}
}
let converted_from_alpha = as_bool(level.get("convertedFromAlphaFormat"), false);
if let Some(Tag::List(sections)) = level.get("Sections") {
for raw in sections {
let mut section = Section::new(raw.clone());
chunk.sides = section.upgrade(chunk.sides);
let y = section.y;
if (0..16).contains(&y) {
chunk.sections[y as usize] = Some(section);
}
}
}
for si in 0..16 {
let Some(section) = &chunk.sections[si] else {
continue;
};
let to_fix = section.to_fix.clone();
let section_y = section.y as i64;
for (block, positions) in to_fix {
let dy = section_y << 12;
for pos in positions {
let pos = pos as i64 | dy;
fix_block(&mut chunk, c, block, pos, converted_from_alpha);
}
}
}
// write()
let mut out = level.clone();
if chunk.block_entities.is_empty() {
super::dynamic::remove(&mut out, "TileEntities");
} else {
set(
&mut out,
"TileEntities",
Tag::List(
chunk
.block_entities
.iter()
.map(|(_, v)| v.clone())
.collect(),
),
);
}
let mut indices = crate::nbt::Compound::new();
let mut sections = Vec::new();
for section in chunk.sections.iter().flatten() {
sections.push(section.write());
indices.insert(
key(&section.y.to_string()),
Tag::IntArray(section.update.clone()),
);
}
let upgrade_data = Tag::compound([
("Sides", Tag::Byte(chunk.sides as i8)),
("Indices", Tag::Compound(indices)),
]);
set(&mut out, "UpgradeData", upgrade_data);
set(&mut out, "Sections", Tag::List(sections));
out
}
fn fix_block(chunk: &mut UpgradeChunk, c: &Consts, block: usize, pos: i64, alpha: bool) {
let up = relative(pos, Direction::Up);
let down = relative(pos, Direction::Down);
let is_snow = |n: &str| n == "minecraft:snow" || n == "minecraft:snow_layer";
match block {
2 => {
if chunk.name(pos) == "minecraft:grass_block" && is_snow(chunk.name(up)) {
chunk.set_block(pos, c.snowy_grass);
}
}
3 => {
if chunk.name(pos) == "minecraft:podzol" && is_snow(chunk.name(up)) {
chunk.set_block(pos, c.snowy_podzol);
}
}
25 => {
if let Some(entity) = chunk.remove_block_entity(pos) {
let note = as_int(entity.get("note"), 0).clamp(0, 24) as i8;
let k = format!("{}{}", as_bool(entity.get("powered"), false), note);
let state = c
.note_block
.get(&k)
.or_else(|| c.note_block.get("false0"))
.copied()
.expect("note block");
chunk.set_block(pos, state);
}
}
26 => {
if let Some(entity) = chunk.block_entity(pos) {
let color = as_int(entity.get("color"), 0);
let state = chunk.state(pos);
if color != 14 && (0..16).contains(&color) {
let k = format!(
"{}{}{}{}",
state.property("facing"),
state.property("occupied"),
state.property("part"),
color
);
if let Some(s) = c.bed.get(&k).copied() {
chunk.set_block(pos, s);
}
}
}
}
64 | 71 | 193..=197 => {
if chunk.name(pos).ends_with("_door") {
let lower = chunk.state(pos).clone();
if lower.property("half") == "lower" {
let above = up;
let upper = chunk.state(above).clone();
if lower.name == upper.name {
let facing = lower.property("facing");
let open = lower.property("open");
let hinge = if alpha {
"left"
} else {
upper.property("hinge")
};
let powered = if alpha {
"false"
} else {
upper.property("powered")
};
let name = &lower.name;
let lo = c
.door
.get(&format!("{name}{facing}lower{hinge}{open}{powered}"))
.copied();
let hi = c
.door
.get(&format!("{name}{facing}upper{hinge}{open}{powered}"))
.copied();
if let (Some(lo), Some(hi)) = (lo, hi) {
chunk.set_block(pos, lo);
chunk.set_block(above, hi);
}
}
}
}
}
86 => {
if chunk.name(pos) == "minecraft:carved_pumpkin" {
let below = chunk.name(down);
if below == "minecraft:grass_block" || below == "minecraft:dirt" {
chunk.set_block(pos, c.pumpkin);
}
}
}
110 => {
if chunk.name(pos) == "minecraft:mycelium" && is_snow(chunk.name(up)) {
chunk.set_block(pos, c.snowy_mycelium);
}
}
140 => {
if let Some(entity) = chunk.remove_block_entity(pos) {
let item = as_str(entity.get("Item")).unwrap_or_default();
let k = format!("{}{}", item, as_int(entity.get("Data"), 0));
let state = c
.flower_pot
.get(&k)
.or_else(|| c.flower_pot.get("minecraft:air0"))
.copied()
.expect("flower pot");
chunk.set_block(pos, state);
}
}
144 => {
if let Some(entity) = chunk.block_entity(pos) {
let ty = as_int(entity.get("SkullType"), 0).to_string();
let facing = chunk.state(pos).property("facing").to_owned();
let k = if facing != "up" && facing != "down" {
format!("{ty}{facing}")
} else {
format!("{ty}{}", as_int(entity.get("Rot"), 0))
};
// `entity.remove(...)` on an immutable Dynamic changes nothing.
let state = c
.skull
.get(&k)
.or_else(|| c.skull.get("0north"))
.copied()
.expect("skull");
chunk.set_block(pos, state);
}
}
175 => {
if chunk.state(pos).property("half") == "upper" {
let variant = chunk.name(down).to_owned();
if let Some(s) = c.upper.get(variant.as_str()).copied() {
chunk.set_block(pos, s);
}
}
}
176 | 177 => {
if let Some(entity) = chunk.block_entity(pos) {
let color = as_int(entity.get("Base"), 0);
let state = chunk.state(pos);
if color != 15 && (0..16).contains(&color) {
let prop = state.property(if block == 176 { "rotation" } else { "facing" });
let k = format!("{prop}_{color}");
if let Some(s) = c.banner.get(&k).copied() {
chunk.set_block(pos, s);
}
}
}
}
_ => {}
}
}
@@ -0,0 +1,513 @@
//! `LeavesFix` (key 1496) and `TrappedChestBlockEntityFix` (key 1624): fixes that
//! read the packed block states of the sections of a chunk.
//!
//! `LeavesFix` visits blocks in the iteration order of fastutil hash sets, and the
//! order decides in which order its new palette entries appear: the sets are
//! emulated here (`IntOpenHashSet` and the key order of an `Int2ObjectOpenHashMap`).
use std::collections::{HashMap, HashSet};
use super::dynamic::{as_int, as_long_stream, as_str, ceillog2, set};
use crate::nbt::Tag;
/// `PackedBitStorage`.
#[derive(Clone)]
struct Packed {
data: Vec<i64>,
bits: usize,
mask: i64,
}
impl Packed {
fn new(bits: usize, data: Vec<i64>) -> Option<Self> {
(data.len() == (4096 * bits).div_ceil(64)).then(|| Self {
data,
bits,
mask: (1i64 << bits) - 1,
})
}
fn zeroed(bits: usize) -> Self {
Self::new(bits, vec![0; (4096 * bits).div_ceil(64)]).expect("length")
}
fn set(&mut self, index: usize, value: i32) {
let position = index * self.bits;
let start = position >> 6;
let end = ((index + 1) * self.bits - 1) >> 6;
let start_bit = position ^ (start << 6);
let value = i64::from(value);
self.data[start] =
self.data[start] & !(self.mask << start_bit) | (value & self.mask) << start_bit;
if start != end {
let shift = 64 - start_bit;
let wanted = self.bits - shift;
self.data[end] =
((self.data[end] as u64) >> wanted << wanted) as i64 | (value & self.mask) >> shift;
}
}
fn get(&self, index: usize) -> i32 {
let position = index * self.bits;
let start = position >> 6;
let end = ((index + 1) * self.bits - 1) >> 6;
let start_bit = position ^ (start << 6);
if start == end {
return (((self.data[start] as u64) >> start_bit) as i64 & self.mask) as i32;
}
let shift = 64 - start_bit;
((((self.data[start] as u64) >> start_bit) as i64 | self.data[end] << shift) & self.mask)
as i32
}
}
// ------------------------------------------------------------------ fastutil
fn array_size(expected: usize) -> usize {
// arraySize(expected, 0.75f): nextPowerOfTwo(ceil(expected / f)), at least 2
let need = (expected as f64 / 0.75f32 as f64).ceil() as usize;
need.next_power_of_two().max(2)
}
fn max_fill(n: usize) -> usize {
((n as f64 * 0.75f32 as f64).ceil() as usize).min(n - 1)
}
fn mix(x: i32) -> usize {
let h = x.wrapping_mul(0x9E37_79B9u32 as i32);
(h ^ ((h as u32) >> 16) as i32) as u32 as usize
}
/// `IntOpenHashSet`: add and iteration order.
struct IntSet {
key: Vec<i32>,
n: usize,
max_fill: usize,
size: usize,
contains_null: bool,
}
impl IntSet {
/// `new IntOpenHashSet()`.
fn new() -> Self {
Self::sized(16)
}
fn sized(expected: usize) -> Self {
let n = array_size(expected);
Self {
key: vec![0; n + 1],
n,
max_fill: max_fill(n),
size: 0,
contains_null: false,
}
}
fn add(&mut self, k: i32) -> bool {
if k == 0 {
if self.contains_null {
return false;
}
self.contains_null = true;
} else {
let mask = self.n - 1;
let mut pos = mix(k) & mask;
while self.key[pos] != 0 {
if self.key[pos] == k {
return false;
}
pos = (pos + 1) & mask;
}
self.key[pos] = k;
}
let grow = self.size >= self.max_fill;
self.size += 1;
if grow {
self.rehash(array_size(self.size + 1));
}
true
}
fn rehash(&mut self, new_n: usize) {
let mask = new_n - 1;
let mut new_key = vec![0; new_n + 1];
let real = if self.contains_null {
self.size - 1
} else {
self.size
};
let mut i = self.n;
for _ in 0..real {
loop {
i -= 1;
if self.key[i] != 0 {
break;
}
}
let mut pos = mix(self.key[i]) & mask;
while new_key[pos] != 0 {
pos = (pos + 1) & mask;
}
new_key[pos] = self.key[i];
}
self.n = new_n;
self.max_fill = max_fill(new_n);
self.key = new_key;
}
/// The elements in iteration order: the null key first, then the table from its end.
fn order(&self) -> Vec<i32> {
let mut out = Vec::with_capacity(self.size);
if self.contains_null {
out.push(0);
}
for pos in (0..self.n).rev() {
if self.key[pos] != 0 {
out.push(self.key[pos]);
}
}
out
}
}
/// The section indices in the iteration order of
/// `new Int2ObjectOpenHashMap<>(hashMapOfTheSections)`.
fn section_order(indices: &[i32]) -> Vec<i32> {
let mut sorted = indices.to_vec();
sorted.sort_unstable();
let mut set = IntSet::sized(sorted.len());
for i in sorted {
set.add(i);
}
set.order()
}
// ------------------------------------------------------------------ sections
fn leaf_index(name: &str) -> Option<i32> {
Some(match name {
"minecraft:acacia_leaves" => 0,
"minecraft:birch_leaves" => 1,
"minecraft:dark_oak_leaves" => 2,
"minecraft:jungle_leaves" => 3,
"minecraft:oak_leaves" => 4,
"minecraft:spruce_leaves" => 5,
_ => return None,
})
}
const LOGS: [&str; 18] = [
"minecraft:acacia_bark",
"minecraft:birch_bark",
"minecraft:dark_oak_bark",
"minecraft:jungle_bark",
"minecraft:oak_bark",
"minecraft:spruce_bark",
"minecraft:acacia_log",
"minecraft:birch_log",
"minecraft:dark_oak_log",
"minecraft:jungle_log",
"minecraft:oak_log",
"minecraft:spruce_log",
"minecraft:stripped_acacia_log",
"minecraft:stripped_birch_log",
"minecraft:stripped_dark_oak_log",
"minecraft:stripped_jungle_log",
"minecraft:stripped_oak_log",
"minecraft:stripped_spruce_log",
];
/// A section as `LeavesFix.Section` reads it.
struct Section {
index: i32,
palette: Vec<Tag>,
storage: Option<Packed>,
leaf_ids: HashSet<i32>,
log_ids: HashSet<i32>,
state_to_id: HashMap<i32, i32>,
}
fn name_of(state: &Tag) -> String {
as_str(state.get("Name")).unwrap_or_default()
}
fn state_id(name: &str, persistent: bool, distance: i32) -> i32 {
leaf_index(name).unwrap_or(0) << 5 | if persistent { 16 } else { 0 } | distance
}
fn leaf_tag(name: &str, persistent: bool, distance: i32) -> Tag {
Tag::compound([
(
"Properties",
Tag::compound([
(
"persistent",
super::dynamic::string(if persistent { "true" } else { "false" }),
),
("distance", super::dynamic::string(&distance.to_string())),
]),
),
("Name", super::dynamic::string(name)),
])
}
impl Section {
/// `LeavesSection` constructor: reads the palette, and rewrites its leaf states.
fn read_leaves(section: &Tag) -> Self {
let mut s = Self::read(section);
// skippable()
for i in 0..s.palette.len() {
let name = name_of(&s.palette[i]);
if leaf_index(&name).is_some() {
let persistent = as_str(
s.palette[i]
.get("Properties")
.and_then(|p| p.get("decayable")),
)
.is_some_and(|d| d == "false");
s.leaf_ids.insert(i as i32);
s.state_to_id
.insert(state_id(&name, persistent, 7), i as i32);
s.palette[i] = leaf_tag(&name, persistent, 7);
}
if LOGS.contains(&name.as_str()) {
s.log_ids.insert(i as i32);
}
}
s.finish_read(section, s.leaf_ids.is_empty() && s.log_ids.is_empty());
s
}
fn read(section: &Tag) -> Self {
let palette = match section.get("Palette") {
Some(Tag::List(l)) => l.clone(),
_ => Vec::new(),
};
Self {
index: as_int(section.get("Y"), 0),
palette,
storage: None,
leaf_ids: HashSet::new(),
log_ids: HashSet::new(),
state_to_id: HashMap::new(),
}
}
fn finish_read(&mut self, section: &Tag, skippable: bool) {
if skippable {
self.storage = None;
} else {
let states = as_long_stream(section.get("BlockStates")).unwrap_or_default();
let size = ceillog2(self.palette.len()).max(4) as usize;
self.storage = Packed::new(size, states);
}
}
fn is_skippable(&self) -> bool {
self.storage.is_none()
}
fn block(&self, pos: usize) -> i32 {
self.storage.as_ref().map_or(0, |s| s.get(pos))
}
fn is_leaf(&self, block: i32) -> bool {
self.leaf_ids.contains(&block)
}
fn is_log(&self, block: i32) -> bool {
self.log_ids.contains(&block)
}
fn distance(&self, block: i32) -> i32 {
if self.is_log(block) {
return 0;
}
self.palette
.get(block as usize)
.and_then(|p| p.get("Properties"))
.and_then(|p| as_str(p.get("distance")))
.and_then(|d| d.parse().ok())
.unwrap_or(0)
}
fn set_distance(&mut self, pos: usize, block: i32, distance: i32) {
let base = self.palette[block as usize].clone();
let name = name_of(&base);
let persistent = as_str(base.get("Properties").and_then(|p| p.get("persistent")))
.is_some_and(|p| p == "true");
let id_key = state_id(&name, persistent, distance);
if !self.state_to_id.contains_key(&id_key) {
let id = self.palette.len() as i32;
self.leaf_ids.insert(id);
self.state_to_id.insert(id_key, id);
self.palette.push(leaf_tag(&name, persistent, distance));
}
let id = self.state_to_id[&id_key];
let storage = self.storage.as_mut().expect("storage");
if 1i64 << storage.bits <= i64::from(id) {
let mut grown = Packed::zeroed(storage.bits + 1);
for i in 0..4096 {
grown.set(i, storage.get(i));
}
*storage = grown;
}
storage.set(pos, id);
}
fn write(&self, section: &mut Tag) {
let Some(storage) = &self.storage else {
return;
};
set(section, "BlockStates", Tag::LongArray(storage.data.clone()));
set(section, "Palette", Tag::List(self.palette.clone()));
}
}
fn get_index(x: i32, y: i32, z: i32) -> i32 {
y << 8 | z << 4 | x
}
fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 {
let mut s = 0;
if north {
if east {
s |= 2;
} else if west {
s |= 128;
} else {
s |= 1;
}
} else if south {
if west {
s |= 32;
} else if east {
s |= 8;
} else {
s |= 16;
}
} else if east {
s |= 4;
} else if west {
s |= 64;
}
s
}
/// `LeavesFix` over a chunk (`{Level: ...}`).
pub(super) fn leaves_fix(chunk: &mut Tag) {
let Some(level) = chunk.get_mut("Level") else {
return;
};
let Some(Tag::List(raw_sections)) = level.get("Sections").cloned() else {
return;
};
let mut sections: Vec<Section> = raw_sections.iter().map(Section::read_leaves).collect();
if sections.iter().all(Section::is_skippable) {
return;
}
let mut sides = 0;
let mut queue: Vec<IntSet> = (0..7).map(|_| IntSet::new()).collect();
let indices: Vec<i32> = sections.iter().map(|s| s.index).collect();
for index in section_order(&indices) {
let Some(section) = sections.iter().find(|s| s.index == index) else {
continue;
};
if section.is_skippable() {
continue;
}
for i in 0..4096usize {
let block = section.block(i);
if section.is_log(block) {
queue[0].add(section.index << 12 | i as i32);
} else if section.is_leaf(block) {
let x = (i & 15) as i32;
let z = (i >> 4 & 15) as i32;
sides |= side_mask(x == 0, x == 15, z == 0, z == 15);
}
}
}
const DIRECTIONS: [[i32; 3]; 6] = [
[-1, 0, 0],
[1, 0, 0],
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
];
for i in 1..7 {
let current = queue[i - 1].order();
for pos_chunk in current {
let x = pos_chunk & 15;
let y = pos_chunk >> 8 & 0xFF;
let z = pos_chunk >> 4 & 15;
for d in DIRECTIONS {
let (nx, ny, nz) = (x + d[0], y + d[1], z + d[2]);
if !(0..=15).contains(&nx) || !(0..=15).contains(&nz) || !(0..=255).contains(&ny) {
continue;
}
let Some(section) = sections.iter_mut().find(|s| s.index == ny >> 4) else {
continue;
};
if section.is_skippable() {
continue;
}
let pos_section = get_index(nx, ny & 15, nz) as usize;
let block = section.block(pos_section);
if section.is_leaf(block) && section.distance(block) > i as i32 {
section.set_distance(pos_section, block, i as i32);
queue[i].add(get_index(nx, ny, nz));
}
}
}
}
if let Some(Tag::List(list)) = level.get_mut("Sections") {
for raw in list.iter_mut() {
let y = as_int(raw.get("Y"), 0);
if let Some(section) = sections.iter().find(|s| s.index == y) {
section.write(raw);
}
}
}
if sides != 0 {
let mut upgrade = level
.get("UpgradeData")
.cloned()
.unwrap_or_else(super::dynamic::empty_map);
let old = as_int(upgrade.get("Sides"), 0) as i8;
set(&mut upgrade, "Sides", Tag::Byte(old | sides as i8));
set(level, "UpgradeData", upgrade);
}
}
/// `TrappedChestBlockEntityFix` over a chunk (`{Level: ...}`).
pub(super) fn trapped_chest_fix(chunk: &mut Tag) {
let Some(level) = chunk.get_mut("Level") else {
return;
};
let Some(Tag::List(raw_sections)) = level.get("Sections").cloned() else {
return;
};
let mut chests: HashSet<i32> = HashSet::new();
for raw in &raw_sections {
let mut section = Section::read(raw);
let ids: HashSet<i32> = section
.palette
.iter()
.enumerate()
.filter(|(_, p)| name_of(p) == "minecraft:trapped_chest")
.map(|(i, _)| i as i32)
.collect();
section.finish_read(raw, ids.is_empty());
if section.is_skippable() {
continue;
}
for i in 0..4096usize {
if ids.contains(&section.block(i)) {
chests.insert(section.index << 12 | i as i32);
}
}
}
let chunk_x = as_int(level.get("xPos"), 0);
let chunk_z = as_int(level.get("zPos"), 0);
if let Some(Tag::List(entities)) = level.get_mut("TileEntities") {
for be in entities {
if !super::schema::block_entity_known(be, super::schema::key(1624, 0) - 1) {
continue;
}
let x = as_int(be.get("x"), 0).wrapping_sub(chunk_x << 4);
let y = as_int(be.get("y"), 0);
let z = as_int(be.get("z"), 0).wrapping_sub(chunk_z << 4);
if chests.contains(&get_index(x, y, z)) {
set(be, "id", super::dynamic::string("minecraft:trapped_chest"));
}
}
}
}
+235 -4
View File
@@ -19,7 +19,7 @@ pub const VERSION_NAME: &str = "26.3";
const FILE_FIXER_INTRODUCTION: i32 = 4772;
/// The versions of the file fixes, in order.
const FILE_FIXES: [i32; 3] = [4772, 4773, 4899];
const FILE_FIXES: [i32; 4] = [1493, 4772, 4773, 4899];
fn invalid(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.into())
@@ -38,6 +38,23 @@ pub fn read_dat(path: &Path) -> io::Result<Option<Tag>> {
Ok(Some(root.tag))
}
/// `SavedDataStorage.readTagFromDisk`: a file without the gzip header is plain NBT.
pub fn read_saved_dat(path: &Path) -> io::Result<Option<Tag>> {
let bytes = match fs::read(path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let limits = Limits::default();
let raw = if bytes.starts_with(&[0x1f, 0x8b]) {
Compression::Gzip.decode(&bytes, limits.max_bytes)?
} else {
bytes
};
let (root, _) = nbt::read_named(&raw, limits).map_err(|e| invalid(e.to_string()))?;
Ok(Some(root.tag))
}
/// `NbtIo.writeCompressed`, creating the parent folders.
pub fn write_dat(path: &Path, tag: &Tag) -> io::Result<()> {
if let Some(parent) = path.parent() {
@@ -381,6 +398,141 @@ fn level_dat_to_saved_data(base: &Path) -> io::Result<()> {
write_level(base, content, V)
}
/// 1493: `LegacyStructureFileFix`. The structures of `data/*.dat` (1.12) become the
/// `Structures` of the chunks they reach, in the region folders of the old layout.
pub(crate) fn fix_1493(base: &Path) -> io::Result<()> {
use std::collections::{BTreeMap, HashMap};
const LEGACY_TO_CURRENT: [(&str, &str); 4] = [
("Iglu", "Igloo"),
("TeDP", "Desert_Pyramid"),
("TeJP", "Jungle_Pyramid"),
("TeSH", "Swamp_Hut"),
];
#[derive(Default)]
struct LegacyData {
starts: HashMap<String, Tag>,
indexes: BTreeMap<String, Vec<i64>>,
}
let pack = |x: i32, z: i32| i64::from(x) & 0xFFFF_FFFF | (i64::from(z) & 0xFFFF_FFFF) << 32;
let Some(level) = read_level(base, 1493)? else {
return Ok(());
};
let overworld_generator = match as_str(level.get("generatorName")).as_deref() {
Some("flat") => "minecraft:flat",
Some("debug_all_block_states") => "minecraft:debug",
_ => "minecraft:noise",
};
let dimensions: [(&[&str], &str, &str, &str); 3] = [
(
&["Monument", "Stronghold", "Mineshaft", "Temple", "Mansion"],
"",
"minecraft:overworld",
overworld_generator,
),
(
&["Fortress"],
"DIM-1",
"minecraft:the_nether",
"minecraft:noise",
),
(&["EndCity"], "DIM1", "minecraft:the_end", "minecraft:noise"),
];
for (ids, folder, dimension, generator) in dimensions {
let mut structures: BTreeMap<(i32, i32), LegacyData> = BTreeMap::new();
for id in ids {
let path = base.join("data").join(format!("{id}.dat"));
let Some(data) = read_saved_data(&path, Ty::SavedStructureFeatureIndices, 1493)? else {
continue;
};
let Some(Tag::Compound(features)) = data.get("Features") else {
continue;
};
let values: Vec<(String, Tag)> = features
.iter()
.map(|(k, v)| (k.to_string_lossy(), v.clone()))
.collect();
for (_, mut value) in super::items::java_hash_order(values, |(k, _)| k.clone()) {
let chunk_x = as_int(value.get("ChunkX"), 0);
let chunk_z = as_int(value.get("ChunkZ"), 0);
let children = super::dynamic::stream(value.get("Children"));
if let Some(first) = children.first()
&& let Some(current) = as_str(first.get("id"))
.and_then(|i| LEGACY_TO_CURRENT.iter().find(|(from, _)| *from == i))
{
set(&mut value, "id", string(current.1));
}
let Some(feature_id) = as_str(value.get("id")) else {
continue;
};
structures
.entry((chunk_x, chunk_z))
.or_default()
.starts
.insert(feature_id.clone(), value);
for nx in chunk_x - 8..=chunk_x + 8 {
for nz in chunk_z - 8..=chunk_z + 8 {
structures
.entry((nx, nz))
.or_default()
.indexes
.entry(feature_id.clone())
.or_default()
.push(pack(chunk_x, chunk_z));
}
}
}
}
if structures.is_empty() {
continue;
}
let region = if folder.is_empty() {
base.join("region")
} else {
base.join(folder).join("region")
};
upgrade_regions(&region, |tag| {
let version = as_int(tag.get("DataVersion"), -1);
let x = as_int(tag.get("Level").and_then(|l| l.get("xPos")), 0);
let z = as_int(tag.get("Level").and_then(|l| l.get("zPos")), 0);
let Some(legacy) = structures.get(&(x, z)) else {
return;
};
let _ = version;
super::update_chunk_to(tag, dimension, Some(generator), 1493);
let mut level = tag
.get("Level")
.cloned()
.unwrap_or_else(super::dynamic::empty_map);
let mut structure = level
.get("Structures")
.cloned()
.filter(|s| matches!(s, Tag::Compound(_)))
.unwrap_or_else(super::dynamic::empty_map);
let mut starts = structure
.get("Starts")
.cloned()
.filter(|s| matches!(s, Tag::Compound(_)))
.unwrap_or_else(super::dynamic::empty_map);
let mut references = structure
.get("References")
.cloned()
.filter(|s| matches!(s, Tag::Compound(_)))
.unwrap_or_else(super::dynamic::empty_map);
for (id, value) in &legacy.starts {
set(&mut starts, id, value.clone());
}
for (id, indexes) in &legacy.indexes {
set(&mut references, id, Tag::LongArray(indexes.clone()));
}
set(&mut structure, "Starts", starts);
set(&mut structure, "References", references);
set(&mut level, "Structures", structure);
set(tag, "Level", level);
})?;
}
Ok(())
}
/// 4773: `GeneratedStructuresRenameFileFix`.
fn fix_4773(base: &Path) -> io::Result<()> {
for ns in subdirectories(&base.join("generated")) {
@@ -456,6 +608,7 @@ pub fn fix_world_files(base: &Path) -> io::Result<i32> {
for version in FILE_FIXES {
if version > start && version <= CURRENT {
match version {
1493 => fix_1493(base)?,
4772 => fix_4772(base)?,
4773 => fix_4773(base)?,
_ => fix_4899(base)?,
@@ -571,7 +724,7 @@ fn upgrade_saved_data(data: &Path) -> io::Result<()> {
let Some(ty) = super::saved_data_type(&relative) else {
continue;
};
if let Some(mut tag) = read_dat(&file)? {
if let Some(mut tag) = read_saved_dat(&file)? {
super::update_saved_data(ty, &mut tag);
set(&mut tag, "DataVersion", Tag::Int(CURRENT));
write_dat(&file, &tag)?;
@@ -611,6 +764,10 @@ fn tag_to_json(t: &Tag) -> Json {
}
fn upgrade_json(path: &Path, ty: Ty) -> io::Result<()> {
upgrade_json_to(path, ty, CURRENT)
}
fn upgrade_json_to(path: &Path, ty: Ty, to: i32) -> io::Result<()> {
let text = fs::read_to_string(path)?;
let units: Vec<u16> = text.encode_utf16().collect();
let parsed = json::parse_lenient(&units)
@@ -621,8 +778,8 @@ fn upgrade_json(path: &Path, ty: Ty) -> io::Result<()> {
// `PlayerAdvancements`: the version field is not part of the data.
remove(&mut tag, "DataVersion");
}
update(ty, &mut tag, from, CURRENT);
set(&mut tag, "DataVersion", Tag::Int(CURRENT));
update(ty, &mut tag, from, to);
set(&mut tag, "DataVersion", Tag::Int(to));
let out = json::to_stable_string(&tag_to_json(&tag));
fs::write(path, String::from_utf16_lossy(&out))
}
@@ -672,6 +829,80 @@ pub fn upgrade_world_data(base: &Path) -> io::Result<()> {
Ok(())
}
/// A world in the layout of before 1.16 (dimension folders in the world folder,
/// `playerdata`, `stats`, `advancements`) brought to DataVersion `target` and
/// no further, with the file fixes of that range but not the ones that move the
/// files into the 26.x layout: the harness checks the fixes of a range of
/// versions on their own (the vanilla oracle does the same given a target).
pub fn upgrade_band(base: &Path, target: i32) -> io::Result<()> {
if target >= 1493 {
fix_1493(base)?;
}
let level = base.join("level.dat");
if let Some(mut root) = read_dat(&level)? {
let mut data = root
.get("Data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()));
let from = data_version(&data, -1);
update(Ty::Level, &mut data, from, target);
set(&mut data, "DataVersion", Tag::Int(target));
set(&mut root, "Data", data);
write_dat(&level, &root)?;
}
for (folder, id) in [
("", "minecraft:overworld"),
("DIM-1", "minecraft:the_nether"),
("DIM1", "minecraft:the_end"),
] {
let dim = base.join(folder);
upgrade_regions(&dim.join("region"), |tag| {
super::update_chunk_to(tag, id, None, target)
})?;
upgrade_regions(&dim.join("entities"), |tag| {
super::update_region_tag_to(Ty::EntityChunk, tag, target)
})?;
upgrade_regions(&dim.join("poi"), |tag| {
super::update_region_tag_to(Ty::PoiChunk, tag, target)
})?;
}
for file in files_with_suffix(&base.join("playerdata"), ".dat") {
if let Some(mut tag) = read_dat(&file)? {
super::update_player_to(&mut tag, target);
write_dat(&file, &tag)?;
}
}
for (folder, ty) in [("advancements", Ty::Advancements), ("stats", Ty::Stats)] {
for file in files_with_suffix(&base.join(folder), ".json") {
upgrade_json_to(&file, ty, target)?;
}
}
// The saved data of the old layout.
for file in files_with_suffix(&base.join("data"), ".dat") {
let name = file
.file_stem()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let ty = match name.as_str() {
"scoreboard" => Ty::SavedScoreboard,
n if n
.strip_prefix("map_")
.is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())) =>
{
Ty::SavedMapData
}
_ => continue,
};
if let Some(mut tag) = read_dat(&file)? {
let from = data_version(&tag, 1343);
update(ty, &mut tag, from, target);
set(&mut tag, "DataVersion", Tag::Int(target));
write_dat(&file, &tag)?;
}
}
Ok(())
}
/// Bring a whole world saved by 1.20 to 26.2 to the 26.3 format in place.
pub fn upgrade_world(base: &Path) -> io::Result<i32> {
let version = fix_world_files(base)?;
+4 -1
View File
@@ -659,7 +659,10 @@ fn block_pos_format(cx: &mut Cx) {
// ------------------------------------------------------------------ 3814
fn attributes_rename_legacy(cx: &mut Cx, rename_fn: &dyn Fn(&str) -> Option<&'static str>) {
pub(super) fn attributes_rename_legacy(
cx: &mut Cx,
rename_fn: &dyn Fn(&str) -> Option<&'static str>,
) {
let fix_name = |v: &mut Tag, field: &str| {
if let Some(name) = as_str(v.get(field))
&& let Some(new) = rename_fn(&name)
+7 -2
View File
@@ -1135,8 +1135,13 @@ pub(super) fn equipment_to_slots(e: &mut Tag) {
};
let body = remove(e, "body_armor_item");
let saddle = remove(e, "saddle");
// A stack without an id is a placeholder for an empty slot.
let pick = |list: &Vec<Tag>, i: usize| list.get(i).filter(|s| s.get("id").is_some()).cloned();
// A stack without an id (an id that does not read as an item name is none) is a
// placeholder for an empty slot.
let pick = |list: &Vec<Tag>, i: usize| {
list.get(i)
.filter(|s| matches!(s.get("id"), Some(Tag::String(_))))
.cloned()
};
let slots = [
("mainhand", pick(&hands, 0)),
("offhand", pick(&hands, 1)),
@@ -4,12 +4,69 @@ use super::dynamic::{
as_bool, as_byte_buffer, as_int, as_int_stream, as_long_stream, as_number, as_str, ceillog2,
empty_map, remove, rename, set, stream, string,
};
use super::fixes_a::block_rename;
use super::fixes_b::advancements_rename;
use super::schema::{Key, Ty, key};
use super::{Cx, FixFn, renamer};
use crate::nbt::{Compound, JavaString, Tag};
pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(2679, 0), cauldron_rename));
out.push((key(2680, 0), |cx| {
let t = &[("minecraft:grass_path", "minecraft:dirt_path")];
cx.rename(Ty::ItemName, renamer(t));
}));
out.push((key(2680, 0), |cx| {
block_rename(cx, &[("minecraft:grass_path", "minecraft:dirt_path")])
}));
out.push((key(2690, 0), |cx| cx.rename(Ty::ItemName, renamer(COPPER))));
out.push((key(2690, 0), |cx| block_rename(cx, COPPER)));
out.push((key(2691, 0), |cx| {
cx.rename(Ty::ItemName, renamer(WAXED_COPPER))
}));
out.push((key(2691, 0), |cx| block_rename(cx, WAXED_COPPER)));
out.push((key(2693, 0), |cx| {
add_flag(cx, "has_increased_height_already", false)
}));
out.push((key(2696, 0), |cx| {
cx.rename(Ty::ItemName, renamer(GRIMSTONE))
}));
out.push((key(2696, 0), |cx| block_rename(cx, GRIMSTONE)));
out.push((key(2700, 0), |cx| {
block_rename(
cx,
&[
("minecraft:cave_vines_head", "minecraft:cave_vines"),
("minecraft:cave_vines_body", "minecraft:cave_vines_plant"),
],
)
}));
out.push((key(2701, 0), feature_pool_elements));
out.push((key(2702, 0), arrow_pickup));
out.push((key(2707, 0), |cx| {
add_flag(cx, "has_increased_height_already", true)
}));
out.push((key(2710, 0), |cx| {
stats_rename(cx, &[("minecraft:play_one_minute", "minecraft:play_time")])
}));
out.push((key(2717, 0), |cx| {
cx.rename(
Ty::ItemName,
renamer(&[(
"minecraft:azalea_leaves_flowers",
"minecraft:flowering_azalea_leaves",
)]),
)
}));
out.push((key(2717, 0), |cx| {
block_rename(
cx,
&[(
"minecraft:azalea_leaves_flowers",
"minecraft:flowering_azalea_leaves",
)],
)
}));
out.push((key(2825, 0), |cx| {
add_flag(cx, "has_increased_height_already", false)
}));
@@ -308,6 +365,362 @@ fn structures_become_configured(cx: &mut Cx) {
});
}
// ------------------------------------------------------------------ 2679 to 2717
/// `CauldronRenameFix`.
fn cauldron_rename(cx: &mut Cx) {
cx.each(Ty::BlockState, |v| {
if as_str(v.get("Name")).as_deref() != Some("minecraft:cauldron") {
return;
}
let level = v
.get("Properties")
.and_then(|p| as_str(p.get("level")))
.unwrap_or_else(|| "0".into());
if level == "0" {
remove(v, "Properties");
} else {
set(v, "Name", string("minecraft:water_cauldron"));
}
});
}
const COPPER: &[(&str, &str)] = &[
(
"minecraft:weathered_copper_block",
"minecraft:oxidized_copper_block",
),
(
"minecraft:semi_weathered_copper_block",
"minecraft:weathered_copper_block",
),
(
"minecraft:lightly_weathered_copper_block",
"minecraft:exposed_copper_block",
),
(
"minecraft:weathered_cut_copper",
"minecraft:oxidized_cut_copper",
),
(
"minecraft:semi_weathered_cut_copper",
"minecraft:weathered_cut_copper",
),
(
"minecraft:lightly_weathered_cut_copper",
"minecraft:exposed_cut_copper",
),
(
"minecraft:weathered_cut_copper_stairs",
"minecraft:oxidized_cut_copper_stairs",
),
(
"minecraft:semi_weathered_cut_copper_stairs",
"minecraft:weathered_cut_copper_stairs",
),
(
"minecraft:lightly_weathered_cut_copper_stairs",
"minecraft:exposed_cut_copper_stairs",
),
(
"minecraft:weathered_cut_copper_slab",
"minecraft:oxidized_cut_copper_slab",
),
(
"minecraft:semi_weathered_cut_copper_slab",
"minecraft:weathered_cut_copper_slab",
),
(
"minecraft:lightly_weathered_cut_copper_slab",
"minecraft:exposed_cut_copper_slab",
),
(
"minecraft:waxed_semi_weathered_copper",
"minecraft:waxed_weathered_copper",
),
(
"minecraft:waxed_lightly_weathered_copper",
"minecraft:waxed_exposed_copper",
),
(
"minecraft:waxed_semi_weathered_cut_copper",
"minecraft:waxed_weathered_cut_copper",
),
(
"minecraft:waxed_lightly_weathered_cut_copper",
"minecraft:waxed_exposed_cut_copper",
),
(
"minecraft:waxed_semi_weathered_cut_copper_stairs",
"minecraft:waxed_weathered_cut_copper_stairs",
),
(
"minecraft:waxed_lightly_weathered_cut_copper_stairs",
"minecraft:waxed_exposed_cut_copper_stairs",
),
(
"minecraft:waxed_semi_weathered_cut_copper_slab",
"minecraft:waxed_weathered_cut_copper_slab",
),
(
"minecraft:waxed_lightly_weathered_cut_copper_slab",
"minecraft:waxed_exposed_cut_copper_slab",
),
];
const WAXED_COPPER: &[(&str, &str)] = &[
("minecraft:waxed_copper", "minecraft:waxed_copper_block"),
(
"minecraft:oxidized_copper_block",
"minecraft:oxidized_copper",
),
(
"minecraft:weathered_copper_block",
"minecraft:weathered_copper",
),
("minecraft:exposed_copper_block", "minecraft:exposed_copper"),
];
const GRIMSTONE: &[(&str, &str)] = &[
("minecraft:grimstone", "minecraft:deepslate"),
(
"minecraft:grimstone_slab",
"minecraft:cobbled_deepslate_slab",
),
(
"minecraft:grimstone_stairs",
"minecraft:cobbled_deepslate_stairs",
),
(
"minecraft:grimstone_wall",
"minecraft:cobbled_deepslate_wall",
),
(
"minecraft:polished_grimstone",
"minecraft:polished_deepslate",
),
(
"minecraft:polished_grimstone_slab",
"minecraft:polished_deepslate_slab",
),
(
"minecraft:polished_grimstone_stairs",
"minecraft:polished_deepslate_stairs",
),
(
"minecraft:polished_grimstone_wall",
"minecraft:polished_deepslate_wall",
),
("minecraft:grimstone_tiles", "minecraft:deepslate_tiles"),
(
"minecraft:grimstone_tile_slab",
"minecraft:deepslate_tile_slab",
),
(
"minecraft:grimstone_tile_stairs",
"minecraft:deepslate_tile_stairs",
),
(
"minecraft:grimstone_tile_wall",
"minecraft:deepslate_tile_wall",
),
("minecraft:grimstone_bricks", "minecraft:deepslate_bricks"),
(
"minecraft:grimstone_brick_slab",
"minecraft:deepslate_brick_slab",
),
(
"minecraft:grimstone_brick_stairs",
"minecraft:deepslate_brick_stairs",
),
(
"minecraft:grimstone_brick_wall",
"minecraft:deepslate_brick_wall",
),
(
"minecraft:chiseled_grimstone",
"minecraft:chiseled_deepslate",
),
];
/// `SavedDataFeaturePoolElementFix`: the feature of jigsaw pieces' feature pool
/// elements, from an inline configuration to a configured feature id.
fn feature_pool_elements(cx: &mut Cx) {
cx.each(Ty::StructureFeature, |v| {
let Some(children) = v.get("Children") else {
return;
};
if !super::dynamic::is_list(Some(children)) {
return;
}
let fixed = stream(Some(children))
.into_iter()
.map(|mut child| {
let id = as_str(child.get("id")).unwrap_or_default();
if !matches!(
id.as_str(),
"minecraft:jigsaw"
| "minecraft:nvi"
| "minecraft:pcp"
| "minecraft:bastionremnant"
| "minecraft:runtime"
) {
return child;
}
let element = child.get("pool_element");
let is_feature = element
.and_then(|e| as_str(e.get("element_type")))
.as_deref()
== Some("minecraft:feature_pool_element");
if is_feature
&& let Some(f) = child
.get_mut("pool_element")
.and_then(|p| p.get_mut("feature"))
&& let Some(new) = feature_replacement(f)
{
*f = string(new);
}
child
})
.collect();
set(v, "Children", Tag::List(fixed));
});
}
fn path_str(v: &Tag, path: &[&str]) -> String {
let mut cur = Some(v.clone());
for p in path {
cur = match (cur, p.strip_prefix('[').and_then(|s| s.strip_suffix(']'))) {
(Some(c), Some(index)) => {
let i: usize = index.parse().unwrap_or(usize::MAX);
stream(Some(&c)).into_iter().nth(i)
}
(Some(c), None) => c.get(p).cloned(),
(None, _) => None,
};
}
as_str(cur.as_ref()).unwrap_or_default()
}
/// `SavedDataFeaturePoolElementFix.getReplacement`.
fn feature_replacement(value: &Tag) -> Option<&'static str> {
let ty = path_str(value, &["type"]);
let name = path_str(value, &["name"]);
let provider = path_str(value, &["config", "state_provider", "type"]);
let state = path_str(value, &["config", "state_provider", "state", "Name"]);
let first = path_str(
value,
&["config", "state_provider", "entries", "[0]", "data", "Name"],
);
let foliage = path_str(value, &["config", "foliage_placer", "type"]);
let leaves = path_str(value, &["config", "leaves_provider", "state", "Name"]);
let feature = if !ty.is_empty() {
ty
} else if name.is_empty() {
return None;
} else if name == "minecraft:normal_tree" {
"minecraft:tree".to_owned()
} else {
name
};
match feature.as_str() {
"minecraft:random_patch" => {
if provider == "minecraft:simple_state_provider" {
match state.as_str() {
"minecraft:sweet_berry_bush" => return Some("minecraft:patch_berry_bush"),
"minecraft:cactus" => return Some("minecraft:patch_cactus"),
_ => {}
}
} else if provider == "minecraft:weighted_state_provider"
&& (first == "minecraft:grass" || first == "minecraft:fern")
{
return Some("minecraft:patch_taiga_grass");
}
}
"minecraft:block_pile" => {
if provider != "minecraft:simple_state_provider"
&& provider != "minecraft:rotated_block_provider"
{
if provider == "minecraft:weighted_state_provider" {
match first.as_str() {
"minecraft:packed_ice" | "minecraft:blue_ice" => {
return Some("minecraft:pile_ice");
}
"minecraft:jack_o_lantern" | "minecraft:pumpkin" => {
return Some("minecraft:pile_pumpkin");
}
_ => {}
}
}
} else {
match state.as_str() {
"minecraft:hay_block" => return Some("minecraft:pile_hay"),
"minecraft:melon" => return Some("minecraft:pile_melon"),
"minecraft:snow" => return Some("minecraft:pile_snow"),
_ => {}
}
}
}
"minecraft:flower" => return Some("minecraft:flower_plain"),
"minecraft:tree" => match foliage.as_str() {
"minecraft:acacia_foliage_placer" => return Some("minecraft:acacia"),
"minecraft:blob_foliage_placer" if leaves == "minecraft:oak_leaves" => {
return Some("minecraft:oak");
}
"minecraft:pine_foliage_placer" => return Some("minecraft:pine"),
"minecraft:spruce_foliage_placer" => return Some("minecraft:spruce"),
_ => {}
},
_ => {}
}
None
}
/// `AbstractArrowPickupFix`.
fn arrow_pickup(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
let id = as_str(e.get("id")).map(|s| super::dynamic::namespaced(&s));
if !matches!(
id.as_deref(),
Some("minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:trident")
) || e.get("pickup").is_some()
{
return;
}
let from_player = as_bool(e.get("player"), true);
set(e, "pickup", Tag::Byte(i8::from(from_player)));
remove(e, "player");
});
}
/// `StatsRenameFix`: custom statistics and the objectives that count them.
pub(super) fn stats_rename(cx: &mut Cx, table: &[(&str, &'static str)]) {
let r = renamer(table);
cx.each(Ty::Stats, |v| {
if let Some(Tag::Compound(custom)) = v
.get_mut("stats")
.and_then(|s| s.get_mut("minecraft:custom"))
{
let old = std::mem::take(custom);
for (k, value) in old {
let name = super::dynamic::namespaced(&k.to_string_lossy());
let name = r(&name).map_or(name, str::to_owned);
custom.insert(JavaString::from(name.as_str()), value);
}
}
});
cx.each(Ty::Objective, |v| {
if let Some(ct) = v.get_mut("CriteriaType")
&& as_str(ct.get("type")).as_deref() == Some("minecraft:custom")
&& let Some(id) = as_str(ct.get("id"))
{
let id = super::dynamic::namespaced(&id);
let new = r(&id).map_or(id, str::to_owned);
set(ct, "id", string(&new));
}
});
}
// ------------------------------------------------------------------ 2825 to 2843
/// `AddFlagIfNotPresentFix` over the world generation settings.
@@ -323,11 +736,20 @@ pub(super) fn add_flag(cx: &mut Cx, flag: &str, value: bool) {
/// `SpawnerDataFix`: spawn data and potentials wrapped as weighted entries.
fn spawner_data(cx: &mut Cx) {
use super::schema::flat::UNTYPED;
cx.each(Ty::UntaggedSpawner, |v| {
if let Some(data) = remove(v, "SpawnData") {
// Only what read as typed is wrapped.
if v.get("SpawnData").is_some_and(|d| d.get(UNTYPED).is_none())
&& let Some(data) = remove(v, "SpawnData")
{
set(v, "SpawnData", Tag::compound([("entity", data)]));
}
if let Some(potentials) = v.get("SpawnPotentials").cloned() {
let untyped = |entries: &Tag| {
stream(Some(entries))
.iter()
.any(|e| e.get("Entity").is_some_and(|t| t.get(UNTYPED).is_some()))
};
if let Some(potentials) = v.get("SpawnPotentials").filter(|p| !untyped(p)).cloned() {
let entries = stream(Some(&potentials))
.into_iter()
.map(|mut entry| {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,787 @@
//! Fixes of 1.8 to 1.12 (keys 100 to 1125, DataVersion up to 1343): what worlds
//! saved by those versions need before the flattening ([`super::fixes_flat`]).
//! The options fixes of this range (505, 816, 1344) are client settings.
use super::dynamic::{
as_bool, as_float, as_int, as_int_stream, as_number, as_str, boolean, empty_map, is_list,
namespaced, remove, set, stream, string,
};
use super::flat_tables as t;
use super::schema::flat::entity_tree_known;
use super::schema::{Key, Ty, block_entity_known, key};
use super::{Cx, FixFn, drop_typed, items, mark_read, reread, reread_as};
use crate::nbt::{JavaString, Tag};
pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(100, 0), equipment_to_armor_and_hands));
out.push((key(101, 0), |cx| {
cx.entity("Villager", |e| set(e, "CanPickUpLoot", boolean(true)))
}));
out.push((key(102, 0), item_ids));
out.push((key(102, 0), item_potions));
out.push((key(105, 0), spawn_egg_entities));
out.push((key(106, 0), spawner_entity_identifiers));
out.push((key(107, 0), minecart_identifiers));
out.push((key(108, 0), entity_string_uuid));
out.push((key(109, 0), entity_health));
out.push((key(110, 0), horse_saddle));
out.push((key(111, 0), painting_item_frame_direction));
out.push((key(113, 0), redundant_chance_tags));
out.push((key(135, 0), riding_to_passengers));
out.push((key(143, 0), |cx| {
cx.entity("TippedArrow", |e| set(e, "id", string("Arrow")))
}));
out.push((key(147, 0), armor_stand_silent));
out.push((key(165, 0), sign_text_strict_json));
out.push((key(165, 0), written_book_pages_strict_json));
out.push((key(502, 0), |cx| {
cx.rename(Ty::ItemName, |name| {
(namespaced(name) == "minecraft:cooked_fished").then_some("minecraft:cooked_fish")
})
}));
out.push((key(502, 0), zombie_villager_type));
out.push((key(700, 0), elder_guardian_split));
out.push((key(701, 0), skeleton_split));
out.push((key(702, 0), zombie_split));
out.push((key(703, 0), horse_split));
out.push((key(704, 0), block_entity_ids));
out.push((key(705, 0), entity_ids));
out.push((key(804, 0), item_banner_color));
out.push((key(806, 0), item_water_potion));
out.push((key(808, 1), shulker_color));
out.push((key(813, 0), item_shulker_box_color));
out.push((key(813, 0), |cx| {
cx.block_entity("minecraft:shulker_box", |be| {
remove(be, "Color");
})
}));
out.push((key(820, 0), |cx| {
cx.rename(Ty::ItemName, |name| {
(namespaced(name) == "minecraft:totem").then_some("minecraft:totem_of_undying")
})
}));
out.push((key(1022, 0), |cx| {
let k = cx.k;
cx.each(Ty::Player, |p| reread_as(Ty::Player, k, p))
}));
out.push((key(1125, 0), bed_block_entities));
out.push((key(1125, 0), |cx| {
cx.item(
|id| id == "minecraft:bed",
|s| {
if as_int(s.get("Damage"), 0) == 0 {
set(s, "Damage", Tag::Short(14));
}
},
)
}));
}
/// `Number.shortValue` of a numeric field, or the default (`Dynamic.asShort`).
fn as_short(tag: Option<&Tag>, default: i16) -> i16 {
tag.and_then(as_number)
.map_or(default, |n| n.int_value() as i16)
}
fn lookup_int(table: &'static [(i32, &'static str)], k: i32) -> Option<&'static str> {
table.iter().find(|(i, _)| *i == k).map(|(_, v)| *v)
}
fn lookup_str(table: &'static [(&'static str, &'static str)], k: &str) -> Option<&'static str> {
table.iter().find(|(i, _)| *i == k).map(|(_, v)| *v)
}
fn float_list(values: &[f32]) -> Tag {
Tag::List(values.iter().map(|v| Tag::Float(v.to_bits())).collect())
}
// ------------------------------------------------------------------ 100
/// `EntityEquipmentToArmorAndHandFix`: the `Equipment` list becomes hand and armor items.
fn equipment_to_armor_and_hands(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
// The drop chances come first.
let chances: Option<Vec<f32>> =
e.get("DropChances").filter(|c| is_list(Some(c))).map(|c| {
stream(Some(c))
.iter()
.map(|v| as_float(Some(v), 0.0))
.collect()
});
remove(e, "DropChances");
if let Some(mut chances) = chances {
chances.extend([0.0; 5]);
if e.get("HandDropChances").is_none() {
set(e, "HandDropChances", float_list(&[chances[0], 0.0]));
}
if e.get("ArmorDropChances").is_none() {
set(e, "ArmorDropChances", float_list(&chances[1..5]));
}
}
// The equipment list reads only if every element is a compound.
let items: Vec<Tag> = match e.get("Equipment") {
Some(Tag::List(items)) if items.iter().all(|i| matches!(i, Tag::Compound(_))) => {
items.clone()
}
_ => Vec::new(),
};
if !items.is_empty() {
set(
e,
"HandItems",
Tag::List(vec![items[0].clone(), empty_map()]),
);
}
if items.len() > 1 {
let mut armor = vec![empty_map(); 4];
let end = items.len().min(5);
armor[..end - 1].clone_from_slice(&items[1..end]);
set(e, "ArmorItems", Tag::List(armor));
}
// `Equipment` is no field of the new type: the map it was read from gives it back.
drop_typed(e, "Equipment");
});
}
// ------------------------------------------------------------------ 102
/// `ItemIdFix`: numeric item ids become names.
fn item_ids(cx: &mut Cx) {
cx.each(Ty::ItemStack, |s| {
let new = match s.get("id") {
Some(Tag::String(id)) => namespaced(&id.to_string_lossy()),
Some(other) => match as_number(other) {
Some(n) => lookup_int(t::ITEM_IDS, n.int_value())
.unwrap_or("minecraft:air")
.to_owned(),
None => return,
},
None => return,
};
set(s, "id", string(&new));
});
}
/// `ItemPotionFix`: potion damage values become potion names.
fn item_potions(cx: &mut Cx) {
cx.item(
|id| id == "minecraft:potion",
|s| {
if !matches!(s.get("tag"), Some(Tag::Compound(_))) {
return;
}
let damage = i32::from(as_short(s.get("Damage"), 0));
if let Some(tag) = s.get_mut("tag")
&& !matches!(tag.get("Potion"), Some(Tag::String(_)))
{
let potion = lookup_int(t::ITEM_POTIONS, damage & 127).unwrap_or("minecraft:water");
set(tag, "Potion", string(potion));
if damage & 16384 == 16384 {
set(s, "id", string("minecraft:splash_potion"));
}
}
if damage != 0 {
set(s, "Damage", Tag::Short(0));
}
},
);
}
// ------------------------------------------------------------------ 105
/// `ItemSpawnEggFix`: the damage of a spawn egg becomes the entity it spawns.
fn spawn_egg_entities(cx: &mut Cx) {
let (k, input) = (cx.k, cx.k - 1);
cx.item(
|id| id == "minecraft:spawn_egg",
|s| {
let damage = i32::from(as_short(s.get("Damage"), 0));
if let Some(entity) = lookup_int(t::SPAWN_EGG_ENTITIES, damage & 0xFF) {
// The entity tree is typed only if its id is one of the schema's.
let typed = s
.get("tag")
.and_then(|tag| tag.get("EntityTag"))
.filter(|e| entity_tree_known(e, input))
.cloned();
let old_id = typed.as_ref().and_then(|e| as_str(e.get("id")));
if old_id.as_deref() != Some(entity) {
if !matches!(s.get("tag"), Some(Tag::Compound(_))) {
set(s, "tag", empty_map());
}
let mut entity_tag = typed.unwrap_or_else(empty_map);
set(&mut entity_tag, "id", string(entity));
reread_as(Ty::EntityTree, k, &mut entity_tag);
if let Some(tag) = s.get_mut("tag") {
set(tag, "EntityTag", entity_tag);
}
}
}
if damage != 0 {
set(s, "Damage", Tag::Short(0));
}
},
);
}
// ------------------------------------------------------------------ 106
/// `MobSpawnerEntityIdentifiersFix`: the spawned entity is a tree of its own.
fn spawner_entity_identifiers(cx: &mut Cx) {
let k = cx.k;
cx.each(Ty::UntaggedSpawner, |sp| {
if !matches!(sp, Tag::Compound(_)) {
return;
}
if let Some(Tag::String(entity)) = sp.get("EntityId") {
let id = if entity.0.is_empty() {
string("Pig")
} else {
Tag::String(entity.clone())
};
let mut data = sp.get("SpawnData").cloned().unwrap_or_else(empty_map);
if matches!(data, Tag::Compound(_)) {
set(&mut data, "id", id);
}
set(sp, "SpawnData", data);
remove(sp, "EntityId");
}
if let Some(Tag::List(potentials)) = sp.get_mut("SpawnPotentials") {
for potential in potentials {
if let Some(Tag::String(entity)) = potential.get("Type") {
let entity = entity.clone();
let mut data = potential
.get("Properties")
.cloned()
.unwrap_or_else(empty_map);
if matches!(data, Tag::Compound(_)) {
set(&mut data, "id", Tag::String(entity));
}
set(potential, "Entity", data);
remove(potential, "Type");
remove(potential, "Properties");
}
}
}
reread_as(Ty::UntaggedSpawner, k, sp);
});
}
// ------------------------------------------------------------------ 107
/// `EntityMinecartIdentifiersFix`: a minecart's type becomes its entity id.
fn minecart_identifiers(cx: &mut Cx) {
let k = cx.k;
cx.entity("Minecart", |e| {
let name = match as_int(e.get("Type"), 0) {
1 => "MinecartChest",
2 => "MinecartFurnace",
_ => "MinecartRideable",
};
set(e, "id", string(name));
remove(e, "Type");
reread(k, e);
});
}
// ------------------------------------------------------------------ 108
/// `UUID.fromString`.
fn parse_uuid(s: &str) -> Option<(i64, i64)> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 5 {
return None;
}
let part = |i: usize| i64::from_str_radix(parts[i], 16).ok();
let mut most = part(0)? & 0xFFFF_FFFF;
most = (most << 16) | (part(1)? & 0xFFFF);
most = (most << 16) | (part(2)? & 0xFFFF);
let mut least = part(3)? & 0xFFFF;
least = (least << 48) | (part(4)? & 0xFFFF_FFFF_FFFF);
Some((most, least))
}
/// `EntityStringUuidFix`: the string UUID becomes a most/least pair.
fn entity_string_uuid(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
if let Some(uuid) = as_str(e.get("UUID"))
&& let Some((most, least)) = parse_uuid(&uuid)
{
remove(e, "UUID");
set(e, "UUIDMost", Tag::Long(most));
set(e, "UUIDLeast", Tag::Long(least));
}
});
}
// ------------------------------------------------------------------ 109
/// `EntityHealthFix`: the health is a float.
fn entity_health(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
let heal_f = e.get("HealF").and_then(as_number);
let health = e.get("Health").and_then(as_number);
let value = if let Some(n) = heal_f {
remove(e, "HealF");
n.float_value()
} else if let Some(n) = health {
n.float_value()
} else {
return;
};
set(e, "Health", Tag::Float(value.to_bits()));
});
}
// ------------------------------------------------------------------ 110
/// `EntityHorseSaddleFix`: a saddled horse has a saddle item.
fn horse_saddle(cx: &mut Cx) {
cx.entity("EntityHorse", |e| {
if !matches!(e.get("SaddleItem"), Some(Tag::Compound(_))) && as_bool(e.get("Saddle"), false)
{
// `Saddle` stays: `Dynamic.remove` was not kept by the fix.
set(
e,
"SaddleItem",
Tag::compound([
("id", string("minecraft:saddle")),
("Count", Tag::Byte(1)),
("Damage", Tag::Short(0)),
]),
);
}
});
}
// ------------------------------------------------------------------ 111
/// `EntityPaintingItemFrameDirectionFix`.
fn painting_item_frame_direction(cx: &mut Cx) {
const DIRECTIONS: [[i32; 3]; 4] = [[0, 0, 1], [-1, 0, 0], [0, 0, -1], [1, 0, 0]];
for (id, item_frame) in [("Painting", false), ("ItemFrame", true)] {
cx.entity(id, |e| {
if e.get("Facing").and_then(as_number).is_some() {
return;
}
let byte = |tag: Option<&Tag>| tag.and_then(as_number).map_or(0, |n| n.byte_value());
let direction;
if e.get("Direction").and_then(as_number).is_some() {
direction = i32::from(byte(e.get("Direction"))) % 4;
let Some(steps) = usize::try_from(direction).ok().map(|d| DIRECTIONS[d]) else {
return;
};
for (field, step) in ["TileX", "TileY", "TileZ"].into_iter().zip(steps) {
let value = as_int(e.get(field), 0).wrapping_add(step);
set(e, field, Tag::Int(value));
}
remove(e, "Direction");
if item_frame && e.get("ItemRotation").and_then(as_number).is_some() {
let rotation = i32::from(byte(e.get("ItemRotation"))) * 2;
set(e, "ItemRotation", Tag::Byte(rotation as i8));
}
} else {
direction = i32::from(byte(e.get("Dir"))) % 4;
remove(e, "Dir");
}
set(e, "Facing", Tag::Byte(direction as i8));
});
}
}
// ------------------------------------------------------------------ 113
/// `EntityRedundantChanceTagsFix`: drop chances that are all zero are not saved.
fn redundant_chance_tags(cx: &mut Cx) {
let is_zero_list = |tag: Option<&Tag>, size: usize| {
let Some(tag) = tag.filter(|t| is_list(Some(t))) else {
return false;
};
let values = stream(Some(tag));
values.len() == size
&& values
.iter()
.all(|v| as_number(v).is_some_and(|n| n.float_value() == 0.0))
};
cx.each(Ty::Entity, |e| {
if is_zero_list(e.get("HandDropChances"), 2) {
remove(e, "HandDropChances");
}
if is_zero_list(e.get("ArmorDropChances"), 4) {
remove(e, "ArmorDropChances");
}
});
}
// ------------------------------------------------------------------ 135
/// `EntityRidingToPassengersFix`: the vehicle is the root and carries its riders.
fn riding_to_passengers(cx: &mut Cx) {
let (k, input) = (cx.k, cx.k - 1);
cx.each(Ty::EntityTree, |tree| {
if !entity_tree_known(tree, input) {
return;
}
// The vehicle was fixed first: it has its passengers already.
let Some(vehicle) = tree.get("Riding").filter(|v| entity_tree_known(v, input)) else {
return;
};
let vehicle = vehicle.clone();
let mut rider = tree.clone();
remove(&mut rider, "Riding");
// `Riding` is no field of the new type: the map the rider was read from gives it back.
drop_typed(&mut rider, "Riding");
*tree = add_passenger_to_top(vehicle, rider);
});
cx.each(Ty::Player, |p| reread_as(Ty::Player, k, p));
}
/// `EntityRidingToPassengersFix.addPassengerToTop`: the rider goes to the end of the chain.
fn add_passenger_to_top(mut root: Tag, passenger: Tag) -> Tag {
let first = match root.get("Passengers") {
Some(Tag::List(passengers)) => passengers.first().cloned(),
_ => None,
};
let passenger = match first {
Some(first) => add_passenger_to_top(first, passenger),
None => passenger,
};
set(&mut root, "Passengers", Tag::List(vec![passenger]));
root
}
// ------------------------------------------------------------------ 147
/// `EntityArmorStandSilentFix`.
fn armor_stand_silent(cx: &mut Cx) {
cx.entity("ArmorStand", |e| {
if as_bool(e.get("Silent"), false) && !as_bool(e.get("Marker"), false) {
remove(e, "Silent");
}
});
}
// ------------------------------------------------------------------ 165
/// `LegacyComponentDataFixUtils.rewriteFromLenient`.
fn rewrite_from_lenient(text: &[u16]) -> Vec<u16> {
use super::json::{self, Json};
let empty = || json::text_component_json(&[]);
if text.is_empty() || text == "null".encode_utf16().collect::<Vec<_>>().as_slice() {
return empty();
}
let (first, last) = (text[0], text[text.len() - 1]);
let (quote, open_brace, close_brace, open_bracket, close_bracket) = (
u16::from(b'"'),
u16::from(b'{'),
u16::from(b'}'),
u16::from(b'['),
u16::from(b']'),
);
let wrapped = (first == quote && last == quote)
|| (first == open_brace && last == close_brace)
|| (first == open_bracket && last == close_bracket);
if wrapped && let Some(parsed) = json::parse_lenient(text) {
return match parsed {
Json::Str(s) => json::text_component_json(&s),
Json::Num(n) => json::text_component_json(&n.encode_utf16().collect::<Vec<_>>()),
Json::Bool(b) => json::text_component_json(
&(if b { "true" } else { "false" })
.encode_utf16()
.collect::<Vec<_>>(),
),
other => json::to_stable_string(&other),
};
}
json::text_component_json(text)
}
/// `SignTextStrictJsonFix`: the lines of a sign are strict JSON.
fn sign_text_strict_json(cx: &mut Cx) {
cx.block_entity("Sign", |be| {
for line in ["Text1", "Text2", "Text3", "Text4"] {
if let Some(Tag::String(text)) = be.get(line) {
let fixed = rewrite_from_lenient(&text.0);
set(be, line, Tag::String(JavaString(fixed)));
}
}
});
}
/// `WrittenBookPagesStrictJsonFix`: the pages of a written book are strict JSON.
fn written_book_pages_strict_json(cx: &mut Cx) {
cx.item(
|id| id == "minecraft:written_book",
|s| {
let Some(Tag::List(pages)) = s.get_mut("tag").and_then(|t| t.get_mut("pages")) else {
return;
};
if pages.iter().all(|p| matches!(p, Tag::String(_))) {
for page in pages {
if let Tag::String(text) = page {
*text = JavaString(rewrite_from_lenient(&text.0));
}
}
}
},
);
}
// ------------------------------------------------------------------ 502
/// `EntityZombieVillagerTypeFix`: `IsVillager` becomes a zombie type.
fn zombie_villager_type(cx: &mut Cx) {
cx.entity("Zombie", |e| {
if !as_bool(e.get("IsVillager"), false) {
return;
}
if e.get("ZombieType").is_none() {
let profession = as_int(e.get("VillagerProfession"), -1);
// Vanilla picks a random profession for an invalid one: nothing to match there.
let profession = if (0..6).contains(&profession) {
profession
} else {
0
};
set(e, "ZombieType", Tag::Int(profession));
}
remove(e, "IsVillager");
});
}
// ------------------------------------------------------------------ 700 to 703
/// `EntityElderGuardianSplitFix`.
fn elder_guardian_split(cx: &mut Cx) {
cx.entity("Guardian", |e| {
if as_bool(e.get("Elder"), false) {
set(e, "id", string("ElderGuardian"));
}
});
}
/// `EntitySkeletonSplitFix`.
fn skeleton_split(cx: &mut Cx) {
cx.entity("Skeleton", |e| match as_int(e.get("SkeletonType"), 0) {
1 => set(e, "id", string("WitherSkeleton")),
2 => set(e, "id", string("Stray")),
_ => {}
});
}
/// `EntityZombieSplitFix`.
fn zombie_split(cx: &mut Cx) {
let k = cx.k;
cx.entity("Zombie", |e| {
let zombie_type = as_int(e.get("ZombieType"), 0);
match zombie_type {
1..=5 => {
set(e, "id", string("ZombieVillager"));
set(e, "Profession", Tag::Int(zombie_type - 1));
reread(k, e);
}
6 => set(e, "id", string("Husk")),
_ => {}
}
remove(e, "ZombieType");
});
}
/// `EntityHorseSplitFix`.
fn horse_split(cx: &mut Cx) {
let k = cx.k;
cx.entity("EntityHorse", |e| {
let name = match as_int(e.get("Type"), 0) {
1 => "Donkey",
2 => "Mule",
3 => "ZombieHorse",
4 => "SkeletonHorse",
_ => "Horse",
};
set(e, "id", string(name));
remove(e, "Type");
reread(k, e);
});
}
// ------------------------------------------------------------------ 704, 705
/// `BlockEntityIdFix`: block entity ids are namespaced. The item stacks are read
/// again first, with the hook of the new schema.
fn block_entity_ids(cx: &mut Cx) {
let k = cx.k;
cx.each(Ty::ItemStack, |s| items::add_names_at(s, k));
cx.each(Ty::BlockEntity, |be| {
if let Some(id) = as_str(be.get("id"))
&& let Some(new) = lookup_str(t::BLOCK_ENTITY_IDS, &id)
{
set(be, "id", string(new));
}
});
}
/// `EntityIdFix`: entity ids are namespaced (the item stacks are read again first).
fn entity_ids(cx: &mut Cx) {
let k = cx.k;
cx.each(Ty::ItemStack, |s| items::add_names_at(s, k));
cx.each(Ty::Entity, |e| {
if let Some(id) = as_str(e.get("id"))
&& let Some(new) = lookup_str(t::ENTITY_IDS, &id)
{
set(e, "id", string(new));
}
});
}
// ------------------------------------------------------------------ 804 to 813
/// `ItemBannerColorFix`: a banner item's damage is its base colour.
fn item_banner_color(cx: &mut Cx) {
let input = cx.k - 1;
cx.item(
|id| id == "minecraft:banner",
|s| {
let Some(base) = s
.get("tag")
.and_then(|tag| tag.get("BlockEntityTag"))
.filter(|be| block_entity_known(be, input))
.and_then(|be| be.get("Base"))
.and_then(as_number)
else {
return;
};
set(s, "Damage", Tag::Short((base.int_value() & 15) as i16));
let pick_marker = Tag::compound([("Lore", Tag::List(vec![string("(+NBT")]))]);
if s.get("tag")
.and_then(|tag| tag.get("display"))
.is_some_and(|display| *display == pick_marker)
{
return;
}
if let Some(be) = s
.get_mut("tag")
.and_then(|tag| tag.get_mut("BlockEntityTag"))
{
remove(be, "Base");
}
},
);
}
/// `ItemWaterPotionFix`: potions without a type are water.
fn item_water_potion(cx: &mut Cx) {
cx.item(
|id| {
matches!(
id,
"minecraft:potion"
| "minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:tipped_arrow"
)
},
|s| {
if !matches!(s.get("tag"), Some(Tag::Compound(_))) {
set(s, "tag", empty_map());
}
if let Some(tag) = s.get_mut("tag")
&& !matches!(tag.get("Potion"), Some(Tag::String(_)))
{
set(tag, "Potion", string("minecraft:water"));
}
},
);
}
/// `EntityShulkerColorFix`: shulkers of before 1.11 are purple.
fn shulker_color(cx: &mut Cx) {
cx.entity("minecraft:shulker", |e| {
if e.get("Color").is_none() {
set(e, "Color", Tag::Byte(10));
}
});
}
const SHULKER_BOX_COLORS: [&str; 16] = [
"minecraft:white_shulker_box",
"minecraft:orange_shulker_box",
"minecraft:magenta_shulker_box",
"minecraft:light_blue_shulker_box",
"minecraft:yellow_shulker_box",
"minecraft:lime_shulker_box",
"minecraft:pink_shulker_box",
"minecraft:gray_shulker_box",
"minecraft:silver_shulker_box",
"minecraft:cyan_shulker_box",
"minecraft:purple_shulker_box",
"minecraft:blue_shulker_box",
"minecraft:brown_shulker_box",
"minecraft:green_shulker_box",
"minecraft:red_shulker_box",
"minecraft:black_shulker_box",
];
/// `ItemShulkerBoxColorFix`: the colour of a shulker box item is in its name.
fn item_shulker_box_color(cx: &mut Cx) {
let input = cx.k - 1;
cx.item(
|id| id == "minecraft:shulker_box",
|s| {
let Some(be) = s
.get("tag")
.and_then(|tag| tag.get("BlockEntityTag"))
.filter(|be| block_entity_known(be, input))
else {
return;
};
// `Color` stays in the block entity: the fix does not keep `Dynamic.remove`.
let color = as_int(be.get("Color"), 0);
let name = SHULKER_BOX_COLORS[color.rem_euclid(16) as usize];
set(s, "id", string(name));
},
);
}
// ------------------------------------------------------------------ 1125
/// `ChunkBedBlockEntityInjecterFix`: a bed block gets the block entity 1.12 gave it.
fn bed_block_entities(cx: &mut Cx) {
cx.each(Ty::Chunk, |chunk| {
let Some(level) = chunk.get_mut("Level") else {
return;
};
let chunk_x = as_int(level.get("xPos"), 0);
let chunk_z = as_int(level.get("zPos"), 0);
let mut beds = Vec::new();
if let Some(Tag::List(sections)) = level.get("Sections") {
for section in sections {
let y = as_int(section.get("Y"), 0);
for (p, block) in as_int_stream(section.get("Blocks"))
.unwrap_or_default()
.into_iter()
.enumerate()
{
if (block & 0xFF) << 4 == 416 {
let (x, yy, z) = (p as i32 & 15, p as i32 >> 8 & 15, p as i32 >> 4 & 15);
let mut bed = Tag::compound([
("id", string("minecraft:bed")),
("x", Tag::Int(x + (chunk_x << 4))),
("y", Tag::Int(yy + (y << 4))),
("z", Tag::Int(z + (chunk_z << 4))),
("color", Tag::Short(14)),
]);
mark_read(&mut bed);
beds.push(bed);
}
}
}
}
if beds.is_empty() {
return;
}
if !matches!(level.get("TileEntities"), Some(Tag::List(_))) {
set(level, "TileEntities", Tag::List(Vec::new()));
}
if let Some(Tag::List(entities)) = level.get_mut("TileEntities") {
entities.extend(beds);
}
});
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+39
View File
@@ -248,6 +248,45 @@ const SPAWN_EGG_MOBS: &[&str] = &[
"zombified_piglin",
];
/// The read hook of item stacks in the schema at `k` (before 1.20.5): V99's tables below V704,
/// V704's block entities with V99's entities up to V705, V705's from then on.
pub(super) fn add_names_at(stack: &mut Tag, k: super::schema::Key) {
use super::schema::key;
if k >= key(705, 0) {
return add_names(stack);
}
let item = namespaced(&as_str(stack.get("id")).unwrap_or_else(|| "minecraft:air".into()));
let Some(tag) = stack.get_mut("tag") else {
return;
};
if let Some(be) = tag.get_mut("BlockEntityTag")
&& item != "minecraft:air"
{
let found = if k >= key(704, 0) {
ITEM_TO_BLOCK_ENTITY.iter().find(|(i, _)| *i == item)
} else {
super::flat_tables::ITEM_TO_BLOCK_ENTITY_V99
.iter()
.find(|(i, _)| *i == item)
};
if let Some((_, id)) = found {
set(be, "id", string(id));
}
}
if let Some(e) = tag.get_mut("EntityTag")
&& e.get("id").is_none()
{
let id = match item.as_str() {
"minecraft:armor_stand" => Some("ArmorStand"),
"minecraft:painting" => Some("Painting"),
_ => None,
};
if let Some(id) = id {
set(e, "id", string(id));
}
}
}
/// `V99.addNames` with V704/V705's tables: the read hook of item stacks before 1.20.5.
pub(super) fn add_names(stack: &mut Tag) {
let item = namespaced(&as_str(stack.get("id")).unwrap_or_else(|| "minecraft:air".into()));
+90 -15
View File
@@ -1,21 +1,28 @@
//! Vanilla's DataFixers from the 1.19 schemas on (`net.minecraft.util.datafix`):
//! the data of worlds saved by 1.18.2 to 26.2 brought to the 26.3 format exactly
//! Vanilla's DataFixers (`net.minecraft.util.datafix`, DataVersion 99 on):
//! the data of worlds saved by 1.8 to 26.2 brought to the 26.3 format exactly
//! as 26.3 does when it reads them, and the file fixes it runs when it opens
//! such a world (`net.minecraft.util.filefix`).
//!
//! DataFixerUpper reads the data once with the schema of its version (running
//! the schema's read hooks), applies every fix with a key above that version
//! in order, and writes it with the current schema. Each fix finds its values
//! with the schema just below its own key ([`schema`]). Data older than
//! [`OLDEST_SUPPORTED`] needs fixes that are not ported. The fixes of client
//! with the schema just below its own key ([`schema`]). Every
//! fix of the server data is ported ([`OLDEST_SUPPORTED`]). The fixes of client
//! files (options, hotbars, debug profiles) are not ported either.
mod block_state_data;
mod chunk_flatten;
mod chunk_leaves;
pub mod dynamic;
pub mod files;
mod fixes_a;
mod fixes_b;
mod fixes_c;
mod fixes_cliffs;
mod fixes_flat;
mod fixes_legacy;
mod fixes_mid;
mod fixes_old;
mod flat_tables;
mod items;
pub mod json;
pub mod schema;
@@ -27,9 +34,9 @@ use schema::{Key, Ty, key, walk};
/// The DataVersion of the game.
pub const CURRENT: i32 = crate::DATA_VERSION;
/// Data saved before this DataVersion (1.17 is 2724) needs fixes that are not
/// ported (2717 and everything before).
pub const OLDEST_SUPPORTED: i32 = 2724;
/// Data saved before this DataVersion needs fixes that are not ported. Every
/// server fix is, down to the saves of 1.8, which have no DataVersion (read as -1).
pub const OLDEST_SUPPORTED: i32 = -1;
/// `Identifier.tryParse` validity, as `NamespacedSchema.ensureNamespaced` uses it.
pub fn identifier(id: &str) -> Option<(String, String)> {
@@ -126,6 +133,9 @@ pub fn reread(k: Key, e: &mut Tag) {
/// [`reread`] for a value of another type (a block entity).
pub fn reread_as(ty: Ty, k: Key, v: &mut Tag) {
// What was untyped is read again with the new schema.
schema::flat::strip_untyped(v);
schema::flat::mark_untyped(ty, v, k);
walk(ty, v, k, Ty::BlockEntity, &mut mark_read);
walk(ty, v, k, Ty::Entity, &mut mark_read);
}
@@ -145,6 +155,7 @@ fn strip_last_read(v: &mut Tag) {
match v {
Tag::Compound(c) => {
c.remove(&dynamic::key(LAST_READ));
c.remove(&dynamic::key(schema::flat::UNTYPED));
for value in c.values_mut() {
strip_last_read(value);
}
@@ -177,11 +188,16 @@ type FixFn = fn(&mut Cx);
/// Every ported fix (from the 1.19 schemas on), in DataFixers order.
fn fixes() -> Vec<(Key, FixFn)> {
let mut out = Vec::new();
fixes_legacy::register(&mut out);
fixes_flat::register(&mut out);
fixes_mid::register(&mut out);
fixes_cliffs::register(&mut out);
fixes_old::register(&mut out);
fixes_a::register(&mut out);
fixes_b::register(&mut out);
fixes_c::register(&mut out);
// DataFixerBuilder sorts the fixes of equal keys by registration, the rest by key.
out.sort_by_key(|(k, _)| *k);
out
}
@@ -195,10 +211,30 @@ pub fn update(root: Ty, data: &mut Tag, from: i32, to: i32) {
// The data is read once with the schema of its version (its read hooks)...
walk(root, data, from_key, Ty::BlockEntity, &mut mark_read);
walk(root, data, from_key, Ty::Entity, &mut mark_read);
schema::flat::mark_untyped(root, data, from_key);
read_hooks(root, data, from_key);
// ...then every fix above that key, up to the target version...
let mut refreshed = from_key >= schema::flat::END;
for (k, fix) in fixes() {
if k > from_key && k / 10 <= to_version {
if !refreshed && k >= schema::flat::END {
// The data of before 1.14 is read again once its own fixes are done.
refreshed = true;
walk(
root,
data,
schema::flat::END - 1,
Ty::BlockEntity,
&mut mark_read,
);
walk(
root,
data,
schema::flat::END - 1,
Ty::Entity,
&mut mark_read,
);
}
fix(&mut Cx { root, data, k });
}
}
@@ -211,13 +247,34 @@ pub fn update(root: Ty, data: &mut Tag, from: i32, to: i32) {
fn read_hooks(root: Ty, data: &mut Tag, k: Key) {
walk(root, data, k, Ty::ItemStack, &mut |stack| {
if k < key(3818, 5) {
items::add_names(stack);
items::add_names_at(stack, k);
} else if let Tag::String(_) = stack {
// V3818_5 UNPACK_PLAIN_ID: a bare item id is a stack of one.
*stack = Tag::compound([("id", stack.clone()), ("count", Tag::Int(1))]);
}
});
walk(root, data, k, Ty::Objective, &mut fixes_a::unpack_objective);
if k >= key(1451, 6) {
walk(root, data, k, Ty::Objective, &mut fixes_a::unpack_objective);
}
// Block names are numbers or namespaced strings until V1451_4: a number is read as an
// int and written as one.
walk(root, data, k, Ty::BlockName, &mut |name| {
if let Some(n) = as_str(Some(name)) {
*name = string(&dynamic::namespaced(&n));
} else if k < key(1451, 4)
&& let Some(n) = dynamic::as_number(name)
{
*name = Tag::Int(n.int_value());
}
});
// Namespaced name types read their strings with `ensureNamespaced`.
for ty in [Ty::Biome, Ty::EntityName, Ty::ItemName] {
walk(root, data, k, ty, &mut |name| {
if let Some(n) = as_str(Some(name)) {
*name = string(&dynamic::namespaced(&n));
}
});
}
}
fn write_hooks(root: Ty, data: &mut Tag, k: Key) {
@@ -227,8 +284,14 @@ fn write_hooks(root: Ty, data: &mut Tag, k: Key) {
/// `SimpleRegionStorage.upgradeChunkTag` for a region chunk (`ChunkMap`):
/// the dimension and generator are passed to the fixes as `__context`.
pub fn update_chunk(tag: &mut Tag, dimension: &str, generator: Option<&str>) {
update_chunk_to(tag, dimension, generator, CURRENT);
}
/// [`update_chunk`] up to an older DataVersion than the current one (the
/// harness checks the fixes of a range of versions on their own).
pub fn update_chunk_to(tag: &mut Tag, dimension: &str, generator: Option<&str>, to: i32) {
let version = dynamic::as_int(tag.get("DataVersion"), -1);
if version >= CURRENT {
if version >= to {
return;
}
let mut context = Tag::compound([("dimension", string(dimension))]);
@@ -236,21 +299,26 @@ pub fn update_chunk(tag: &mut Tag, dimension: &str, generator: Option<&str>) {
dynamic::set(&mut context, "generator", string(g));
}
dynamic::set(tag, "__context", context);
update(Ty::Chunk, tag, version, CURRENT);
update(Ty::Chunk, tag, version, to);
dynamic::remove(tag, "__context");
dynamic::set(tag, "DataVersion", Tag::Int(CURRENT));
dynamic::set(tag, "DataVersion", Tag::Int(to));
}
/// `SimpleRegionStorage.upgradeChunkTag` for entity chunks (default version -1)
/// and POI chunks (default 1945).
pub fn update_region_tag(root: Ty, tag: &mut Tag) {
update_region_tag_to(root, tag, CURRENT);
}
/// [`update_region_tag`] up to an older DataVersion.
pub fn update_region_tag_to(root: Ty, tag: &mut Tag, to: i32) {
let default = if root == Ty::PoiChunk { 1945 } else { -1 };
let version = dynamic::as_int(tag.get("DataVersion"), default);
if version >= CURRENT {
if version >= to {
return;
}
update(root, tag, version, CURRENT);
dynamic::set(tag, "DataVersion", Tag::Int(CURRENT));
update(root, tag, version, to);
dynamic::set(tag, "DataVersion", Tag::Int(to));
}
/// `PlayerDataStorage.load`: the DataVersion field stays as loaded.
@@ -259,6 +327,13 @@ pub fn update_player(tag: &mut Tag) {
update(Ty::Player, tag, version, CURRENT);
}
/// [`update_player`] up to an older DataVersion.
pub fn update_player_to(tag: &mut Tag, to: i32) {
let version = dynamic::as_int(tag.get("DataVersion"), -1);
update(Ty::Player, tag, version, to);
dynamic::set(tag, "DataVersion", Tag::Int(to));
}
/// The saved data type of a file below a `data` folder (`namespace/path.dat`).
pub fn saved_data_type(relative: &str) -> Option<Ty> {
let name = relative.strip_suffix(".dat").unwrap_or(relative);
+32 -1
View File
@@ -8,6 +8,9 @@
use super::dynamic::{as_str, namespaced};
use crate::nbt::Tag;
#[path = "schema_flat.rs"]
pub(super) mod flat;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Ty {
Level,
@@ -93,6 +96,21 @@ impl Walker<'_> {
}
}
fn list(&mut self, ty: Ty, v: &mut Tag, name: &str) {
// A list of block names reads the numbers of an array tag and writes them as a list.
if ty == Ty::BlockName
&& self.k < key(1451, 4)
&& let Some(array) = v.get_mut(name)
{
let numbers: Option<Vec<Tag>> = match array {
Tag::IntArray(a) => Some(a.iter().map(|x| Tag::Int(*x)).collect()),
Tag::ByteArray(a) => Some(a.iter().map(|x| Tag::Byte(*x as i8)).collect()),
Tag::LongArray(a) => Some(a.iter().map(|x| Tag::Long(*x)).collect()),
_ => None,
};
if let Some(numbers) = numbers {
*array = Tag::List(numbers);
}
}
if let Some(Tag::List(items)) = v.get_mut(name) {
for item in items {
self.walk(ty, item);
@@ -144,6 +162,9 @@ impl Walker<'_> {
fn children(&mut self, ty: Ty, v: &mut Tag) {
let k = self.k;
if k < flat::END && self.legacy_children(ty, v) {
return;
}
match ty {
Ty::Level => {
if k < key(4771, 0) {
@@ -203,6 +224,8 @@ impl Walker<'_> {
}
}
Ty::EntityChunk => self.list(Ty::EntityTree, v, "Entities"),
// What the schema it was read with did not know stays untyped (see `flat::UNTYPED`).
Ty::EntityTree if v.get(flat::UNTYPED).is_some() => {}
Ty::EntityTree => {
self.list(Ty::EntityTree, v, "Passengers");
self.walk(Ty::Entity, v);
@@ -420,7 +443,11 @@ impl Walker<'_> {
"minecraft:item" | "minecraft:item_frame" | "minecraft:glow_item_frame" => {
self.field(Ty::ItemStack, v, "Item");
}
"minecraft:potion" if k < key(4306, 0) => self.field(Ty::ItemStack, v, "Item"),
"minecraft:potion" if k < key(4306, 0) => {
// V2511_1 renamed the typed field.
let field = if k < key(2511, 1) { "Potion" } else { "Item" };
self.field(Ty::ItemStack, v, field);
}
"minecraft:splash_potion" | "minecraft:lingering_potion" if k >= key(4306, 0) => {
self.field(Ty::ItemStack, v, "Item");
}
@@ -542,6 +569,7 @@ impl Walker<'_> {
}
"minecraft:crafter" if k >= key(3682, 0) => named_inventory(self, v),
"minecraft:jukebox" => self.field(Ty::ItemStack, v, "RecordItem"),
"minecraft:flower_pot" if k < key(1451, 5) => self.field(Ty::ItemName, v, "Item"),
"minecraft:sign" | "minecraft:hanging_sign" => {
for side in ["front_text", "back_text"] {
if let Some(s) = v.get_mut(side) {
@@ -833,6 +861,9 @@ impl Walker<'_> {
/// Block entity ids the schema at `k` knows (others are read as remainder).
pub fn block_entity_known(be: &Tag, k: Key) -> bool {
let id = namespaced(&as_str(be.get("id")).unwrap_or_default());
if k < flat::END {
return flat::legacy_block_entity_known(&id, k);
}
let since = match id.as_str() {
"minecraft:sculk_catalyst" => key(3076, 0),
"minecraft:sculk_shrieker" => key(3078, 0),
@@ -0,0 +1,508 @@
//! The schemas of before 1.14 (keys below 1800): V99 to V1510 as far as the fixes
//! of those versions look. [`Walker::legacy_children`] answers for the types whose
//! shape differs from the general code of [`super`]; the other types fall through.
use super::{Key, Ty, Walker, as_str, key, namespaced};
use crate::nbt::Tag;
use std::cell::Cell;
use std::collections::HashSet;
use std::sync::OnceLock;
/// DataFixerUpper reads the data once, with the schema of its version: an entity tree
/// of an id that schema does not register stays untyped for good, even when a later
/// schema registers the id. Such a tree carries this key until the data is written.
pub(in crate::datafix) const UNTYPED: &str = "\u{0}untyped";
thread_local! {
/// Set while the data is read with its own schema: the walkers mark what is untyped.
static MARKING: Cell<bool> = const { Cell::new(false) };
}
/// Mark the untyped entity trees of data read with the schema at `k`.
pub(in crate::datafix) fn mark_untyped(root: Ty, data: &mut Tag, k: Key) {
if k >= END {
return;
}
MARKING.with(|m| m.set(true));
super::walk(root, data, k, Ty::BlockEntity, &mut |_| {});
MARKING.with(|m| m.set(false));
}
/// Remove the untyped marks of `v` (it is read again).
pub(in crate::datafix) fn strip_untyped(v: &mut Tag) {
match v {
Tag::Compound(c) => {
c.remove(&crate::datafix::dynamic::key(UNTYPED));
c.values_mut().for_each(strip_untyped);
}
Tag::List(items) => items.iter_mut().for_each(strip_untyped),
_ => {}
}
}
fn mark(tree: &mut Tag) {
if let Tag::Compound(_) = tree {
crate::datafix::dynamic::set(tree, UNTYPED, Tag::Byte(1));
}
}
/// Whether every tree of a list reads as typed (a list reads only if all its elements do);
/// while the data is read, the trees of a list that does not are marked.
pub(in crate::datafix) fn all_trees_typed(trees: &mut [Tag], k: Key) -> bool {
let ok = trees.iter().all(|t| entity_tree_known(t, k));
if !ok && MARKING.with(Cell::get) {
trees.iter_mut().for_each(mark);
}
ok
}
/// The schemas below this key are described here.
pub(in crate::datafix) const END: Key = key(1800, 0);
impl Walker<'_> {
/// `children` for a schema below [`END`]; false when the general code applies.
pub(super) fn legacy_children(&mut self, ty: Ty, v: &mut Tag) -> bool {
let k = self.k;
match ty {
Ty::Entity => {
if k < key(705, 0) {
self.legacy_entity_old(v);
} else {
self.legacy_entity(v);
}
true
}
// An entity of an unknown id does not read as a typed value: nothing in it is fixed.
Ty::EntityTree => {
if entity_tree_known(v, k) {
if k < key(135, 0) {
// The vehicle this entity rides is a tree of its own.
if let Some(vehicle) = v.get_mut("Riding") {
if entity_tree_known(vehicle, k) {
self.walk(Ty::EntityTree, vehicle);
} else if MARKING.with(Cell::get) {
mark(vehicle);
}
}
} else if let Some(Tag::List(trees)) = v.get_mut("Passengers")
&& all_trees_typed(trees, k)
{
for tree in trees {
self.walk(Ty::EntityTree, tree);
}
}
self.walk(Ty::Entity, v);
} else if MARKING.with(Cell::get) {
mark(v);
}
true
}
Ty::UntaggedSpawner if k >= key(106, 0) => {
self.legacy_untagged_spawner(v);
true
}
Ty::BlockEntity if k < key(704, 0) => {
self.legacy_block_entity_old(v);
true
}
Ty::Chunk => {
if let Some(level) = v.get_mut("Level") {
self.legacy_level_chunk(level);
}
true
}
// STATS is a plain map until V1451_6 turns it into typed counters.
Ty::Stats if k < key(1451, 6) => true,
Ty::Objective if k < key(1451, 6) => {
self.field(Ty::TextComponent, v, "DisplayName");
true
}
_ => false,
}
}
/// The `Level` of a chunk (V99 to V1510).
fn legacy_level_chunk(&mut self, v: &mut Tag) {
let k = self.k;
// A list of entity trees reads only if every entity of it is known.
if let Some(Tag::List(trees)) = v.get_mut("Entities")
&& all_trees_typed(trees, k)
{
for tree in trees {
self.walk(Ty::EntityTree, tree);
}
}
if let Some(Tag::List(items)) = v.get_mut("TileEntities") {
for be in items {
if super::block_entity_known(be, k) {
self.walk(Ty::BlockEntity, be);
}
}
}
self.list_of_field(Ty::BlockName, v, "TileTicks", "i");
if k >= key(1451, 1)
&& let Some(Tag::List(sections)) = v.get_mut("Sections")
{
for s in sections {
self.list(Ty::BlockState, s, "Palette");
}
}
if k >= key(1466, 0)
&& let Some(s) = v.get_mut("Structures")
{
self.values(Ty::StructureFeature, s, "Starts");
}
}
/// `UNTAGGED_SPAWNER` of V106 to V2830: the potential entities are a list that
/// reads only if all of them do.
fn legacy_untagged_spawner(&mut self, v: &mut Tag) {
let k = self.k;
if let Some(Tag::List(potentials)) = v.get_mut("SpawnPotentials") {
let mut trees: Vec<Option<&mut Tag>> =
potentials.iter_mut().map(|p| p.get_mut("Entity")).collect();
let ok = trees
.iter()
.all(|t| t.as_deref().is_some_and(|t| entity_tree_known(t, k)));
if ok {
for tree in trees.iter_mut().flatten() {
self.walk(Ty::EntityTree, tree);
}
} else if MARKING.with(Cell::get) {
trees.iter_mut().flatten().for_each(|t| mark(t));
}
}
self.field(Ty::EntityTree, v, "SpawnData");
}
/// `ENTITY` of the schemas V99 to V703 (CamelCase ids).
fn legacy_entity_old(&mut self, v: &mut Tag) {
let k = self.k;
if k < key(100, 0) {
self.list(Ty::ItemStack, v, "Equipment");
} else {
self.list(Ty::ItemStack, v, "ArmorItems");
self.list(Ty::ItemStack, v, "HandItems");
}
let id = as_str(v.get("id")).unwrap_or_default();
match id.as_str() {
"Item" | "ItemFrame" => self.field(Ty::ItemStack, v, "Item"),
"ThrownEgg" | "Snowball" | "Fireball" | "SmallFireball" | "ThrownEnderpearl"
| "ThrownExpBottle" | "WitherSkull" | "Arrow" | "TippedArrow" | "SpectralArrow" => {
self.field(Ty::BlockName, v, "inTile")
}
"ThrownPotion" => {
self.field(Ty::BlockName, v, "inTile");
self.field(Ty::ItemStack, v, "Potion");
}
"FallingSand" => {
self.field(Ty::BlockName, v, "Block");
self.field(Ty::BlockEntity, v, "TileEntityData");
}
"FireworksRocketEntity" => self.field(Ty::ItemStack, v, "FireworksItem"),
"Minecart" | "MinecartChest" | "MinecartHopper" => {
self.field(Ty::BlockName, v, "DisplayTile");
self.list(Ty::ItemStack, v, "Items");
}
"MinecartRideable" | "MinecartFurnace" | "MinecartTNT" => {
self.field(Ty::BlockName, v, "DisplayTile")
}
"MinecartSpawner" => {
self.field(Ty::BlockName, v, "DisplayTile");
self.spawner(v);
}
"MinecartCommandBlock" => {
self.field(Ty::BlockName, v, "DisplayTile");
self.field(Ty::TextComponent, v, "LastOutput");
}
"Enderman" => self.field(Ty::BlockName, v, "carried"),
"EntityHorse" => {
self.list(Ty::ItemStack, v, "Items");
self.field(Ty::ItemStack, v, "ArmorItem");
self.field(Ty::ItemStack, v, "SaddleItem");
}
"Horse" => {
self.field(Ty::ItemStack, v, "ArmorItem");
self.field(Ty::ItemStack, v, "SaddleItem");
}
"Donkey" | "Mule" => {
self.list(Ty::ItemStack, v, "Items");
self.field(Ty::ItemStack, v, "SaddleItem");
}
"ZombieHorse" | "SkeletonHorse" => self.field(Ty::ItemStack, v, "SaddleItem"),
"Villager" => {
self.list(Ty::ItemStack, v, "Inventory");
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
"ZombieVillager" => {
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
"AreaEffectCloud" => self.field(Ty::Particle, v, "Particle"),
_ => {}
}
}
/// `BLOCK_ENTITY` of the schemas V99 to V703 (CamelCase ids).
fn legacy_block_entity_old(&mut self, v: &mut Tag) {
let id = as_str(v.get("id")).unwrap_or_default();
match id.as_str() {
"Furnace" | "Chest" | "Trap" | "Dropper" | "Cauldron" | "Hopper" => {
self.list(Ty::ItemStack, v, "Items")
}
"RecordPlayer" => self.field(Ty::ItemStack, v, "RecordItem"),
"Sign" => {
for line in ["Text1", "Text2", "Text3", "Text4"] {
self.field(Ty::TextComponent, v, line);
}
}
"MobSpawner" => self.spawner(v),
"FlowerPot" => self.field(Ty::ItemName, v, "Item"),
"Control" => self.field(Ty::TextComponent, v, "LastOutput"),
"Banner" => self.field(Ty::TextComponent, v, "CustomName"),
_ => {}
}
}
/// `ENTITY` of the schemas V705 to V1510 (the ids are `minecraft:...` since V704).
fn legacy_entity(&mut self, v: &mut Tag) {
let k = self.k;
self.list(Ty::ItemStack, v, "ArmorItems");
self.list(Ty::ItemStack, v, "HandItems");
self.field(Ty::TextComponent, v, "CustomName");
let id = namespaced(&as_str(v.get("id")).unwrap_or_default());
// V1451_3 flattens the blocks of entities; V1510 renames some entities.
let blocks_as_names = k < key(1451, 3);
let renamed = k >= key(1510, 0);
let block = |w: &mut Self, v: &mut Tag, old: &str, new: &str| {
if blocks_as_names {
w.field(Ty::BlockName, v, old);
} else {
w.field(Ty::BlockState, v, new);
}
};
match id.as_str() {
"minecraft:area_effect_cloud" => self.field(Ty::Particle, v, "Particle"),
"minecraft:arrow" | "minecraft:spectral_arrow" => {
block(self, v, "inTile", "inBlockState")
}
"minecraft:egg"
| "minecraft:ender_pearl"
| "minecraft:fireball"
| "minecraft:small_fireball"
| "minecraft:snowball"
| "minecraft:wither_skull" => {
if blocks_as_names {
self.field(Ty::BlockName, v, "inTile");
}
}
"minecraft:xp_bottle" if !renamed => {
if blocks_as_names {
self.field(Ty::BlockName, v, "inTile");
}
}
"minecraft:potion" => {
self.field(Ty::ItemStack, v, "Potion");
if blocks_as_names {
self.field(Ty::BlockName, v, "inTile");
}
}
"minecraft:trident" => {
self.field(Ty::BlockState, v, "inBlockState");
self.field(Ty::ItemStack, v, "Trident");
}
"minecraft:chest_minecart" | "minecraft:hopper_minecart" => {
block(self, v, "DisplayTile", "DisplayState");
self.list(Ty::ItemStack, v, "Items");
}
"minecraft:minecart" | "minecraft:furnace_minecart" | "minecraft:tnt_minecart" => {
block(self, v, "DisplayTile", "DisplayState");
}
"minecraft:commandblock_minecart" if !renamed => {
block(self, v, "DisplayTile", "DisplayState");
self.field(Ty::TextComponent, v, "LastOutput");
}
"minecraft:command_block_minecart" if renamed => {
block(self, v, "DisplayTile", "DisplayState");
self.field(Ty::TextComponent, v, "LastOutput");
}
"minecraft:spawner_minecart" => {
block(self, v, "DisplayTile", "DisplayState");
self.spawner(v);
}
"minecraft:enderman" => block(self, v, "carried", "carriedBlockState"),
"minecraft:falling_block" => {
block(self, v, "Block", "BlockState");
self.field(Ty::BlockEntity, v, "TileEntityData");
}
"minecraft:fireworks_rocket" if !renamed => {
self.field(Ty::ItemStack, v, "FireworksItem")
}
"minecraft:firework_rocket" if renamed => self.field(Ty::ItemStack, v, "FireworksItem"),
"minecraft:item" | "minecraft:item_frame" => self.field(Ty::ItemStack, v, "Item"),
"minecraft:horse" => {
self.field(Ty::ItemStack, v, "ArmorItem");
self.field(Ty::ItemStack, v, "SaddleItem");
}
"minecraft:donkey" | "minecraft:mule" => {
self.list(Ty::ItemStack, v, "Items");
self.field(Ty::ItemStack, v, "SaddleItem");
}
"minecraft:llama" => {
self.list(Ty::ItemStack, v, "Items");
self.field(Ty::ItemStack, v, "SaddleItem");
self.field(Ty::ItemStack, v, "DecorItem");
}
"minecraft:skeleton_horse" | "minecraft:zombie_horse" => {
self.field(Ty::ItemStack, v, "SaddleItem");
}
"minecraft:villager" => {
self.list(Ty::ItemStack, v, "Inventory");
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
"minecraft:zombie_villager" => {
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
_ => {}
}
}
}
/// Whether the block entity id is registered in the schema at `k` (before 1.14).
pub(super) fn legacy_block_entity_known(id: &str, k: Key) -> bool {
if k < key(704, 0) {
return crate::datafix::flat_tables::BLOCK_ENTITIES_V99.contains(&id);
}
match id {
"minecraft:furnace"
| "minecraft:chest"
| "minecraft:ender_chest"
| "minecraft:jukebox"
| "minecraft:dispenser"
| "minecraft:dropper"
| "minecraft:sign"
| "minecraft:mob_spawner"
| "minecraft:piston"
| "minecraft:brewing_stand"
| "minecraft:enchanting_table"
| "minecraft:end_portal"
| "minecraft:beacon"
| "minecraft:skull"
| "minecraft:daylight_detector"
| "minecraft:hopper"
| "minecraft:comparator"
| "minecraft:banner"
| "minecraft:structure_block"
| "minecraft:end_gateway"
| "minecraft:command_block" => true,
// V808 adds the shulker box.
"minecraft:shulker_box" => k >= key(808, 0),
// Registered by V1125 and dropped by V1451_5.
"minecraft:bed" => k >= key(1125, 0),
"minecraft:noteblock" | "minecraft:flower_pot" => k < key(1451, 5),
"minecraft:trapped_chest" => k >= key(1451, 0),
"DUMMY" => k >= key(1466, 0),
"minecraft:conduit" => k >= key(1481, 0),
_ => false,
}
}
/// Whether `id` is an entity registered by the schema at `k` (V705 to V1510).
pub(in crate::datafix) fn legacy_entity_known(id: &str, k: Key) -> bool {
if k < key(705, 0) {
return old_entity_known(id, k);
}
static ERAS: OnceLock<[HashSet<String>; 5]> = OnceLock::new();
let eras = ERAS.get_or_init(|| {
let mut set: HashSet<String> = crate::datafix::flat_tables::ENTITIES_V1460
.iter()
.map(|s| (*s).to_owned())
.collect();
let rename = |set: &mut HashSet<String>, from: &str, to: &str| {
if set.remove(from) {
set.insert(to.to_owned());
}
};
let base = set.clone();
// V1470
for id in [
"turtle",
"cod_mob",
"tropical_fish",
"salmon_mob",
"puffer_fish",
"phantom",
"dolphin",
"drowned",
"trident",
] {
set.insert(format!("minecraft:{id}"));
}
let v1470 = set.clone();
rename(&mut set, "minecraft:puffer_fish", "minecraft:pufferfish");
let v1483 = set.clone();
rename(&mut set, "minecraft:cod_mob", "minecraft:cod");
rename(&mut set, "minecraft:salmon_mob", "minecraft:salmon");
let v1486 = set.clone();
for (from, to) in [
("commandblock_minecart", "command_block_minecart"),
("ender_crystal", "end_crystal"),
("snowman", "snow_golem"),
("evocation_illager", "evoker"),
("evocation_fangs", "evoker_fangs"),
("illusion_illager", "illusioner"),
("vindication_illager", "vindicator"),
("villager_golem", "iron_golem"),
("xp_orb", "experience_orb"),
("xp_bottle", "experience_bottle"),
("eye_of_ender_signal", "eye_of_ender"),
("fireworks_rocket", "firework_rocket"),
] {
rename(
&mut set,
&format!("minecraft:{from}"),
&format!("minecraft:{to}"),
);
}
[base, v1470, v1483, v1486, set]
});
let era = if k < key(1470, 0) {
0
} else if k < key(1483, 0) {
1
} else if k < key(1486, 0) {
2
} else if k < key(1510, 0) {
3
} else {
4
};
eras[era].contains(id)
}
/// Whether the entity tree's own entity reads as a typed value at `k`.
pub(in crate::datafix) fn entity_tree_known(tree: &Tag, k: Key) -> bool {
tree.get(UNTYPED).is_none()
&& legacy_entity_known(&namespaced(&as_str(tree.get("id")).unwrap_or_default()), k)
}
/// Whether `id` is an entity registered by the schemas V99 to V703 (CamelCase ids).
fn old_entity_known(id: &str, k: Key) -> bool {
match id {
"Minecart" => k < key(107, 0),
"TippedArrow" => k < key(143, 0),
"PolarBear" => k >= key(501, 0),
"ElderGuardian" => k >= key(700, 0),
"WitherSkeleton" | "Stray" => k >= key(701, 0),
"ZombieVillager" | "Husk" => k >= key(702, 0),
"Horse" | "Donkey" | "Mule" | "ZombieHorse" | "SkeletonHorse" => k >= key(703, 0),
"EntityHorse" => k < key(703, 0),
_ => crate::datafix::flat_tables::ENTITIES_V99.contains(&id),
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ The registry loader checks data version, duplicate states, default IDs and
block-name coverage. The local oracle exports all 35,723 state identities and
defaults from vanilla. This imports identities, not block implementations,
shapes or behavior. Registry exports and game-derived fixtures stay in `.local/`.
Chunk access requires data version 5023. A world saved by an older version is upgraded when it is opened, as 26.3 does: the file fixes (`FileFixerUpper`) and level.dat, then vanilla's DataFixers over every chunk, entity chunk, POI chunk, player, saved data, advancements and statistics file (`horizon_world::datafix`; vanilla upgrades each file as it reads it, Horizon all of them on opening). `tools/test_datafix_parity.py` compares the result with vanilla's own upgrade over worlds written by older server jars. Worlds older than the ported fixes are refused with a message pointing at `tools/upgrade_world.py`, which runs vanilla's `--forceUpgrade` on a copy. `BlockRegistry::resolve` rejects invalid property descriptors. The separate
Chunk access requires data version 5023. A world saved by an older version is upgraded when it is opened, as 26.3 does: the file fixes (`FileFixerUpper`) and level.dat, then vanilla's DataFixers over every chunk, entity chunk, POI chunk, player, saved data, advancements and statistics file (`horizon_world::datafix`; vanilla upgrades each file as it reads it, Horizon all of them on opening). `tools/test_datafix_parity.py` compares the result with vanilla's own upgrade over worlds written by older server jars. Every server data fix is ported, from the saves of 1.8 (no DataVersion) on; only the fixes of client files (options, hotbars) are not. `BlockRegistry::resolve` rejects invalid property descriptors. The separate
[block-state JSON codec](block-state-codecs.md) reproduces vanilla property
fallback for compact and full JSON forms.
@@ -21,6 +21,8 @@ import net.minecraft.server.Bootstrap;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.util.datafix.DataFixTypes;
import net.minecraft.util.datafix.DataFixers;
import net.minecraft.util.filefix.FileFix;
import net.minecraft.util.filefix.FileFixerUpper;
import net.minecraft.util.worldupdate.UpgradeProgress;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
@@ -55,6 +57,10 @@ public final class VanillaDataFixOracle {
Path out = Path.of(args[1]);
delete(out);
copy(in, out);
if (args.length > 2) {
band(out, Integer.parseInt(args[2]));
System.exit(0);
}
int current = SharedConstants.getCurrentVersion().dataVersion().version();
var fixer = DataFixers.getDataFixer();
// FileFixerUpper.fix through a real level storage access, as the game opens a
@@ -112,6 +118,74 @@ public final class VanillaDataFixOracle {
System.exit(0);
}
/**
* The data fixes up to a target DataVersion on a world in the layout of before
* 1.16, without the file fixes: lets the fixes of a range of versions be checked
* on their own, whatever the later fixes do to the same data.
*/
private static void band(Path out, int target) throws Exception {
var fixer = DataFixers.getDataFixer();
// The file fixes of the range (1493, LegacyStructureFileFix), as FileFixerUpper runs them
// (in place; the copy-on-write view and the level.dat rewrite are not what is checked).
var fileFixes = FileFixerUpper.class.getDeclaredField("fileFixes");
fileFixes.setAccessible(true);
for (Object o : (List<?>) fileFixes.get(DataFixers.getFileFixer())) {
FileFix fileFix = (FileFix) o;
if (fileFix.getVersion() <= target) {
fileFix.runFixOperations(out, new UpgradeProgress());
}
}
Path levelFile = out.resolve("level.dat");
if (Files.exists(levelFile)) {
CompoundTag root = NbtIo.readCompressed(levelFile, NbtAccounter.unlimitedHeap());
CompoundTag data = root.getCompoundOrEmpty("Data");
int from = NbtUtils.getDataVersion(data, -1);
data = DataFixTypes.LEVEL.update(fixer, data, from, target);
root.put("Data", NbtUtils.addDataVersion(data, target));
NbtIo.writeCompressed(root, levelFile);
}
String[][] dims = {{"", "minecraft:overworld"}, {"DIM-1", "minecraft:the_nether"}, {"DIM1", "minecraft:the_end"}};
for (String[] d : dims) {
Path dim = d[0].isEmpty() ? out : out.resolve(d[0]);
ResourceKey<Level> key = ResourceKey.create(Registries.DIMENSION, Identifier.parse(d[1]));
CompoundTag context = ChunkMap.getChunkDataFixContextTag(key, Optional.empty());
upgradeRegions(dim.resolve("region"), key, "chunk", DataFixTypes.CHUNK, -1, context, target);
upgradeRegions(dim.resolve("entities"), key, "entities", DataFixTypes.ENTITY_CHUNK, -1, null, target);
upgradeRegions(dim.resolve("poi"), key, "poi", DataFixTypes.POI_CHUNK, 1945, null, target);
}
for (Path file : list(out.resolve("playerdata"), ".dat")) {
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
tag = DataFixTypes.PLAYER.update(fixer, tag, NbtUtils.getDataVersion(tag), target);
NbtIo.writeCompressed(NbtUtils.addDataVersion(tag, target), file);
}
upgradeJson(out.resolve("advancements"), DataFixTypes.ADVANCEMENTS, true, target);
upgradeJson(out.resolve("stats"), DataFixTypes.STATS, false, target);
// The saved data of the old layout (data/scoreboard.dat, data/map_N.dat).
for (Path file : list(out.resolve("data"), ".dat")) {
String name = file.getFileName().toString().replace(".dat", "");
DataFixTypes type = name.equals("scoreboard") ? DataFixTypes.SAVED_DATA_SCOREBOARD
: name.matches("map_\\d+") ? DataFixTypes.SAVED_DATA_MAP_DATA : null;
if (type != null) {
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
tag = type.update(fixer, tag, NbtUtils.getDataVersion(tag, 1343), target);
NbtIo.writeCompressed(NbtUtils.addDataVersion(tag, target), file);
}
}
}
private static void upgradeJson(Path folder, DataFixTypes type, boolean removeVersion, int target) throws Exception {
var fixer = DataFixers.getDataFixer();
for (Path file : list(folder, ".json")) {
JsonElement json = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8));
var dynamic = new Dynamic<>(JsonOps.INSTANCE, json);
int from = NbtUtils.getDataVersion(dynamic, 1343);
var input = removeVersion ? dynamic.remove("DataVersion") : dynamic;
var fixed = type.update(fixer, input, from, target);
fixed = fixed.set("DataVersion", fixed.createInt(target));
Files.writeString(file, GSON.toJson(fixed.getValue()), StandardCharsets.UTF_8);
}
}
/** Chunk generator type per dimension, from the saved world generation settings. */
private static Map<String, String> generators(Path world) throws Exception {
Map<String, String> out = new HashMap<>();
@@ -192,7 +266,11 @@ public final class VanillaDataFixOracle {
if (type == null) {
continue;
}
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
// SavedDataStorage.readTagFromDisk: a file that does not start with the gzip header is plain NBT.
byte[] bytes = Files.readAllBytes(file);
boolean gzip = bytes.length >= 2 && (bytes[0] & 255) == 0x1f && (bytes[1] & 255) == 0x8b;
CompoundTag tag = gzip ? NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap())
: NbtIo.read(new java.io.DataInputStream(new java.io.ByteArrayInputStream(bytes)));
int version = NbtUtils.getDataVersion(tag, 1343);
tag = type.update(fixer, tag, version, current);
NbtIo.writeCompressed(NbtUtils.addDataVersion(tag, current), file);
+46 -4
View File
@@ -138,6 +138,9 @@ def experiments(version):
def items(e, version=None):
"""The sample stacks of an era, in the exact component formats `version` accepts."""
stacks = ITEMS_A if e == A else ITEMS_B if e == B else ITEMS_C
if version is not None and version < 2586: # 1.13.2 to 1.15
import datafix_scene_old
stacks = stacks + datafix_scene_old.items(version)
if version is None:
return stacks
return [v for v in (versioned(s, version) for s in stacks) if available(v, version)]
@@ -147,6 +150,7 @@ def items(e, version=None):
ITEM_SINCE = {
'minecraft:goat_horn': 3105,
'minecraft:decorated_pot': 3327,
'minecraft:axolotl_bucket': 2686,
}
@@ -236,6 +240,9 @@ def block_entities(e, version):
out = [(b, '{SpawnData:{id:"minecraft:zombie",ArmorItems:[{},{},{},{id:"minecraft:iron_helmet",Count:1b}]},'
'SpawnPotentials:[{Weight:1,Entity:{id:"minecraft:skeleton"}}]}') if b == 'spawner' else (b, nbt)
for b, nbt in out]
if version < 2586:
import datafix_scene_old
out += datafix_scene_old.block_entities(version)
if version >= 3682:
out.append(('crafter', '{Items:[{Slot:0b,id:"minecraft:stone",Count:1b}],triggered:1,crafting_ticks_remaining:2}'))
# Blocks the 1.20 experiment brought in 1.19.3 and 1.19.4.
@@ -309,8 +316,11 @@ def entities(e, version):
('allay', 'Inventory:[{id:"minecraft:diamond",Count:1b}]'),
('goat', ''),
]
since = {'allay': 3105, 'chest_boat': 3105, 'text_display': 3325, 'item_display': 3325}
since = {'allay': 3105, 'chest_boat': 3105, 'text_display': 3325, 'item_display': 3325, 'goat': 2700}
out = [(k, x) for k, x in out if version >= since.get(k, 0)]
if version < 2514: # 1.13.2 to 1.15: entities in the formats those versions write
import datafix_scene_old
out += datafix_scene_old.entities(version)
if version < 3086: # cats before 1.19 have a numeric CatType
out = [(k, 'CatType:1' if k == 'cat' else x) for k, x in out]
if 3105 <= version < 3322: # darkness counts its factor from a timestamp before 1.19.4
@@ -362,14 +372,46 @@ def entities(e, version):
return out
def world_commands(version):
"""(command, seconds to wait) for the scoreboard, a boss bar and a trip through the other
dimensions, before 1.17: what makes level.dat, the scoreboard and the other dimension folders carry data."""
if version >= 2586:
return []
return [
('bossbar add upgrade:boss {"text":"Boss"}', 0),
('bossbar set upgrade:boss players @a', 0),
('scoreboard objectives add kills dummy {"text":"Kills"}', 0),
('scoreboard objectives add zombies minecraft.killed:minecraft.zombie', 0),
('scoreboard players set Upgrader kills 3', 0),
('team add red {"text":"Red"}', 0),
('team modify red prefix {"text":"[R]"}', 0),
('team join red Upgrader', 0),
('advancement grant @a only minecraft:story/root', 0),
('execute in minecraft:the_end run tp Upgrader 100 60 0', 20),
('execute in minecraft:the_nether run tp Upgrader 0 80 0', 15),
]
def blocks(version):
"""Plain blocks whose states changed over the versions."""
if version < 2586:
import datafix_scene_old
return datafix_scene_old.blocks(version)
return []
def player_commands(e, name, version=None):
"""Give the joined bot a varied inventory and ender chest."""
out = []
stacks = items(e, version)
if version is not None and version < 2700: # `/item` arrived in 1.17
replace = lambda slot, item: f'replaceitem entity {name} {slot} {item}'
else:
replace = lambda slot, item: f'item replace entity {name} {slot} with {item}'
for i, stack in enumerate(stacks[:30]):
out.append(f'item replace entity {name} container.{i} with {give_form(e, stack)}')
out.append(f'item replace entity {name} enderchest.0 with {give_form(e, stacks[0])}')
out.append(f'item replace entity {name} armor.head with minecraft:iron_helmet')
out.append(replace(f'container.{i}', give_form(e, stack)))
out.append(replace('enderchest.0', give_form(e, stacks[0])))
out.append(replace('armor.head', 'minecraft:iron_helmet'))
out.append(f'xp set {name} 5 levels')
return out
File diff suppressed because it is too large Load Diff
+119
View File
@@ -0,0 +1,119 @@
"""Scene additions for worlds saved by 1.13.2 to 1.16.5 (DataVersion 1631 to 2586): the entities, block
entities and items whose save format those versions changed, in the syntax and format of the version
that writes them (numeric UUIDMost/UUIDLeast, string owner UUIDs, Profession/Career villagers, ...).
Every entry is (minimum DataVersion, maximum DataVersion exclusive, value); datafix_scene.py adds the
ones valid for the world's version to its general scene.
"""
U1 = '11111111-2222-3333-4444-555555555555'
U2 = '66666666-7777-8888-9999-aaaaaaaaaaaa'
MODIFIERS = ('[{Name:"horse.jumpStrength",Base:0.7d},{Name:"generic.maxHealth",Base:20.0d,'
'Modifiers:[{Name:"m",Amount:1.0d,Operation:0,UUIDMost:5L,UUIDLeast:6L}]}]')
TRADES = ('{buy:{id:"minecraft:wheat",Count:20b},sell:{id:"minecraft:emerald",Count:1b},maxUses:16,uses:1,rewardExp:1b},'
'{buy:{id:"minecraft:paper",Count:24b},sell:{id:"minecraft:emerald",Count:1b},maxUses:16,uses:0},'
'{buy:{id:"minecraft:book",Count:4b},sell:{id:"minecraft:emerald",Count:1b},maxUses:12,uses:0},'
'{buy:{id:"minecraft:ink_sac",Count:5b},sell:{id:"minecraft:emerald",Count:1b},maxUses:12,uses:0}')
# (since, until, entity, fields)
ENTITIES = [
# 1.13.2: professions are numbers
(1631, 1900, 'villager', 'Profession:1,Career:2,CareerLevel:2,Offers:{Recipes:[%s]},Inventory:[{id:"minecraft:bread",Count:3b}]' % TRADES),
(1631, 1900, 'villager', 'Profession:3,Career:3,CareerLevel:1'),
(1631, 1900, 'zombie_villager', 'Profession:4,Career:2'),
(1631, 1900, 'ocelot', 'CatType:2,OwnerUUID:"%s"' % U1),
(1631, 1900, 'ocelot', 'CatType:0'),
(1631, 1900, 'ocelot', 'CatType:0,OwnerUUID:"%s"' % U2),
# 1.14: VillagerData and Xp; some without them
(1900, 2100, 'villager', 'VillagerData:{profession:"minecraft:farmer",level:1,type:"minecraft:plains"},'
'Offers:{Recipes:[%s]},Gossips:[{Type:"golem",Value:5},{Type:"major_positive",Value:2}]' % TRADES),
(1900, 2100, 'villager', 'VillagerData:{profession:"minecraft:armorer",level:3,type:"minecraft:desert"},Xp:70'),
(1900, 2100, 'zombie_villager', 'VillagerData:{profession:"minecraft:cleric",level:2,type:"minecraft:plains"}'),
(1900, 2100, 'cat', 'CatType:9'),
(1900, 2100, 'cat', 'CatType:3,CollarColor:5b'),
(1900, 2100, 'pillager', 'Inventory:[{id:"minecraft:arrow",Count:2b}]'),
(1900, 2100, 'fox', 'Type:"red",TrustedUUIDs:[{M:3L,L:4L}]'),
(1631, 2514, 'wolf', 'Owner:"%s",OwnerUUID:"%s",CollarColor:3b,Health:15.0f' % ('Steve', U1)),
(1631, 2514, 'horse', 'Tame:1b,OwnerUUID:"%s",SaddleItem:{id:"minecraft:saddle",Count:1b},'
'ArmorItem:{id:"minecraft:iron_horse_armor",Count:1b},Attributes:%s' % (U2, MODIFIERS)),
(1631, 2514, 'armor_stand', 'Attributes:%s' % MODIFIERS),
(1631, 2514, 'cow', 'Leash:{UUIDMost:7L,UUIDLeast:8L}'),
(1631, 2509, 'zombie_pigman', 'Anger:100s,HurtBy:"%s"' % U1),
(1631, 2514, 'item', 'Item:{id:"minecraft:diamond",Count:3b},Owner:{M:9L,L:10L},Thrower:{M:11L,L:12L}'),
(1631, 2514, 'area_effect_cloud', 'OwnerUUIDMost:13L,OwnerUUIDLeast:14L,Particle:"entity_effect",Radius:2.0f,Duration:600'),
(1631, 2514, 'arrow', 'OwnerUUIDMost:15L,OwnerUUIDLeast:16L,inGround:1b'),
(1631, 2514, 'trident', 'OwnerUUIDMost:17L,OwnerUUIDLeast:18L,Trident:{id:"minecraft:trident",Count:1b}'),
(1631, 2514, 'potion', 'Potion:{id:"minecraft:splash_potion",Count:1b,tag:{Potion:"minecraft:swiftness"}},owner:{M:19L,L:20L}'),
(1631, 2514, 'snowball', 'owner:{M:21L,L:22L}'),
(1631, 2514, 'egg', 'owner:{M:23L,L:24L}'),
(1631, 2514, 'ender_pearl', 'owner:{M:25L,L:26L}'),
(1631, 2514, 'experience_bottle', 'owner:{M:27L,L:28L}'),
(1631, 2514, 'llama_spit', 'Owner:{OwnerUUIDMost:29L,OwnerUUIDLeast:30L}'),
(1631, 2514, 'shulker_bullet', 'Owner:{M:31L,L:32L},Target:{M:33L,L:34L}'),
(1631, 2514, 'evoker_fangs', 'OwnerUUIDMost:35L,OwnerUUIDLeast:36L'),
(1631, 2514, 'shulker', 'Rotation:[40.0f,0.0f],Peek:0b'),
(1631, 2514, 'bat', ''),
(2100, 2514, 'bee', 'HurtBy:"%s",HasNectar:1b,Anger:50' % U1),
(2100, 2514, 'villager', 'VillagerData:{profession:"minecraft:farmer",level:2,type:"minecraft:plains"},Xp:20,'
'Brain:{memories:{"minecraft:job_site":{pos:[I;1,2,3],dimension:"minecraft:overworld"}}}'),
]
# (since, until, block, nbt)
BLOCK_ENTITIES = [
(1631, 2514, 'white_banner', '{CustomName:\'{"translate":"block.minecraft.illager_banner","color":"gold"}\','
'Patterns:[{Pattern:"cre",Color:15}]}'),
(1631, 2514, 'chest', '{LootTable:"minecraft:chests/village_blacksmith"}'),
(1631, 2514, 'furnace', '{BurnTime:100s,CookTime:20s,CookTimeTotal:200s,RecipesUsedSize:2,RecipeLocation0:"minecraft:iron_ingot",'
'RecipeAmount0:3,RecipeLocation1:"minecraft:glass",RecipeAmount1:1}'),
(1631, 2514, 'blast_furnace', '{RecipesUsedSize:1,RecipeLocation0:"minecraft:iron_ingot",RecipeAmount0:2}') if False else None,
(1631, 2514, 'player_head', '{Owner:{Id:"%s",Name:"Notch"}}' % U1),
(1631, 2514, 'conduit', '{target_uuid:{M:5L,L:6L},Target:{M:5L,L:6L}}'),
(1631, 2514, 'oak_sign', '{Text1:\'{"text":"one"}\',Text2:\'{"text":"two"}\'}'),
(1900, 2514, 'jigsaw[facing=up]', '{attachement_type:"minecraft:bottom",target_pool:"minecraft:village/plains/houses",'
'final_state:"minecraft:air"}'),
(1900, 2514, 'jigsaw[facing=east]', '{attachement_type:"minecraft:empty",target_pool:"minecraft:empty"}'),
(1900, 2514, 'lectern', '{Book:{id:"minecraft:written_book",Count:1b,tag:{title:"L",author:"A",pages:[\'"x"\']}},Page:0}'),
(2100, 2514, 'beehive', '{Bees:[{EntityData:{id:"minecraft:bee"},TicksInHive:3,MinOccupationTicks:600}]}'),
]
BLOCK_ENTITIES = [b for b in BLOCK_ENTITIES if b]
# Plain blocks whose states changed: (since, until, command tail after "setblock x y z")
BLOCKS = [
(1900, 2500, 'cobblestone_wall[east=true,west=false,north=true,south=false]'),
(1900, 2500, 'andesite_wall[east=true,west=true,north=false,south=false,up=true]'),
(1631, 2500, 'redstone_wire[east=none,west=none,north=none,south=none,power=0]'),
(1631, 2500, 'redstone_wire[east=up,west=none,north=none,south=none,power=3]'),
(1631, 2500, 'redstone_wire[east=none,west=none,north=side,south=none,power=1]'),
(1631, 2500, 'oak_sign[rotation=3]'),
(1631, 1900, 'stone_slab[type=bottom]'),
(1631, 2100, 'bee_nest') if False else None,
]
BLOCKS = [b for b in BLOCKS if b]
ITEMS = [
(1631, 2514, '{id:"minecraft:white_banner",Count:1b,tag:{display:{Name:\'{"translate":"block.minecraft.illager_banner","color":"gold"}\','
'Lore:[\'first\',\'{"text":"second"}\']},BlockEntityTag:{Patterns:[{Pattern:"cre",Color:15}]}}}'),
(1631, 2514, '{id:"minecraft:player_head",Count:1b,tag:{SkullOwner:{Id:"%s",Name:"Notch"}}}' % U2),
(1631, 2514, '{id:"minecraft:diamond_sword",Count:1b,tag:{AttributeModifiers:[{AttributeName:"generic.attackDamage",Name:"x",Amount:2.5d,'
'Operation:0,UUIDMost:41L,UUIDLeast:42L,Slot:"mainhand"}]}}'),
(1631, 2514, '{id:"minecraft:filled_map",Count:1b,tag:{map:0}}'),
(1631, 2514, '{id:"minecraft:cactus_green",Count:1b}') if False else None,
(1631, 2514, '{id:"minecraft:stone_slab",Count:2b}') if False else None,
]
ITEMS = [i for i in ITEMS if i]
def entities(version):
return [(kind, fields) for since, until, kind, fields in ENTITIES if since <= version < until]
def block_entities(version):
return [(block, nbt) for since, until, block, nbt in BLOCK_ENTITIES if since <= version < until]
def blocks(version):
return [block for since, until, block in BLOCKS if since <= version < until]
def items(version):
return [stack for since, until, stack in ITEMS if since <= version < until]
+81 -25
View File
@@ -31,14 +31,39 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import datafix_scene as scene # noqa: E402
import datafix_scene_12 as scene12 # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
LOCAL = ROOT / '.local' / 'datafix'
# Old server jars and their worlds are inputs, not outputs: keep them beside the
# vanilla data, which parallel worktrees share (.local/minecraft links there).
SHARED = (ROOT / '.local' / 'minecraft').resolve().parent / 'datafix'
VERSIONS = ['1.17.1', '1.18.1', '1.18.2', '1.19', '1.19.2', '1.19.3', '1.19.4', '1.20.1', '1.20.2', '1.20.4', '1.20.5', '1.20.6', '1.21.1',
# Worlds saved before 1.17 are only read by branches that carry the fixes for them: until those are
# integrated they stay in the worktree's own .local, not in the folder every worktree's harness reads.
LEGACY = {'1.8.9', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', '1.14.4', '1.15.2', '1.16.1', '1.16.5'}
def worlds_dir(name):
return LOCAL / 'worlds-pre-1.17' if name.split('-')[0] in LEGACY else SHARED / 'worlds'
VERSIONS = ['1.8.9', '1.9.4', '1.10.2', '1.11.2', '1.12.2', '1.13.2', '1.14.4', '1.15.2', '1.16.1', '1.16.5', '1.17.1', '1.18.1', '1.18.2', '1.19', '1.19.2', '1.19.3', '1.19.4', '1.20.1', '1.20.2', '1.20.4', '1.20.5', '1.20.6', '1.21.1',
'1.21.3', '1.21.4', '1.21.5', '1.21.6', '1.21.8', '1.21.9', '1.21.10', '1.21.11', '26.1', '26.1.2', '26.2']
# Extra worlds of one version with another world type, for the level.dat generator settings:
# name -> (version, server.properties). They get no scene, only a joined player.
VARIANTS = {
'1.13.2-flat': ('1.13.2', {'level-type': 'flat', 'generator-settings':
'3;minecraft:bedrock,2*minecraft:dirt,minecraft:grass_block;1;village,oceanmonument,mansion(distance=30)'}),
'1.14.4-flat': ('1.14.4', {'level-type': 'flat', 'generator-settings':
'3;minecraft:bedrock,3*minecraft:stone,minecraft:grass_block;2;stronghold(distance=20 count=5),village(distance=12),'
'oceanmonument(spacing=10 separation=4)'}),
'1.14.4-largebiomes': ('1.14.4', {'level-type': 'largebiomes'}),
'1.14.4-amplified': ('1.14.4', {'level-type': 'amplified'}),
'1.13.2-debug': ('1.13.2', {'level-type': 'debug_all_block_states'}),
'1.14.4-buffet': ('1.14.4', {'level-type': 'buffet', 'generator-settings':
'{"chunk_generator":{"type":"minecraft:surface"},"biome_source":{"type":"minecraft:fixed","options":'
'{"biomes":["minecraft:desert"]}}}'}),
}
MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'
LOCK = json.loads((ROOT / 'research-lock.json').read_text())['java_runtimes']
BOT = 'Upgrader'
@@ -136,14 +161,16 @@ def install_runtime(pin, home):
class Server:
def __init__(self, directory, jar, port, packs=(), java='java'):
def __init__(self, directory, jar, port, packs=(), java='java', props_override=None):
directory.mkdir(parents=True, exist_ok=True)
self.directory = directory
(directory / 'eula.txt').write_text('eula=true\n')
props = {'server-port': port, 'online-mode': 'false', 'level-name': 'world', 'level-seed': '4242',
'view-distance': '4', 'simulation-distance': '4', 'spawn-protection': '0', 'sync-chunk-writes': 'true',
'enable-rcon': 'false', 'enable-query': 'false', 'max-tick-time': '-1'}
if packs:
props['initial-enabled-packs'] = ','.join(['vanilla', *packs])
props.update(props_override or {})
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
self.process = subprocess.Popen([java, '-Xmx2G', '-jar', str(jar), 'nogui'], cwd=directory,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
@@ -348,17 +375,56 @@ def uuid_nbt(i):
return f'[I;{UUID_BASE},0,0,{i}]'
def build(version, force=False):
def uuid_fields(data_version, i):
"""The UUID of a summoned entity: an int array since 1.16, two longs before."""
if data_version >= 2514:
return f'UUID:{uuid_nbt(i)}'
return f'UUIDMost:{UUID_BASE << 32}L,UUIDLeast:{i + 1}L'
def build_scene(server, run, Bot, port, protocol, props, era, data_version):
"""The scene of the generic generator; returns the bot that stays joined."""
if not props: # variants only differ in their world type
run('forceload add -48 -48 79 79')
run('fill 0 99 0 47 99 47 minecraft:stone')
run('fill 0 100 0 47 112 47 minecraft:air')
for i, (block, nbt) in enumerate(scene.block_entities(era, data_version)):
x, z = 1 + 3 * (i % 15), 1 + 3 * (i // 15)
run(f'setblock {x} 100 {z} minecraft:{block}{nbt}')
for i, (kind, extra) in enumerate(scene.entities(era, data_version)):
x, z = 1.5 + 3 * (i % 15), 25.5 + 3 * (i // 15)
fields = f'{uuid_fields(data_version, i)},NoAI:1b,Silent:1b,NoGravity:1b,Invulnerable:1b,PersistenceRequired:1b'
run(f'summon minecraft:{kind} {x} 100 {z} {{{fields}' + (',' + extra if extra else '') + '}')
for i, block in enumerate(scene.blocks(data_version)):
run(f'setblock {1 + 3 * (i % 15)} 100 {19 + 3 * (i // 15)} minecraft:{block}')
if not props:
run('setworldspawn 20 101 20')
bot = Bot(port, protocol, BOT)
time.sleep(3)
for command in scene.player_commands(era, BOT, data_version):
run(command)
time.sleep(3)
for command, wait in ([] if props else scene.world_commands(data_version)):
run(command)
time.sleep(wait)
run('save-all flush')
time.sleep(2)
return bot
def build(name, force=False):
version, props = VARIANTS.get(name, (name, None))
jar, data_version, protocol = server_jar(version)
target = SHARED / 'worlds' / version
data_version = data_version or 0 # 1.8 saves have no DataVersion
target = worlds_dir(name) / name
if target.exists() and not force:
print(f'{version}: kept {target}')
return []
era = scene.era(data_version)
work = LOCAL / 'gen' / version
work = LOCAL / 'gen' / name
shutil.rmtree(work, ignore_errors=True)
port = 30000 + (os.getpid() + data_version) % 20000
server = Server(work, jar, port, scene.experiments(data_version), java(version))
server = Server(work, jar, port, scene.experiments(data_version), java(version), props)
problems = []
def run(command):
@@ -368,27 +434,15 @@ def build(version, force=False):
problems.append((command[:160], bad[:2]))
return out
run('forceload add -48 -48 79 79')
run('fill 0 99 0 47 99 47 minecraft:stone')
run('fill 0 100 0 47 112 47 minecraft:air')
for i, (block, nbt) in enumerate(scene.block_entities(era, data_version)):
x, z = 1 + 3 * (i % 15), 1 + 3 * (i // 15)
run(f'setblock {x} 100 {z} minecraft:{block}{nbt}')
for i, (kind, extra) in enumerate(scene.entities(era, data_version)):
x, z = 1.5 + 3 * (i % 15), 25.5 + 3 * (i // 15)
fields = f'UUID:{uuid_nbt(i)},NoAI:1b,Silent:1b,NoGravity:1b,Invulnerable:1b,PersistenceRequired:1b'
run(f'summon minecraft:{kind} {x} 100 {z} {{{fields}' + (',' + extra if extra else '') + '}')
run('setworldspawn 20 101 20')
bot = Bot(port, protocol, BOT)
time.sleep(3)
for command in scene.player_commands(era, BOT, data_version):
run(command)
time.sleep(3)
run('save-all flush')
time.sleep(2)
if data_version < 1631 and not props: # 1.12 and older: tools/datafix_scene_12.py builds the scene and saves the world itself
bot = scene12.populate(server, Bot, port, protocol, BOT, problems)
else:
bot = build_scene(server, run, Bot, port, protocol, props, era, data_version)
bot.leave()
time.sleep(2)
server.stop()
if data_version < 1631 and not props:
scene12.fixtures(work / 'world') # the few statistics a passive bot cannot cause, written by hand
# Copy aside, then rename: an interrupted copy must not look like a finished world.
partial = target.with_name(target.name + '.partial')
shutil.rmtree(partial, ignore_errors=True)
@@ -409,8 +463,10 @@ def main():
p.add_argument('versions', nargs='*')
p.add_argument('--force', action='store_true')
args = p.parse_args()
for version in args.versions or VERSIONS:
for version in args.versions or [*VERSIONS, *VARIANTS]:
build(version, args.force)
if version == '1.12.2':
scene12.build_flat(sys.modules[__name__], args.force) # and the flat world 1.12.2-flat
if __name__ == '__main__':
+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env python3
"""Convert vanilla's BlockStateData.java into a plain data file.
Reads .local/minecraft/26.3/sources/server/net/minecraft/util/datafix/fixes/BlockStateData.java
Writes crates/horizon-world/src/datafix/block_state_data.txt
Output: UTF-8, '#' header lines, then one line per register() call, in the order the
calls execute (the static initializer order of the bootstrap* methods), tab separated:
ID <TAB> newName <TAB> newProps <TAB> legacyName1 <TAB> legacyProps1 <TAB> legacyName2 <TAB> legacyProps2 ...
Props are `key=value` pairs joined by `;`, sorted by key; empty string when there are none
(including an explicit `Map.of()`).
Usage: tools/gen_block_state_data.py [path/to/BlockStateData.java] [-o output.txt]
Re-runnable: the output only depends on the Java file.
"""
import argparse
import re
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
DEFAULT_JAVA = REPO / ".local/minecraft/26.3/sources/server/net/minecraft/util/datafix/fixes/BlockStateData.java"
DEFAULT_OUT = REPO / "crates/horizon-world/src/datafix/block_state_data.txt"
TOKEN_RE = re.compile(
r"""
(?P<ws>\s+)
| (?P<lcomment>//[^\n]*)
| (?P<bcomment>/\*.*?\*/)
| (?P<string>"(?:[^"\\]|\\.)*")
| (?P<ident>[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)
| (?P<number>-?[0-9]+)
| (?P<punct>[(),;{}=<>?\[\].@!\-+*/%|&~:^'])
""",
re.X | re.S,
)
def tokenize(text):
pos = 0
out = []
while pos < len(text):
m = TOKEN_RE.match(text, pos)
if not m:
raise SystemExit(f"tokenize error at offset {pos}: {text[pos:pos+60]!r}")
pos = m.end()
kind = m.lastgroup
if kind in ("ws", "lcomment", "bcomment"):
continue
out.append((kind, m.group()))
return out
def unquote(s):
inner = s[1:-1]
if "\\" in inner:
raise SystemExit(f"unexpected escape in string {s}")
return inner
class Parser:
"""Parses a token list holding a call expression tree: ident(args) / strings / numbers / idents."""
def __init__(self, toks, consts):
self.toks = toks
self.i = 0
self.consts = consts
def peek(self):
return self.toks[self.i] if self.i < len(self.toks) else (None, None)
def next(self):
t = self.toks[self.i]
self.i += 1
return t
def expect(self, val):
k, v = self.next()
if v != val:
raise SystemExit(f"expected {val!r} got {v!r} at token {self.i}")
def parse_args(self):
"""After '(' consumed: return list of parsed args up to ')'."""
args = []
if self.peek()[1] == ")":
self.next()
return args
while True:
args.append(self.parse_expr())
k, v = self.next()
if v == ")":
return args
if v != ",":
raise SystemExit(f"expected ',' or ')' got {v!r} at token {self.i}")
def parse_expr(self):
k, v = self.next()
if k == "string":
return ("str", unquote(v))
if k == "number":
return ("int", int(v))
if k == "ident":
if self.peek()[1] == "(":
self.next()
args = self.parse_args()
return ("call", v, args)
return ("name", v)
raise SystemExit(f"unexpected token {v!r} at {self.i}")
def eval_map(expr, consts):
"""Evaluate a Map.of(...) call or a constant name into a dict."""
if expr[0] == "name":
if expr[1] not in consts:
raise SystemExit(f"unresolved map constant {expr[1]}")
return dict(consts[expr[1]])
if expr[0] == "call" and expr[1] == "Map.of":
args = expr[2]
if len(args) % 2:
raise SystemExit("odd Map.of args")
d = {}
for a in range(0, len(args), 2):
k, v = args[a], args[a + 1]
if k[0] != "str" or v[0] != "str":
raise SystemExit(f"non-string Map.of entry {k} {v}")
if k[1] in d:
raise SystemExit(f"duplicate key {k[1]}")
d[k[1]] = v[1]
return d
raise SystemExit(f"cannot evaluate map expr {expr}")
def fmt_props(d):
for k, v in d.items():
if not re.fullmatch(r"[a-z0-9_]+", k) or not re.fullmatch(r"[A-Za-z0-9_]+", v):
raise SystemExit(f"unexpected prop chars {k}={v}")
return ";".join(f"{k}={d[k]}" for k in sorted(d))
def eval_create(expr, consts):
if expr[0] != "call" or expr[1] != "create":
raise SystemExit(f"expected create(...) got {expr}")
args = expr[2]
if not args or args[0][0] != "str":
raise SystemExit(f"create without name: {expr}")
name = args[0][1]
if not re.fullmatch(r"[a-z0-9_:]+", name) and name != "%%FILTER_ME%%":
raise SystemExit(f"bad block name {name!r}")
if len(args) == 1:
return name, ""
if len(args) == 2:
return name, fmt_props(eval_map(args[1], consts))
raise SystemExit(f"create with {len(args)} args")
def matching_brace(toks, i):
"""toks[i] is '{'; return index of matching '}'."""
depth = 0
for j in range(i, len(toks)):
if toks[j][1] == "{":
depth += 1
elif toks[j][1] == "}":
depth -= 1
if depth == 0:
return j
raise SystemExit("unbalanced braces")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("java", nargs="?", default=str(DEFAULT_JAVA))
ap.add_argument("-o", "--output", default=str(DEFAULT_OUT))
a = ap.parse_args()
java_path = Path(a.java)
text = java_path.read_text(encoding="utf-8")
toks = tokenize(text)
# ---- map constants: `private static final Map<String, String> NAME = <expr>;`
consts = {}
i = 0
n = len(toks)
while i < n:
if (
toks[i][1] == "Map"
and toks[i + 1][1] == "<"
and i >= 3
and toks[i - 1][1] == "final"
and toks[i - 2][1] == "static"
):
# Map < String , String > NAME = expr ;
j = i + 1
while toks[j][1] != ">":
j += 1
name = toks[j + 1][1]
assert toks[j + 2][1] == "=", toks[j : j + 4]
p = Parser(toks[j + 3 :], consts)
expr = p.parse_expr()
assert toks[j + 3 + p.i][1] == ";", toks[j + 3 + p.i]
if name in consts:
raise SystemExit(f"duplicate const {name}")
consts[name] = eval_map(expr, consts)
i = j + 3 + p.i
else:
i += 1
# ---- methods: find `void bootstrapX ( ) {` bodies
bodies = {}
for i in range(n - 5):
if (
toks[i][1] == "void"
and toks[i + 1][1].startswith("bootstrap")
and toks[i + 2][1] == "("
and toks[i + 3][1] == ")"
and toks[i + 4][1] == "{"
):
end = matching_brace(toks, i + 4)
bodies[toks[i + 1][1]] = toks[i + 5 : end]
# ---- static initializer order
order = None
for i in range(n - 1):
if toks[i][1] == "static" and toks[i + 1][1] == "{":
end = matching_brace(toks, i + 1)
seq = []
k = i + 2
while k < end:
if toks[k][0] == "ident" and toks[k][1].startswith("bootstrap") and toks[k + 1][1] == "(":
seq.append(toks[k][1])
k += 3
else:
k += 1
order = seq
if not order:
raise SystemExit("static initializer not found")
if set(order) != set(bodies) or len(order) != len(set(order)):
raise SystemExit(f"bootstrap methods {sorted(bodies)} vs called {order}")
# ---- parse register calls
lines = []
total_register = 0
total_create = 0
total_legacy = 0
max_id = -1
for m in order:
body = bodies[m]
k = 0
while k < len(body):
t = body[k]
if t[0] == "ident" and t[1] == "register" and body[k + 1][1] == "(":
p = Parser(body[k + 2 :], consts)
args = p.parse_args()
k += 2 + p.i
if body[k][1] != ";":
raise SystemExit(f"{m}: register not followed by ';'")
total_register += 1
if args[0][0] != "int":
raise SystemExit(f"{m}: register id not int: {args[0]}")
rid = args[0][1]
if len(args) < 2:
raise SystemExit(f"{m}: register({rid}) without new tag")
fields = [str(rid)]
for c in args[1:]:
name, props = eval_create(c, consts)
total_create += 1
fields += [name, props]
total_legacy += len(args) - 2
max_id = max(max_id, rid)
lines.append("\t".join(fields))
else:
# anything other than register(...) ; in a bootstrap body is unexpected
raise SystemExit(f"{m}: unexpected token {t} in body")
k += 1
k += 1 # skip ';'
# ---- independent validation: count `register(` occurrences inside bootstrap bodies (text based)
src_lines = text.split("\n")
in_body = False
textual = 0
for ln in src_lines:
if re.match(r"\s*private static void bootstrap\w*\(\)\s*\{", ln):
in_body = True
continue
if in_body:
if re.match(r" \}\s*$", ln):
in_body = False
continue
textual += len(re.findall(r"\bregister\(", ln))
if textual != total_register or textual != len(lines):
raise SystemExit(f"register count mismatch: textual {textual}, parsed {total_register}, lines {len(lines)}")
textual_create = 0
in_body = False
for ln in src_lines:
if re.match(r"\s*private static void bootstrap\w*\(\)\s*\{", ln):
in_body = True
continue
if in_body:
if re.match(r" \}\s*$", ln):
in_body = False
continue
textual_create += len(re.findall(r"\bcreate\(", ln))
if textual_create != total_create:
raise SystemExit(f"create count mismatch: textual {textual_create}, parsed {total_create}")
header = [
"# Generated by tools/gen_block_state_data.py from vanilla 26.3 BlockStateData.java. Do not edit.",
"# One line per register(ID, new, legacy...) call, in execution order of the static initializer",
"# (bootstrap0, 1, 2, 3_1, 3_2, 4 .. 9, A .. F).",
"# Format (tab separated): ID <TAB> newName <TAB> newProps [<TAB> legacyName <TAB> legacyProps]...",
"# ID is the decimal 1.12 (blockId << 4 | data) id; newName/newProps is the 1.13 block state;",
"# each legacy pair is a 1.12 Name + Properties tag that maps to ID.",
"# Props: key=value pairs joined by ';', sorted by key; empty string when there are none.",
"# newName may be the literal %%FILTER_ME%% (vanilla FILTER_ME marker, the skull ids 2304..2317).",
]
out = Path(a.output)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(header + lines) + "\n", encoding="utf-8")
print(f"java: {java_path}")
print(f"output: {out}")
print(f"map constants: {len(consts)}")
print(f"bootstrap order: {' '.join(order)}")
print(f"register calls: {total_register} (grep count {textual})")
print(f"data lines: {len(lines)}")
print(f"create() calls: {total_create} (all resolved; grep count {textual_create})")
print(f"legacy tags: {total_legacy}")
print(f"highest ID: {max_id}")
if __name__ == "__main__":
sys.exit(main())
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""Copy the lookup tables of vanilla's flattening-era DataFixers (1.12.2 -> 1.13.2) into
crates/horizon-world/src/datafix/flat_tables.rs, so that the Rust fixes use exactly vanilla's
data. Run from the repository root; the vanilla sources are the ones under .local/minecraft.
gen_flat_tables.py [-o OUT]
"""
import argparse
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
FIXES = ROOT / '.local' / 'minecraft' / '26.3' / 'sources' / 'server' / 'net' / 'minecraft' / 'util' / 'datafix' / 'fixes'
OUT = ROOT / 'crates' / 'horizon-world' / 'src' / 'datafix' / 'flat_tables.rs'
STR = r'"((?:[^"\\]|\\.)*)"'
def declaration(text, var):
"""The source of `NAME = ...;` for a field called `var`."""
m = re.search(r'\b' + re.escape(var) + r'\s*=', text)
if not m:
sys.exit(f'declaration {var} not found')
depth = 0
i = m.end()
while True:
c = text[i]
if c in '({[':
depth += 1
elif c in ')}]':
depth -= 1
elif c == '"':
i = text.index('"', i + 1)
while text[i - 1] == '\\':
i = text.index('"', i + 1)
elif c == ';' and depth == 0:
return text[m.end():i]
i += 1
def pairs(path, var, value_int=False, key_int=False):
body = declaration((FIXES / path).read_text(), var)
key = r'(\d+)' if key_int else STR
value = r'(\d+)' if value_int else STR
out = re.findall(r'put\(\s*' + key + r',\s*' + value + r'\s*\)', body)
if not out:
sys.exit(f'{path} {var}: no entries')
return out
def pairs_array(path, var, nullable=False):
"""`map[N] = "x";` entries of an array declaration."""
text = (FIXES / path).read_text()
start = text.index(var)
body = text[start:text.index('});', start)]
out = re.findall(r'map\[(\d+)\]\s*=\s*' + STR + r';', body)
if nullable:
out = [(i, v) for i, v in out]
if not out:
sys.exit(f'{path} {var}: no entries')
return out
def strings(path, var, call):
body = declaration((FIXES / path).read_text(), var)
out = re.findall(call + r'\(\s*' + STR + r'\s*\)', body) if call else re.findall(STR, body)
if not out:
sys.exit(f'{path} {var}: no entries')
return out
def rs_str(s):
return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
def emit_pairs(name, entries, int_key=False, int_value=False, doc=''):
lines = [f'/// {doc}'] if doc else []
kt = 'i32' if int_key else '&str'
vt = 'i32' if int_value else '&str'
lines.append(f'pub static {name}: &[({kt}, {vt})] = &[')
for k, v in entries:
a = k if int_key else rs_str(k)
b = v if int_value else rs_str(v)
lines.append(f' ({a}, {b}),')
lines.append('];')
return '\n'.join(lines)
def emit_strs(name, entries, doc=''):
lines = [f'/// {doc}'] if doc else []
lines.append(f'pub static {name}: &[&str] = &[')
lines += [f' {rs_str(s)},' for s in entries]
lines.append('];')
return '\n'.join(lines)
def schema_entities(schema_file, method='registerEntities'):
"""The entity (or block entity) ids a schema's `registerEntities` registers."""
text = (FIXES.parent / 'schemas' / schema_file).read_text()
start = text.index(method)
body = text[start:text.index('return map;', start)]
names = re.findall(r'(?:registerMob|registerSimple|registerThrowableProjectile|registerMinecart|registerInventory)\(schema, map, "([^"]+)"', body)
names += re.findall(r'schema\.registerSimple\(map, "([^"]+)"', body)
names += re.findall(r'schema\.register\(\s*map,\s*"([^"]+)"', body)
return sorted(set(names))
def structure_renames():
text = (FIXES / 'ChunkStructuresTemplateRenameFix.java').read_text()
out = []
for m in re.finditer(r'\.put\(\s*' + STR + r',\s*Pair\.of\(\s*' + STR + r',\s*ImmutableMap\.<String, String>builder\(\)((?:\s*\.put\(' + STR + r',\s*' + STR + r'\))*)\s*\.build\(\)', text):
structure, child = m.group(1), m.group(2)
entries = re.findall(r'\.put\(' + STR + r',\s*' + STR + r'\)', m.group(3))
out.append((structure, child, entries))
if len(out) != 4:
sys.exit(f'expected 4 structure renames, found {len(out)}')
lines = ['/// `ChunkStructuresTemplateRenameFix.RENAMES`: structure id, child id, template renames.',
'pub static STRUCTURE_TEMPLATE_RENAMES: &[(&str, &str, &[(&str, &str)])] = &[']
for structure, child, entries in out:
lines.append(f' ({rs_str(structure)}, {rs_str(child)}, &[')
lines += [f' ({rs_str(a)}, {rs_str(b)}),' for a, b in entries]
lines.append(' ]),')
lines.append('];')
return '\n'.join(lines)
def main():
p = argparse.ArgumentParser()
p.add_argument('-o', '--out', default=str(OUT))
args = p.parse_args()
parts = [
'//! Lookup tables of the DataFixers of 1.13 (DataVersion 1343 to 1631), copied from vanilla\'s\n'
'//! sources by `tools/gen_flat_tables.py`. Do not edit.\n',
emit_pairs('ITEM_FLATTENING', pairs('ItemStackTheFlatteningFix.java', 'MAP'),
doc='`ItemStackTheFlatteningFix.MAP`: `id.damage` to the flattened item.'),
emit_strs('ITEM_DAMAGE_IDS', strings('ItemStackTheFlatteningFix.java', 'DAMAGE_IDS', ''),
doc='`ItemStackTheFlatteningFix.DAMAGE_IDS`: items that keep their damage in `tag.Damage`.'),
emit_pairs('BLOCK_IDS', pairs('EntityBlockStateFix.java', 'MAP', value_int=True), int_value=True,
doc='`EntityBlockStateFix.MAP`: 1.12 block name to numeric id.'),
emit_pairs('ITEM_IDS', pairs('ItemIdFix.java', 'ITEM_NAMES', key_int=True), int_key=True,
doc='`ItemIdFix.ITEM_NAMES`: numeric item id to name.'),
emit_strs('SPECIAL_OBJECTIVE_CRITERIA', strings('StatsCounterFix.java', 'SPECIAL_OBJECTIVE_CRITERIA', '')),
emit_strs('STATS_SKIP', strings('StatsCounterFix.java', 'SKIP', 'add')),
emit_pairs('STATS_CUSTOM', pairs('StatsCounterFix.java', 'CUSTOM_MAP')),
emit_pairs('STATS_ITEM_KEYS', pairs('StatsCounterFix.java', 'ITEM_KEYS')),
emit_pairs('STATS_ENTITY_KEYS', pairs('StatsCounterFix.java', 'ENTITY_KEYS')),
emit_pairs('STATS_ENTITIES', pairs('StatsCounterFix.java', 'ENTITIES')),
emit_pairs('RECIPES', pairs('RecipesFix.java', 'RECIPES')),
emit_pairs('RECIPES_RENAMENING', pairs('RecipesRenameningFix.java', 'RECIPES')),
emit_pairs('ADVANCEMENTS', pairs('AdvancementsFix.java', 'RENAMES')),
emit_pairs('GENERATOR_BIOMES', pairs('LevelDataGeneratorOptionsFix.java', 'MAP')),
emit_pairs('SPAWN_EGGS', pairs('ItemStackSpawnEggFix.java', 'MAP')),
emit_pairs('ENCHANTMENTS', pairs('ItemStackEnchantmentNamesFix.java', 'MAP', key_int=True), int_key=True),
emit_pairs('CORAL', pairs('RenamedCoralFix.java', 'RENAMED_IDS')),
emit_pairs('CORAL_FANS', pairs('RenamedCoralFansFix.java', 'RENAMED_IDS')),
emit_pairs('THE_RENAMENING_ENTITIES', pairs('EntityTheRenameningFix.java', 'RENAMED_IDS')),
emit_pairs('THE_RENAMENING_BLOCKS', pairs('EntityTheRenameningFix.java', 'RENAMED_BLOCKS')),
emit_pairs('COD_SALMON', pairs('EntityCodSalmonFix.java', 'RENAMED_IDS')),
emit_pairs('COD_SALMON_EGGS', pairs('EntityCodSalmonFix.java', 'RENAMED_EGG_IDS')),
emit_strs('ENTITIES_V1460', schema_entities('V1460.java'),
doc='The entity ids V1460 registers (V705 has the same ones).'),
emit_strs('ENTITIES_V99', schema_entities('V99.java'), doc='The entity ids V99 registers.'),
emit_strs('BLOCK_ENTITIES_V99', schema_entities('V99.java', 'registerBlockEntities'),
doc='The block entity ids V99 registers.'),
emit_pairs('SPAWN_EGG_ENTITIES', pairs_array('ItemSpawnEggFix.java', 'ID_TO_ENTITY'), int_key=True,
doc='`ItemSpawnEggFix.ID_TO_ENTITY`: spawn egg damage to entity id.'),
emit_pairs('ENTITY_IDS', pairs('EntityIdFix.java', 'ID_MAP'), doc='`EntityIdFix.ID_MAP`.'),
emit_pairs('BLOCK_ENTITY_IDS', pairs('BlockEntityIdFix.java', 'ID_MAP'), doc='`BlockEntityIdFix.ID_MAP`.'),
emit_pairs('ITEM_TO_BLOCK_ENTITY_V99', pairs('../schemas/V99.java', 'ITEM_TO_BLOCKENTITY'),
doc='`V99.ITEM_TO_BLOCKENTITY`.'),
emit_pairs('ITEM_POTIONS', pairs_array('ItemPotionFix.java', 'POTIONS', nullable=True), int_key=True,
doc='`ItemPotionFix.POTIONS`: damage & 127 to potion (absent: null).'),
structure_renames(),
]
Path(args.out).write_text('\n\n'.join(parts) + '\n')
subprocess.run(['rustfmt', '--edition', '2024', args.out], check=True)
print('wrote', args.out)
if __name__ == '__main__':
main()
+21 -11
View File
@@ -53,6 +53,10 @@ IGNORED = {
}
def world_path(name):
return (LOCAL / 'worlds-pre-1.17' if (LOCAL / 'worlds-pre-1.17' / name).is_dir() else WORLDS) / name
def java_classpath():
import oracle_harness as harness
import test_rust_parity as base
@@ -83,20 +87,20 @@ def shard(items):
return items[index - 1::count]
def run_vanilla(classpath, world, out):
def run_vanilla(classpath, world, out, target=None):
# The oracle replaces OUT itself: left in place, an unchanged run's outputs can be reused.
log = out.parent / (out.name + '.log')
with log.open('w') as f:
subprocess.run(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', classpath,
'dev.horizonlab.parity.VanillaDataFixOracle', str(world), str(out)],
'dev.horizonlab.parity.VanillaDataFixOracle', str(world), str(out), *([str(target)] if target else [])],
check=True, stdout=f, stderr=subprocess.STDOUT)
def run_horizon(binary, world, out):
def run_horizon(binary, world, out, target=None):
shutil.rmtree(out, ignore_errors=True)
log = out.parent / (out.name + '.log')
with log.open('w') as f:
subprocess.run([str(binary), str(world), str(out)], check=True, stdout=f, stderr=subprocess.STDOUT)
subprocess.run([str(binary), str(world), str(out), *([str(target)] if target else [])], check=True, stdout=f, stderr=subprocess.STDOUT)
# ---------------------------------------------------------------- comparison
@@ -206,38 +210,44 @@ def main():
p.add_argument('--keep', action='store_true')
p.add_argument('--vanilla-only', action='store_true', help='only run the oracle')
p.add_argument('--binary', help='a prebuilt datafix_world example')
p.add_argument('--band', type=int, metavar='TARGET', help='check the data fixes up to this DataVersion only (not the '
'file fixes), on the sample worlds saved before it, for developing the fixes of a range of versions')
args = p.parse_args()
import datafix_worlds
import fcntl
WORLDS.parent.mkdir(parents=True, exist_ok=True)
with open(WORLDS.parent / 'generate.lock', 'w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX) # another worktree may be generating them
missing = [v for v in datafix_worlds.VERSIONS if not (WORLDS / v / 'level.dat').exists()]
missing = [v for v in [*datafix_worlds.VERSIONS, *datafix_worlds.VARIANTS] if not (datafix_worlds.worlds_dir(v) / v / 'level.dat').exists()]
if missing:
print('generating sample worlds:', ' '.join(missing), flush=True)
subprocess.run([sys.executable, str(ROOT / 'tools' / 'datafix_worlds.py'), *missing], cwd=ROOT, check=True)
worlds = sorted(p.name for p in WORLDS.iterdir() if p.is_dir())
worlds = sorted(p.name for d in (WORLDS, LOCAL / 'worlds-pre-1.17') if d.is_dir() for p in d.iterdir() if p.is_dir())
band = args.band
if band and not args.versions: # worlds in the layout of before 1.16, saved before the target
worlds = [w for w in worlds if json.loads((world_path(w) / 'datafix-source.json').read_text())['data_version'] < band]
versions = shard(args.versions or worlds)
classpath = java_classpath()
binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust()
total = 0
for version in versions:
world = WORLDS / version
world = world_path(version)
source = json.loads((world / 'datafix-source.json').read_text())
print(f'{version} (DataVersion {source["data_version"]})')
RUN.mkdir(parents=True, exist_ok=True)
run_vanilla(classpath, world, RUN / f'{version}-vanilla')
tag = f'{version}-band{band}' if band else version
run_vanilla(classpath, world, RUN / f'{tag}-vanilla', band)
if binary is None:
continue
run_horizon(binary, world, RUN / f'{version}-horizon')
failures = summarize(compare(RUN / f'{version}-vanilla', RUN / f'{version}-horizon'))
run_horizon(binary, world, RUN / f'{tag}-horizon', band)
failures = summarize(compare(RUN / f'{tag}-vanilla', RUN / f'{tag}-horizon'))
print(f' {version}: {"ok" if not failures else f"{failures} differences"}')
total += failures
if binary is not None:
print('datafix parity', 'FAILED' if total else 'ok', f'({total} differences over {len(versions)} worlds)')
if not total and not args.keep:
for version in versions: # vanilla outputs stay, for reuse
shutil.rmtree(RUN / f'{version}-horizon', ignore_errors=True)
shutil.rmtree(RUN / f'{version}-band{band}-horizon' if band else RUN / f'{version}-horizon', ignore_errors=True)
sys.exit(1 if total else 0)