diff --git a/crates/horizon-client/examples/hotbar_fixture.rs b/crates/horizon-client/examples/hotbar_fixture.rs new file mode 100644 index 000000000..beac564ec --- /dev/null +++ b/crates/horizon-client/examples/hotbar_fixture.rs @@ -0,0 +1,42 @@ +//! Creative toolbars read through the data fixers, for +//! tools/test_hotbar_parity.py: reads one JSON case per line (the SNBT of a +//! `hotbar.nbt`, or null for a missing file) and prints the stacks of the nine +//! rows after `horizon_client::hotbar::from_tag`. +//! +//! usage: hotbar_fixture RESOURCES CASES OUTPUT +use horizon_client::{hotbar, item_data::canon_stack, items::Items}; +use horizon_world::nbt::{Tag, parse_snbt}; +use serde_json::Value; +use std::path::Path; +use std::{fmt::Write as _, fs}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: hotbar_fixture RESOURCES CASES OUTPUT"; + let items = Items::catalog(Path::new(args.first().and(args.get(1)).ok_or(usage)?))?; + let known = |id: &str| items.get(id).is_some(); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let rows = match case["snbt"].as_str() { + Some(text) => match parse_snbt(text) { + Ok((tag @ Tag::Compound(_), _)) => hotbar::from_tag(tag, &known), + _ => return Err("case snbt".into()), + }, + None => (0..hotbar::GROUPS) + .map(|_| vec![None; hotbar::SIZE]) + .collect(), + }; + for (i, row) in rows.iter().enumerate() { + let _ = write!(out, "{i}:"); + for stack in row { + let _ = write!(out, " {}", canon_stack(stack.as_ref())); + } + out.push_str(" | "); + } + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/hotbar.rs b/crates/horizon-client/src/hotbar.rs new file mode 100644 index 000000000..a60f28287 --- /dev/null +++ b/crates/horizon-client/src/hotbar.rs @@ -0,0 +1,121 @@ +//! The creative mode toolbars of `hotbar.nbt` (`HotbarManager`, +//! `Hotbar`): nine saved rows of nine stacks, read through the `HOTBAR` +//! data fixers when the file is from an older version. +use crate::{items::ItemStack, save}; +use horizon_world::nbt::{JavaString, Tag}; +use std::path::Path; + +/// `HotbarManager.NUM_HOTBAR_GROUPS`. +pub const GROUPS: usize = 9; +/// `Inventory.getSelectionSize`: the stacks of one saved row. +pub const SIZE: usize = 9; + +/// One saved toolbar row. +pub type Hotbar = Vec>; + +fn empty() -> Hotbar { + vec![None; SIZE] +} + +/// `Hotbar.CODEC` and `Hotbar.load` on the row's tag: a row of fewer than nine +/// entries is lost, a longer one is cut (`Util.fixedSize` returns the first +/// nine as a partial result), an entry that is not a stack is empty. +fn row(tag: Option<&Tag>, known: &dyn Fn(&str) -> bool) -> Hotbar { + let Some(Tag::List(items)) = tag else { + return empty(); + }; + if items.len() < SIZE { + return empty(); + } + items.iter().take(SIZE).map(|t| stack(t, known)).collect() +} + +/// `ItemStack.OPTIONAL_CODEC` of a saved stack: the count is lenient (1 +/// unless it is a number from 1 to 99), an item that is not registered is an +/// error. +fn stack(tag: &Tag, known: &dyn Fn(&str) -> bool) -> Option { + let stack = save::item_from_nbt(tag)?; + if !known(&stack.item) { + return None; + } + let count = match tag.get("count") { + Some(Tag::Byte(n)) => i32::from(*n), + Some(Tag::Short(n)) => i32::from(*n), + Some(Tag::Int(n)) => *n, + _ => 1, + }; + Some(ItemStack { + count: if (1..=99).contains(&count) { + count as u32 + } else { + 1 + }, + ..stack + }) +} + +/// `HotbarManager.load` on the file's tag. +pub fn from_tag(mut tag: Tag, known: &dyn Fn(&str) -> bool) -> Vec { + let version = match tag.get("DataVersion") { + Some(Tag::Int(v)) => *v, + _ => 1343, + }; + // Until the last fixer that rewrites item stacks (`UnfilledBuriedTreasureMapFix`, + // 5016) the fixers read each row as a list of stacks: an entry that is + // none is dropped from its row (a bare item id is a stack from 3818.5 on) + // and a row that is no list ends the reading. After that fixer nothing + // reads the rows and bare ids are no stacks. + const LAST_STACK_FIXER: i32 = 5016; + if version < horizon_world::DATA_VERSION + && let Tag::Compound(rows) = &mut tag + { + if version < LAST_STACK_FIXER { + // A row that is no list stops the traversal there: it and the + // rows after it (in key order) are lost. + let broken = (0..GROUPS).find(|i| { + rows.get(&JavaString::from(i.to_string().as_str())) + .is_some_and(|r| { + !matches!( + r, + Tag::List(_) | Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_) + ) + }) + }); + if let Some(broken) = broken { + for i in broken..GROUPS { + rows.remove(&JavaString::from(i.to_string().as_str())); + } + } + // Entries that are no stacks are dropped from their row. + for row in rows.values_mut() { + if let Tag::List(items) = row { + items.retain(|i| { + matches!(i, Tag::Compound(_)) + || (version > 3818 && matches!(i, Tag::String(_))) + }); + } + } + } else { + for row in rows.values_mut() { + if let Tag::List(items) = row { + for item in items.iter_mut().filter(|i| matches!(i, Tag::String(_))) { + *item = Tag::Compound(Default::default()); + } + } + } + } + } + horizon_world::datafix::update_hotbar(&mut tag); + (0..GROUPS) + .map(|i| row(tag.get(&i.to_string()), known)) + .collect() +} + +/// `HotbarManager.load` of the `hotbar.nbt` at `path`: every row empty when +/// the file is missing or unreadable. +pub fn load(path: &Path, known: &dyn Fn(&str) -> bool) -> Vec { + match save::read_dat(path) { + Some(tag @ Tag::Compound(_)) => from_tag(tag, known), + _ => (0..GROUPS).map(|_| empty()).collect(), + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6300abbbf..03fe05d3a 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -47,6 +47,7 @@ pub mod gamerules; pub mod gfx; pub mod gossip; pub mod health; +pub mod hotbar; pub mod hud; pub mod hud_layout; pub mod hud_overlays; diff --git a/crates/horizon-world/src/datafix/fixes_a.rs b/crates/horizon-world/src/datafix/fixes_a.rs index 3d89ec990..e47cf15e4 100644 --- a/crates/horizon-world/src/datafix/fixes_a.rs +++ b/crates/horizon-world/src/datafix/fixes_a.rs @@ -56,6 +56,7 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) { }) })); out.push((key(3818, 0), beehive_fields)); + out.push((key(3818, 0), empty_item_in_hotbar)); out.push((key(3818, 1), banner_patterns)); out.push((key(3818, 2), tipped_arrow_potion)); out.push((key(3818, 4), particle_unflattening)); @@ -714,6 +715,21 @@ fn beehive_fields(cx: &mut Cx) { }); } +/// `EmptyItemInHotbarFix`: a saved toolbar's air or zero-count stacks become +/// the empty compound. +fn empty_item_in_hotbar(cx: &mut Cx) { + if !matches!(cx.root, Ty::Hotbar) { + return; + } + cx.each(Ty::ItemStack, |stack| { + let air = as_str(stack.get("id")).is_none_or(|id| id == "minecraft:air"); + let empty = as_int(stack.get("Count"), 0) <= 0; + if air || empty { + *stack = empty_map(); + } + }); +} + const PATTERN_IDS: [(&str, &str); 41] = [ ("b", "minecraft:base"), ("bl", "minecraft:square_bottom_left"), diff --git a/crates/horizon-world/src/datafix/mod.rs b/crates/horizon-world/src/datafix/mod.rs index 014c84614..eb5740fa7 100644 --- a/crates/horizon-world/src/datafix/mod.rs +++ b/crates/horizon-world/src/datafix/mod.rs @@ -334,6 +334,13 @@ pub fn update_player_to(tag: &mut Tag, to: i32) { dynamic::set(tag, "DataVersion", Tag::Int(to)); } +/// `HotbarManager.load`: a creative toolbar file (`hotbar.nbt`, its DataVersion +/// 1343 when missing) brought to the current version. +pub fn update_hotbar(tag: &mut Tag) { + let version = dynamic::as_int(tag.get("DataVersion"), 1343); + update(Ty::Hotbar, tag, version, CURRENT); +} + /// The saved data type of a file below a `data` folder (`namespace/path.dat`). pub fn saved_data_type(relative: &str) -> Option { let name = relative.strip_suffix(".dat").unwrap_or(relative); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java new file mode 100644 index 000000000..99233ab77 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java @@ -0,0 +1,50 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.HotbarManager; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.nbt.TagParser; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.world.item.ItemStack; + +/** + * Original oracle for creative toolbars read from a hotbar.nbt of any version: + * each case's SNBT is written as the file and the real HotbarManager (with the + * game's DataFixer, so DataFixTypes.HOTBAR and its item stack fixers) loads it; + * each of the nine rows is then loaded with Hotbar.load and printed. + */ +public final class VanillaHotbarOracle { + public static void main(String[] args) throws Exception { + ParityData.init(); + Path dir = Files.createTempDirectory("hotbar"); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + Files.deleteIfExists(dir.resolve("hotbar.nbt")); + if (!f.get("snbt").isJsonNull()) { + CompoundTag tag = TagParser.parseCompoundFully(f.get("snbt").getAsString()); + NbtIo.write(tag, dir.resolve("hotbar.nbt")); + } + HotbarManager manager = new HotbarManager(dir, DataFixers.getDataFixer()); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < HotbarManager.NUM_HOTBAR_GROUPS; i++) { + result.append(i).append(':'); + for (ItemStack stack : manager.get(i).load(ParityData.lookup)) result.append(' ').append(ParityData.canon(stack)); + result.append(" | "); + } + out.println(result); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_hotbar_parity.py b/tools/test_hotbar_parity.py new file mode 100644 index 000000000..336bda274 --- /dev/null +++ b/tools/test_hotbar_parity.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Compare creative toolbars read from an older hotbar.nbt with the vanilla client's. + +Each case is the SNBT of a hotbar.nbt of some DataVersion (the version tag +missing means 1343): nine rows of nine stacks in the item format of that era +(damage values of 1.12, `tag` compounds of 1.13 to 1.20.4, components of +1.20.5 on), with empty stacks (air, count zero or negative, no +id), rows of the wrong size or type and garbage. The Java oracle +(VanillaHotbarOracle) writes the file and loads it with the client's real +HotbarManager and DataFixers (DataFixTypes.HOTBAR, so EmptyItemInHotbarFix +and every item stack fixer), then Hotbar.load on each row; +examples/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine +rows' stacks are compared. +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import test_model_baking_parity as baking + import test_rust_parity as base + +VERSIONS = [None, 1343, 1344, 1451, 1519, 1631, 1976, 2200, 2504, 2586, 2730, 2975, 3105, 3218, 3337, 3465, 3578, 3698, + 3700, 3817, 3818, 3820, 3824, 3825, 3900, 4059, 4082, 4189, 4325, 4540, 4650, 4780, 4900, 5023] + +LEGACY = [ + '{id:"minecraft:planks",Damage:2s,Count:3b}', '{id:"minecraft:wool",Damage:14s,Count:64b}', + '{id:"minecraft:stone",Damage:3s,Count:1b}', '{id:"minecraft:log",Damage:1s,Count:1b}', + '{id:"minecraft:log2",Damage:1s,Count:7b}', '{id:"minecraft:potion",Damage:8193s,Count:1b}', + '{id:"minecraft:diamond_pickaxe",Damage:12s,Count:1b,tag:{ench:[{id:32s,lvl:3s}],display:{Name:"Pick"}}}', + '{id:"minecraft:golden_apple",Damage:1s,Count:2b}', '{id:"minecraft:dye",Damage:4s,Count:5b}', + '{id:"minecraft:stained_glass_pane",Damage:5s,Count:9b}', '{id:"minecraft:skull",Damage:3s,Count:1b,tag:{SkullOwner:"Notch"}}', + '{id:"minecraft:banner",Damage:1s,Count:1b,tag:{BlockEntityTag:{Base:1,Patterns:[{Pattern:"cre",Color:15}]}}}', + '{id:"minecraft:tallgrass",Damage:1s,Count:1b}', '{id:"minecraft:stick",Count:1b}', '{id:"minecraft:iron_sword",Count:1b,Damage:40s}', + '{id:"minecraft:bed",Damage:14s,Count:1b}', '{id:"minecraft:monster_egg",Damage:2s,Count:3b}', + '{id:"minecraft:written_book",Count:1b,tag:{title:"t",author:"a",pages:["{\\"text\\":\\"p\\"}"]}}', +] +CLASSIC = [ + '{id:"minecraft:diamond_sword",Count:1b,tag:{Damage:5,Enchantments:[{id:"minecraft:sharpness",lvl:3s}],display:{Name:\'{"text":"Cool"}\'}}}', + '{id:"minecraft:potion",Count:1b,tag:{Potion:"minecraft:strong_healing"}}', '{id:"minecraft:stone",Count:64b}', + '{id:"minecraft:firework_rocket",Count:3b,tag:{Fireworks:{Flight:2b}}}', '{id:"minecraft:cobblestone",Count:12b}', + '{id:"minecraft:player_head",Count:1b,tag:{SkullOwner:"Notch"}}', '{id:"minecraft:dirt",Count:2b}', + '{id:"minecraft:white_banner",Count:1b,tag:{BlockEntityTag:{Patterns:[{Pattern:"cre",Color:15}]}}}', + '{id:"minecraft:enchanted_book",Count:1b,tag:{StoredEnchantments:[{id:"minecraft:mending",lvl:1s}]}}', + '{id:"minecraft:tipped_arrow",Count:8b,tag:{Potion:"minecraft:weakness"}}', '{id:"minecraft:string",Count:3b}', + '{id:"minecraft:iron_axe",Count:1b,tag:{Damage:3,RepairCost:7,Unbreakable:1b}}', + '{id:"minecraft:filled_map",Count:1b,tag:{map:12}}', '{id:"minecraft:leather_chestplate",Count:1b,tag:{display:{color:255}}}', + '{id:"minecraft:shield",Count:1b,tag:{BlockEntityTag:{Base:3}}}', '{id:"minecraft:bundle",Count:1b,tag:{Items:[{id:"minecraft:stone",Count:2b}]}}', + '{id:"minecraft:diamond_sword",Count:1b,tag:{AttributeModifiers:[{AttributeName:"generic.attack_damage",Name:"x",Amount:2.5d,Operation:0,UUID:[I;1,2,3,4],Slot:"mainhand"}]}}', +] +COMPONENTS = [ + '{id:"minecraft:diamond_sword",count:1,components:{"minecraft:damage":5}}', '{id:"minecraft:stone",count:64}', + '{id:"minecraft:potion",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:strong_healing"}}}', + '{id:"minecraft:firework_rocket",count:3,components:{"minecraft:fireworks":{flight_duration:2b}}}', + '{id:"minecraft:white_banner",count:1}', '{id:"minecraft:iron_axe",count:1,components:{"minecraft:repair_cost":7}}', + '{id:"minecraft:grass_block",count:2}', '{id:"minecraft:cobblestone",count:12}', '{id:"minecraft:stone"}', +] +JUNK = ['{}', '{id:"minecraft:air",Count:1b}', '{id:"minecraft:stone",Count:0b}', '{id:"minecraft:stone",Count:-3b}', + '{Count:5b}', '{id:"minecraft:stone"}', '{id:"minecraft:air",count:3}', '{id:"minecraft:stone",count:0}', + '{id:"minecraft:stone",count:200}', '{id:"minecraft:stone",Count:100b}', '{id:"minecraft:nonexistent",Count:1b}', + '{id:5s,Count:1b}', '{id:"minecraft:stone",Count:"x"}'] +# Entries that are no stacks, and rows that are no lists: the fixers drop the entry from its row (so a row of ten +# with one is a full row, and a row of nine a short one) and a row that is no list ends the reading. Several of +# them in one file interact in ways this does not follow, so each gets its own file. +ODD = ['"stone"', '5', '[]', '1b', '{}', '[I;1,2]'] + + +def pool(version): + v = version or 1343 + if v < 1451: + return LEGACY + if v < 3819: + return CLASSIC + return COMPONENTS + + +def stack(rng, version): + r = rng.random() + if r < 0.75: + return rng.choice(pool(version)) + if r < 0.92: + return rng.choice(JUNK) + return rng.choice(pool(rng.choice(VERSIONS))) + + +def case(rng): + version = rng.choice(VERSIONS) + rows = [] + elements = {} + for i in range(9): + r = rng.random() + if r < 0.04: + continue + if r < 0.07: + rows.append(f'"{i}":5') + continue + size = 9 if r < 0.93 else rng.choice([0, 8, 10]) + stacks = [stack(rng, version) for _ in range(size)] + elements[i] = stacks + rows.append(f'"{i}":[' + ','.join(stacks) + ']') + head = '' if version is None else f'DataVersion:{version},' + return {'snbt': '{' + head + ','.join(rows) + '}', 'version': version, 'elements': elements} + + +def odd_cases(): + cases = [] + for version in [None, 1343, 1631, 3337, 3700, 3818, 3819, 3824, 4325, 4540, 5015, 5016, 5022, 5023]: + v = version or 1343 + ok = '{id:"minecraft:stone",Count:2b}' if v < 3819 else '{id:"minecraft:stone",count:2}' + head = '' if version is None else f'DataVersion:{version},' + good = '[' + ','.join([ok] * 9) + ']' + for odd in ODD: + for position in (0, 4, 8): + row = [ok] * 9 + row[position] = odd + cases.append({'snbt': '{' + head + f'"0":[{",".join(row)}],"1":{good}' + '}'}) + for row_size in (8, 10): + row = [ok] * row_size + row[3] = odd + cases.append({'snbt': '{' + head + f'"0":[{",".join(row)}],"1":{good}' + '}'}) + # A row that is none: the rows after it. + cases.append({'snbt': '{' + head + ','.join(f'"{i}":{odd if i == 2 else good}' for i in range(9)) + '}'}) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=23) + parser.add_argument('--cases', type=int, default=400) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + rng = random.Random(args.seed) + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('hotbar-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'VanillaHotbarOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + cases = [{'snbt': None}] + odd_cases() + [case(rng) for _ in range(args.cases)] + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaHotbarOracle', + str(work / 'cases.jsonl'), str(work / 'native.txt')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'hotbar_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', lambda c, line: 'hotbar' if not line.startswith('error') else 'oracle error', + describe=lambda c: c['snbt'][:300] if c['snbt'] else 'missing file', limit=args.limit) + raise SystemExit(1 if bad else 0) + + +if __name__ == '__main__': + main()