Datafix harness: --band TARGET checks the fixes up to a DataVersion on legacy-layout worlds; fixes sorted by key
This commit is contained in:
@@ -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) => {
|
||||
|
||||
@@ -611,6 +611,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 +625,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 +676,54 @@ 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, without the file fixes: the harness checks the data 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<()> {
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
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)?;
|
||||
|
||||
@@ -182,6 +182,8 @@ fn fixes() -> Vec<(Key, FixFn)> {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -227,8 +229,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 +244,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 +272,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);
|
||||
|
||||
@@ -55,6 +55,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 +116,53 @@ 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();
|
||||
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);
|
||||
}
|
||||
|
||||
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<>();
|
||||
|
||||
@@ -83,20 +83,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,6 +206,8 @@ 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
|
||||
@@ -217,6 +219,9 @@ def main():
|
||||
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())
|
||||
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((WORLDS / 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()
|
||||
@@ -226,18 +231,19 @@ def main():
|
||||
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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user