diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..13584e4d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Generated files that tests compare byte for byte with what they generate: LF on every OS, also +# where Git for Windows' core.autocrlf would check them out with CRLF. +docs/launcher-commands.md text eol=lf +docs/horizon-ctl-commands.md text eol=lf +website/src/tokens.css text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17075add1..1dfd43300 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,7 +61,8 @@ jobs: if: steps.rust.outputs.required != 'false' run: | cargo +stable fmt --all -- --check - cargo +stable clippy --workspace --all-targets -- -D warnings + # With the game's code mods (on in every release build, off by default). + cargo +stable clippy --workspace --all-targets --features horizon-client/mods -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings # Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already @@ -69,8 +70,8 @@ jobs: - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' run: | - cargo +stable test --workspace --lib --bins --tests - cargo +stable test --workspace --doc + cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack + cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 95a2fec64..a0953c73a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -133,7 +133,8 @@ jobs: if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev - name: Build the client, horizon-ctl, horizon-prepare and horizon-server - run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server + # `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds). + run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server - name: Every program the release folder takes was built run: | for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do @@ -255,8 +256,9 @@ jobs: run: | set -euo pipefail # After the client is packaged: target/release/horizon-client is rebuilt without the audio and - # controllers features, so it needs neither libasound nor libudev (minimal server images lack them). - cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them), + # and with code mods like the client. + cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" diff --git a/Cargo.lock b/Cargo.lock index 2f832e248..1a1b288c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1493,7 +1493,6 @@ dependencies = [ name = "horizon-mods" version = "0.1.0" dependencies = [ - "horizon-mods", "log", "serde", "serde_json", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index cd5d86fe7..c0296cc1c 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -18,7 +18,8 @@ horizon-protocol = { path = "../horizon-protocol" } horizon-server-files = { path = "../horizon-server-files" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). -horizon-mods = { path = "../horizon-mods" } +# Their runtime is the `mods` feature. +horizon-mods = { path = "../horizon-mods", default-features = false } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" @@ -78,8 +79,15 @@ default = ["audio", "controllers"] audio = ["dep:cpal"] # Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. controllers = ["dep:gilrs", "dep:horizon-dualsense"] +# Runs code mods (wasmtime and cranelift: a quarter of a clean build). On in every release build +# (release.yml); the tests and probes don't need it. Content mods load without it. +mods = ["horizon-mods/runtime"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] [lints] workspace = true + +[dev-dependencies] +# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests). +naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] } diff --git a/crates/horizon-client/examples/block_facts_bench.rs b/crates/horizon-client/examples/block_facts_bench.rs deleted file mode 100644 index f68dcf999..000000000 --- a/crates/horizon-client/examples/block_facts_bench.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Full production fact loading, including file reads, interning and temporary destruction. -//! cargo run --profile fast -p horizon-client --example block_facts_bench -- ROOT [SAMPLES] -//! Use SAMPLES=1 with an OS peak-RSS wrapper; `digest` checks all facts -//! and the shape sharing partition (including sharing between outlines and edges). -use horizon_client::blocks::BlockFacts; -use horizon_world::{DATA_VERSION, nbt::Tag, registry::BlockRegistry}; -use serde_json::Value; -use std::{ - collections::{HashMap, hash_map::DefaultHasher}, - fs, - hash::{Hash, Hasher}, - hint::black_box, - path::Path, - time::Instant, -}; -type Result = horizon_client::Result; - -fn tag(value: &Value) -> Result { - Ok(match value { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(i32::try_from(n.as_i64().ok_or("registry number")?)?), - Value::Array(a) => Tag::List(a.iter().map(tag).collect::>()?), - Value::Object(o) => Tag::Compound( - o.iter() - .map(|(k, v)| Ok((k.as_str().into(), tag(v)?))) - .collect::>()?, - ), - _ => return Err("registry value".into()), - }) -} -fn registry(root: &Path) -> Result { - let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; - Ok(BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .ok_or("registry states")? - .iter() - .map(|s| tag(&s[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ]))?) -} -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let root = Path::new( - args.first() - .ok_or("usage: block_facts_bench ROOT [SAMPLES|digest]")?, - ); - let setup = Instant::now(); - let registry = registry(root)?; - println!( - "registry_setup_ms={:.3}", - setup.elapsed().as_secs_f64() * 1000.0 - ); - if args.get(1).is_some_and(|s| s == "digest") { - let facts = BlockFacts::load(root, ®istry)?; - let mut hash = DefaultHasher::new(); - let mut shapes = HashMap::new(); - facts.air.hash(&mut hash); - for state in &facts.states { - format!("{state:?}").hash(&mut hash); - for shape in [&state.outline, &state.outline_edges] { - let next = shapes.len(); - shapes - .entry((shape.as_ptr(), shape.len())) - .or_insert(next) - .hash(&mut hash); - } - } - println!( - "states={} shared_shapes={} digest={:016x}", - facts.states.len(), - shapes.len(), - hash.finish() - ); - return Ok(()); - } - let samples: usize = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(samples > 0); - // First load is reported separately; OS file caches are not forcibly evicted. - let load = || -> Result { - let start = Instant::now(); - let facts = black_box(BlockFacts::load(black_box(root), black_box(®istry))?); - let ms = start.elapsed().as_secs_f64() * 1000.0; - drop(facts); - Ok(ms) - }; - println!("first_load_ms={:.3}", load()?); - if samples > 1 { - load()?; - load()?; - let mut times = (0..samples).map(|_| load()).collect::>>()?; - println!("samples_ms={times:.3?}"); - times.sort_by(f64::total_cmp); - println!("median_ms={:.3}", times[times.len() / 2]); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs deleted file mode 100644 index be619245f..000000000 --- a/crates/horizon-client/examples/chunk_bench.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Resident chunk storage benchmark: generates a block of vanilla terrain, then -//! reports the resident block/biome memory, the cost of lookups, meshing and -//! lighting on it. -//! -//! chunk_bench [--seed S] [--size N] -#![forbid(unsafe_code)] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - mesher::{MeshTables, Mesher}, - models, - streaming::{ChunkGenerator, Proto}, - vanillagen::VanillaTerrain, -}; -use horizon_core::biome::BiomeZoom; -use std::{path::PathBuf, sync::Arc, time::Instant}; -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?); - let flag = |name: &str, default: i64| -> i64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); - let assets = Assets::load(&root)?; - let render = assets.reload(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?; - let light = LightTables::load(&root, assets.registry, &facts)?; - let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?; - let mut worker = terrain.worker(); - - // Protos for size+4 columns, decorated for the inner size+2, finished as size+2. - let started = Instant::now(); - let outer = size + 4; - let mut protos: Vec> = (0..outer * outer) - .map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer))) - .collect(); - eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let inner = size + 2; - for z in 1..=inner { - for x in 1..=inner { - let mut region: [Proto; 9] = std::array::from_fn(|k| { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] - .take() - .expect("proto") - }); - terrain.decorate(&mut worker, &mut region); - for (k, p) in region.into_iter().enumerate() { - let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1); - protos[((z + dz) * outer + x + dx) as usize] = Some(p); - } - } - } - eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64()); - let started = Instant::now(); - let mut chunks: Vec = Vec::new(); - for z in 1..=inner { - for x in 1..=inner { - let proto = protos[(z * outer + x) as usize].take().expect("proto"); - let mut chunk = terrain.finish(proto); - chunk.x = x; - chunk.z = z; - chunks.push(chunk); - } - } - let finish = started.elapsed().as_secs_f64(); - println!( - "finish (proto -> resident chunk): {:.1} ms per chunk", - finish * 1e3 / chunks.len() as f64 - ); - - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Light all inner-inner columns. - let started = Instant::now(); - let mut lit = Vec::new(); - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - lit.push(((x, z), light_chunk(&borrowed, &light, true))); - } - } - println!( - "light: {:.2} ms per column", - started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64 - ); - let mut chunks: Vec = chunks.iter().map(|c| (**c).clone()).collect(); - for ((x, z), sections) in lit { - apply_lighting(&mut chunks[((z - 1) * inner + x - 1) as usize], sections); - } - let chunks: Vec> = chunks.into_iter().map(Arc::new).collect(); - let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone(); - - // Memory. - let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize); - for chunk in &chunks { - bytes += chunk.heap_bytes(); - for s in &chunk.sections { - sections += 1; - uniform += usize::from(s.is_uniform(s.get(0))); - } - } - println!( - "resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)", - chunks.len(), - sections, - uniform, - bytes as f64 / 1024.0 / chunks.len() as f64, - bytes as f64 / 1048576.0 - ); - - // Meshing. - let mut mesher = Mesher { - nether_shading: false, - assets: &assets, - render: &render, - tables: &tables, - biomes: &biomes, - visibility: tables.visibility.clone(), - zoom: BiomeZoom::new(7), - blend_radius: 2, - smooth_lighting: true, - cutout_leaves: true, - cull_leaves: false, - }; - let mut best = f64::MAX; - let mut quads = 0usize; - for _ in 0..3 { - let started = Instant::now(); - let mut jobs = 0; - quads = 0; - for z in 2..inner { - for x in 2..inner { - let region: [[Option>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let borrowed = horizon_client::mesher::borrow(®ion); - for sy in 0..SECTIONS as i32 { - let mesh = mesher.mesh(&borrowed, sy); - quads += (mesh.solid.len() + mesh.translucent.len()) / 4; - jobs += 1; - } - } - } - best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs)); - } - println!( - "mesh: {:.1} us per section ({} quads total)", - best * 1e6, - quads - ); - - // Random lookups, as collision and entity queries do. - let mut state = 0x9E37_79B9_7F4A_7C15u64; - let started = Instant::now(); - let mut sum = 0u64; - let lookups = 20_000_000u64; - for _ in 0..lookups { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32; - let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32; - let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize]; - let (x, y, z) = ( - (state >> 16) as i32 & 15, - MIN_Y + ((state >> 24) % 384) as i32, - (state >> 40) as i32 & 15, - ); - sum += u64::from(chunk.get(x, y, z)); - } - println!( - "random get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / lookups as f64 - ); - // Coherent scan, as a column or area query does. - let started = Instant::now(); - let mut sum = 0u64; - for _ in 0..4 { - for chunk in &chunks { - for y in MIN_Y..MIN_Y + 384 { - for z in 0..16 { - for x in 0..16 { - sum += u64::from(chunk.get(x, y, z)); - } - } - } - } - } - println!( - "scan get: {:.2} ns per lookup (checksum {sum})", - started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0) - ); - Ok(()) -} diff --git a/crates/horizon-client/examples/entity_geometry_bench.rs b/crates/horizon-client/examples/entity_geometry_bench.rs deleted file mode 100644 index 57104f58b..000000000 --- a/crates/horizon-client/examples/entity_geometry_bench.rs +++ /dev/null @@ -1,140 +0,0 @@ -//! Isolated production mob-model builder benchmark; no assets, Game, GPU or full-frame work. -//! CARGO_TARGET_DIR=/home/bob/Documents/horizon/target CARGO_INCREMENTAL=0 \ -//! cargo run --profile fast -p horizon-client --example entity_geometry_bench -use horizon_client::{ - mesher::Vertex, - mobs::{Part, Polygon, anim::Poses, render}, -}; -use std::{hint::black_box, time::Instant}; - -fn cube(name: String, position: f32) -> Part { - let polygons = (0..6) - .map(|face| { - let axis = face / 2; - let side = (face % 2) as f32; - let mut normal = [0.0; 3]; - normal[axis] = side * 2.0 - 1.0; - Polygon { - normal, - vertices: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]].map(|uv| { - let mut vertex = [0.0; 5]; - vertex[axis] = side * 8.0; - vertex[(axis + 1) % 3] = uv[0] * 8.0; - vertex[(axis + 2) % 3] = uv[1] * 8.0; - vertex[3] = uv[0]; - vertex[4] = uv[1]; - vertex - }), - } - }) - .collect(); - Part { - name, - pose: [position, 0.0, 0.0, 0.1, 0.2, 0.0, 1.0, 1.0, 1.0], - polygons, - children: Vec::new(), - } -} - -fn build(model: &Part, poses: &Poses, count: usize, out: &mut Vec) { - for i in 0..count { - render::draw( - black_box(model), - glam::Mat4::from_translation(glam::Vec3::new((i % 32) as f32, 0.0, (i / 32) as f32)), - black_box(poses), - [0.125, 0.25, 0.5, 0.75], - 0xffc0_d0e0, - 0xf0f0, - 0, - out, - ); - } - black_box(out.as_slice()); -} - -fn measure(model: &Part, poses: &Poses, count: usize, iterations: usize, reuse: bool) -> f64 { - let mut retained = Vec::new(); - build(model, poses, count, &mut retained); // Untimed warmup. - let start = Instant::now(); - for _ in 0..iterations { - let mut out = if reuse { - std::mem::take(&mut retained) - } else { - Vec::new() - }; - out.clear(); - build(model, poses, count, &mut out); - if reuse { - retained = out; - } - } - start.elapsed().as_secs_f64() * 1e6 / iterations as f64 -} - -fn main() { - let mut model = cube("body".into(), 0.0); - model.children = (1..6).map(|i| cube(format!("part{i}"), i as f32)).collect(); - let poses = Poses::new(&model); - for count in [32, 256, 1024, 4096, 8192] { - let mut expected = Vec::new(); - build(&model, &poses, count, &mut expected); - let mut retained = Vec::new(); - build(&model, &poses, count, &mut retained); - let (pointer, capacity) = (retained.as_ptr(), retained.capacity()); - // Populated -> empty/reset -> smaller -> populated must never leave stale vertices. - for n in [0, count / 2, count, count] { - retained.clear(); - build(&model, &poses, n, &mut retained); - let mut fresh = Vec::new(); - build(&model, &poses, n, &mut fresh); - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&fresh) - ); - assert_eq!( - (retained.as_ptr(), retained.capacity()), - (pointer, capacity) - ); - } - assert_eq!( - bytemuck::cast_slice::(&retained), - bytemuck::cast_slice::(&expected) - ); - let iterations = (100_000 / count).clamp(40, 1000); - let mut fresh = Vec::new(); - let mut reused = Vec::new(); - let mut paired_speedups = Vec::new(); - // Alternate order, reporting medians over eleven warmed batches. - for batch in 0..11 { - let mut pair = [0.0; 2]; - for reuse in if batch % 2 == 0 { - [false, true] - } else { - [true, false] - } { - let time = measure(&model, &poses, count, iterations, reuse); - pair[usize::from(reuse)] = time; - if reuse { - reused.push(time); - } else { - fresh.push(time); - } - } - paired_speedups.push(pair[0] / pair[1]); - } - paired_speedups.sort_by(f64::total_cmp); - fresh.sort_by(f64::total_cmp); - reused.sort_by(f64::total_cmp); - println!( - "entities={count} vertices={} capacity={capacity} retained_bytes={} fresh_us={:.3} reused_us={:.3} speedup={:.3}x paired_speedup_median={:.3}x paired_speedup_range={:.3}..{:.3}x iterations={iterations} batches=11 byte_equivalence=pass pointer_capacity_reuse=pass", - retained.len(), - capacity * size_of::(), - fresh[5], - reused[5], - fresh[5] / reused[5], - paired_speedups[5], - paired_speedups[0], - paired_speedups[10] - ); - } -} diff --git a/crates/horizon-client/examples/json_readers_bench.rs b/crates/horizon-client/examples/json_readers_bench.rs deleted file mode 100644 index a9e370f0a..000000000 --- a/crates/horizon-client/examples/json_readers_bench.rs +++ /dev/null @@ -1,205 +0,0 @@ -//! Compare the exact read/deserialize sequences used by the model loaders. -//! Run with `cargo run -p horizon-client --profile fast --example json_readers_bench`. -//! Optional arguments: resource directory, repetitions (default 9). -use serde_json::{Map, Value, json}; -use std::{ - collections::BTreeMap, - fmt::Debug, - fs::{self, File}, - hint::black_box, - io::BufReader, - path::{Path, PathBuf}, - time::Instant, -}; - -type Result = horizon_client::Result; - -#[derive(Clone, Copy)] -enum Reader { - File, - Buffered, - Slice, -} -const READERS: [Reader; 3] = [Reader::File, Reader::Buffered, Reader::Slice]; - -// These match the map types and reader expressions at all three production sites. -macro_rules! reader { - ($name:ident, $map:ty) => { - fn $name(path: &Path, reader: Reader) -> Result<$map> { - Ok(match reader { - Reader::File => serde_json::from_reader(File::open(path)?)?, - Reader::Buffered => serde_json::from_reader(BufReader::new(File::open(path)?))?, - Reader::Slice => serde_json::from_slice(&fs::read(path)?)?, - }) - } - }; -} -reader!(prepare_facts, Map); -reader!(catalog_facts, BTreeMap); - -struct Fixture(PathBuf); -impl Fixture { - fn new() -> Result { - let root = - std::env::temp_dir().join(format!("horizon-json-readers-{}", std::process::id())); - fs::create_dir(&root)?; - Ok(Self(root)) - } -} -impl Drop for Fixture { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } -} - -fn fixtures(root: &Path) -> Result<()> { - let states: Vec<_> = (0..56) - .map(|i| { - json!({"facing": (["north", "east", "south", "west"][i % 4]), - "powered": if i / 4 % 2 == 0 { "false" } else { "true" }, - "age": (i / 8).to_string()}) - }) - .collect(); - let mut models = Map::new(); - let mut render = Map::new(); - for i in 0..1024 { - let name = format!("minecraft:fixture_block_{i:04}"); - models.insert( - name.clone(), - json!({ - "schema": {"facing": {"named": ["north", "east", "south", "west"]}, - "powered": {"named": ["false", "true"]}, "age": {"integer": [0, 6]}}, - "states": states - }), - ); - render.insert( - name, - json!({"rule": "never", "can_occlude": true, "bars_tag": false}), - ); - } - fs::write(root.join("model-states.json"), serde_json::to_vec(&models)?)?; - fs::write( - root.join("render-definitions.json"), - serde_json::to_vec(&render)?, - )?; - Ok(()) -} - -fn benchmark( - label: &str, - path: &Path, - repetitions: usize, - read: impl Fn(&Path, Reader) -> Result, -) -> Result<()> { - let expected = read(path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, read(path, reader)?); - for _ in 0..2 { - black_box(read(black_box(path), reader)?); - } - } - drop(expected); - let mut samples: [Vec; 3] = std::array::from_fn(|_| Vec::new()); - for repetition in 0..repetitions { - // Rotate reader order to distribute drift across implementations. - for offset in 0..3 { - let index = (repetition + offset) % 3; - let start = Instant::now(); - let value = black_box(read(black_box(path), READERS[index])?); - samples[index].push(start.elapsed().as_secs_f64() * 1000.0); - drop(value); // Match the loaders: retain the parsed tree after loading. - } - } - let median: Vec<_> = samples - .iter_mut() - .map(|s| { - s.sort_by(f64::total_cmp); - s[s.len() / 2] - }) - .collect(); - println!( - "{label}: {} bytes, {repetitions} samples/reader, median ms: File={:.3}, BufReader={:.3}, read+slice={:.3}; slice speedup={:.2}x", - fs::metadata(path)?.len(), - median[0], - median[1], - median[2], - median[0] / median[2] - ); - Ok(()) -} - -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); - let fixture = if args.is_empty() { - Some(Fixture::new()?) - } else { - None - }; - let root = fixture - .as_ref() - .map(|f| f.0.clone()) - .unwrap_or_else(|| PathBuf::from(&args[0])); - if fixture.is_some() { - fixtures(&root)?; - println!( - "Generated representative fixtures: 1024 blocks, 57344 model states; warm filesystem cache." - ); - } - let repetitions = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); - assert!(repetitions > 0, "repetitions must be positive"); - benchmark( - "prepare model states", - &root.join("model-states.json"), - repetitions, - prepare_facts, - )?; - benchmark( - "catalog model states", - &root.join("model-states.json"), - repetitions, - catalog_facts, - )?; - benchmark( - "render definitions", - &root.join("render-definitions.json"), - repetitions, - catalog_facts, - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reader_equivalence_and_errors() -> Result<()> { - let fixture = Fixture::new()?; - let path = fixture.0.join("test.json"); - fs::write(&path, br#"{"minecraft:stone":{"schema":{},"states":[{}]},"unicode":"\u2603","duplicate":1,"duplicate":2}"#)?; - let expected = prepare_facts(&path, Reader::File)?; - for reader in READERS { - assert_eq!(expected, prepare_facts(&path, reader)?); - assert_eq!( - expected.iter().collect::>(), - catalog_facts(&path, reader)?.iter().collect() - ); - } - for invalid in [b"{\"a\": ".as_slice(), b"{} trailing", b"{\"a\":\"\xff\"}"] { - fs::write(&path, invalid)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert!(error.downcast_ref::().is_some()); - assert!(catalog_facts(&path, reader).is_err()); - } - } - fs::remove_file(&path)?; - for reader in READERS { - let error = prepare_facts(&path, reader).unwrap_err(); - assert_eq!( - error.downcast_ref::().unwrap().kind(), - std::io::ErrorKind::NotFound - ); - } - Ok(()) - } -} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs deleted file mode 100644 index 139528612..000000000 --- a/crates/horizon-client/examples/lan_flat.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! Serve a small flat world on the LAN server without the game, for joining -//! with a real client while developing the protocol: -//! `cargo run --release --example lan_flat -- RESOURCES PORT`. -use horizon_client::{ - assets::Assets, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y}, - lan::{ - Lan, - chunks::ChunkEncoder, - data::SyncData, - hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, - }, - world::World, -}; -use horizon_protocol::packets::play::Serverbound as S; -use std::{path::PathBuf, sync::Arc, time::Duration}; - -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); - let root = PathBuf::from(args.next().ok_or("RESOURCES PORT")?); - let port: u16 = args.next().ok_or("port")?.parse()?; - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let state = |name: &str| assets.registry.default_state(name).map_or(0, |s| s.0); - let sync = Arc::new(SyncData::load(&root)?); - let biomes: Vec = sync - .dynamic - .registries - .get("minecraft:worldgen/biome") - .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) - .unwrap_or_default(); - let encoder = ChunkEncoder::new( - facts - .states - .iter() - .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), - &sync.builtin, - &biomes, - &biomes, - ); - let (stone, dirt, grass) = ( - state("minecraft:stone"), - state("minecraft:dirt"), - state("minecraft:grass_block"), - ); - let mut world = World::new(facts.air, 0); - for cz in -8..=8 { - for cx in -8..=8 { - let mut chunk = Chunk::empty(cx, cz); - for z in 0..16 { - for x in 0..16 { - for y in MIN_Y..60 { - let v = if y == 59 { - grass - } else if y > 55 { - dirt - } else { - stone - }; - chunk.set(x, y, z, v); - } - } - } - chunk.lit = true; - world.chunks.insert((cx, cz), Arc::new(chunk)); - } - } - let lan = Lan::start(sync.clone(), port, "Flat - Example".into(), 8)?; - println!("listening on {}", lan.port); - let mut hub = Hub::new( - lan, - sync, - encoder, - HubConfig { - default_game_mode: 1, - guest_commands: true, - force_game_mode: false, - hardcore: false, - view_distance: 8, - simulation_distance: 8, - dimension: "minecraft:overworld".into(), - seed: 0, - max_players: 8, - dedicated: false, - integrated: false, - }, - ); - let mut next_entity = 100u32; - let host = HostState { - uuid: 42, - name: "Host".into(), - entity_id: 1, - position: [0.5, 60.0, 0.5], - yaw: 0.0, - pitch: 0.0, - head_yaw: 0.0, - on_ground: true, - game_mode: 1, - sneaking: false, - sprinting: false, - equipment: Default::default(), - health: 20.0, - attributes: Vec::new(), - bed: None, - living_flags: 0, - }; - loop { - world.game_time += 1; - world.day_time += 1; - let mut ctx = TickCtx { - world: &mut world, - host: Some(&host), - entities: &[], - next_entity: &mut next_entity, - spawn: [8.5, 60.0, 8.5], - difficulty: 2, - difficulty_locked: false, - clock_rate: 1.0, - tick_rate: 20.0, - tick_frozen: false, - tick_steps: (0, 0), - collision: None, - border: &horizon_client::worldborder::WorldBorder::default(), - }; - for event in hub.tick(&mut ctx) { - match event { - HostEvent::Joined(conn) => hub.place_new_player(conn, &mut ctx), - HostEvent::Packet(_, packet) => { - if std::env::var_os("HORIZON_NET_DEBUG").is_some() - && !matches!(*packet, S::ClientTickEnd(_)) - { - eprintln!("[lan] {packet:?}"); - } - } - HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => { - println!("{line}") - } - HostEvent::Left(_) => {} - } - } - std::thread::sleep(Duration::from_millis(50)); - } -} diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs deleted file mode 100644 index 5c30a71ff..000000000 --- a/crates/horizon-client/examples/load_bench.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup. -//! -//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum] -//! Add --profile-worker when a sampling collector cannot sample the main thread. -//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light), -//! plus isolated inflate/NBT and native decode. No files in the save are changed. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, decode_with}, -}; -use horizon_world::{nbt::Limits, region::RegionFile}; -use sha2::{Digest, Sha256}; -use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - if std::env::args().any(|a| a == "--profile-worker") { - std::thread::spawn(|| run().map_err(|e| e.to_string())) - .join() - .expect("benchmark worker") - .map_err(Into::into) - } else { - run() - } -} - -fn run() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let flag = |name: &str, default: usize| -> Result { - Ok(match args.iter().position(|a| a == name) { - Some(i) => args.get(i + 1).ok_or(usage)?.parse()?, - None => default, - }) - }; - let rounds = flag("--rounds", 5)?; - let limit = flag("--limit", 256)?; - if rounds == 0 || limit == 0 { - return Err("rounds and limit must be positive".into()); - } - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))? - .map(|e| e.map(|e| e.path())) - .collect::>()?; - paths.retain(|p| p.extension().is_some_and(|e| e == "mca")); - paths.sort(); - let mut corpus = Vec::new(); - 'regions: for path in paths { - let mut region = RegionFile::open(path)?; - let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect(); - positions.sort_by_key(|p| (p.x, p.z)); - for pos in positions { - let record = region.read(pos)?.ok_or("missing record")?; - let tag = record.nbt(Limits::default())?; - if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() { - continue; - } - corpus.push((pos, record, tag)); - if corpus.len() == limit { - break 'regions; - } - } - } - if corpus.is_empty() { - return Err("no full chunks in corpus".into()); - } - let mut records_hash = Sha256::new(); - for (pos, record, _) in &corpus { - records_hash.update(pos.x.to_le_bytes()); - records_hash.update(pos.z.to_le_bytes()); - records_hash.update((record.compressed.len() as u64).to_le_bytes()); - records_hash.update(&record.compressed); - } - println!( - "{}", - serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds, - "compressed_records_sha256": format!("{:x}", records_hash.finalize()), - "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()}) - ); - // Prime SaveDir's region handles and the filesystem cache before measurement. - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - for round in 0..rounds { - let started = Instant::now(); - for (pos, _, _) in &corpus { - black_box( - source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?, - ); - } - let load_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, record, _) in &corpus { - black_box(record.nbt(Limits::default())?); - } - let nbt_s = started.elapsed().as_secs_f64(); - let started = Instant::now(); - for (_, _, tag) in &corpus { - black_box( - decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?, - ); - } - let decode_s = started.elapsed().as_secs_f64(); - println!( - "{}", - serde_json::json!({"round": round, "load_s": load_s, - "inflate_nbt_s": nbt_s, "decode_s": decode_s}) - ); - } - if args.iter().any(|a| a == "--checksum") { - let mut hash = Sha256::new(); - let mut light_loaded = 0; - for (pos, _, _) in &corpus { - let chunk = source - .load(pos.x, pos.z, assets.registry, &biomes) - .ok_or("load failed")?; - hash.update(pos.x.to_le_bytes()); - hash.update(pos.z.to_le_bytes()); - light_loaded += usize::from(chunk.light_loaded); - for section in &chunk.sections { - for i in 0..4096 { - hash.update(section.get(i).to_le_bytes()); - hash.update([section.light(i)]); - } - for i in 0..64 { - hash.update(section.biomes.get(i).to_le_bytes()); - } - } - } - println!( - "{}", - serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()), - "light_loaded": light_loaded}) - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/ambient_fixture.rs b/crates/horizon-client/examples/probe/ambient_fixture.rs similarity index 98% rename from crates/horizon-client/examples/ambient_fixture.rs rename to crates/horizon-client/examples/probe/ambient_fixture.rs index d75a1b568..3fd507902 100644 --- a/crates/horizon-client/examples/ambient_fixture.rs +++ b/crates/horizon-client/examples/probe/ambient_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_ambient_sound_parity.py` scripts through Horizon's //! ambient sound handlers over its `SoundEngine`: //! `ambient_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, f, flush}; use horizon_client::ambience::{Ambience, AmbientContext, AmbientSounds, Mood, bubble_column_in}; use horizon_client::sound_engine::{Bound, SoundEngine, TickContext, Ticking}; @@ -47,8 +46,8 @@ fn sounds(a: &[&str]) -> AmbientSounds { } } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/probe/arrow_probe.rs similarity index 99% rename from crates/horizon-client/examples/arrow_probe.rs rename to crates/horizon-client/examples/probe/arrow_probe.rs index 63ff2df32..f72e6276e 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/probe/arrow_probe.rs @@ -50,8 +50,8 @@ fn particle(k: ArrowParticle) -> &'static str { ArrowParticle::Splash => "splash", } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into()); } diff --git a/crates/horizon-client/examples/audio_attributes_fixture.rs b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs similarity index 97% rename from crates/horizon-client/examples/audio_attributes_fixture.rs rename to crates/horizon-client/examples/probe/audio_attributes_fixture.rs index 73f463fc4..4bbb3a239 100644 --- a/crates/horizon-client/examples/audio_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/audio_attributes_fixture.rs @@ -18,8 +18,8 @@ fn music(m: Option<&Music>) -> String { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let root = std::path::Path::new(&args[1]); let tables = MusicTables::load(root); let ambient = AmbientTables::load(root); diff --git a/crates/horizon-client/examples/audio_common/mod.rs b/crates/horizon-client/examples/probe/audio_common/mod.rs similarity index 100% rename from crates/horizon-client/examples/audio_common/mod.rs rename to crates/horizon-client/examples/probe/audio_common/mod.rs diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/probe/auto_jump_probe.rs similarity index 98% rename from crates/horizon-client/examples/auto_jump_probe.rs rename to crates/horizon-client/examples/probe/auto_jump_probe.rs index d8dee95df..c15565850 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/probe/auto_jump_probe.rs @@ -24,8 +24,8 @@ fn db(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let [root, input, output, scene_json] = &args[..] else { return Err("usage: auto_jump_probe RESOURCES INPUT OUTPUT SCENE_JSON".into()); }; diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_anim_fixture.rs index e108c53b3..3a3a0ef14 100644 --- a/crates/horizon-client/examples/block_entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_anim_fixture.rs @@ -118,8 +118,8 @@ fn status(s: ShulkerStatus) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/block_entity_render_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_render_fixture.rs index d844c4e44..a0e3471bc 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs @@ -110,8 +110,8 @@ fn intern(s: &str) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, textures, output] = args.as_slice() else { return Err("usage: block_entity_render_fixture RESOURCES INPUTS TEXTURES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/block_entity_tickers_fixture.rs b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs similarity index 98% rename from crates/horizon-client/examples/block_entity_tickers_fixture.rs rename to crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs index f08c333f6..d375f1b74 100644 --- a/crates/horizon-client/examples/block_entity_tickers_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_tickers_fixture.rs @@ -26,8 +26,8 @@ fn entity(name: &str) -> BlockEntity { .unwrap_or_else(|| panic!("no block entity for {name}")) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut entities = BlockEntities::default(); diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/probe/block_particles_fixture.rs similarity index 95% rename from crates/horizon-client/examples/block_particles_fixture.rs rename to crates/horizon-client/examples/probe/block_particles_fixture.rs index 63ef242b7..0e58d99ea 100644 --- a/crates/horizon-client/examples/block_particles_fixture.rs +++ b/crates/horizon-client/examples/probe/block_particles_fixture.rs @@ -8,8 +8,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/block_transform_fixture.rs b/crates/horizon-client/examples/probe/block_transform_fixture.rs similarity index 96% rename from crates/horizon-client/examples/block_transform_fixture.rs rename to crates/horizon-client/examples/probe/block_transform_fixture.rs index 01d92a047..9d8d1d7db 100644 --- a/crates/horizon-client/examples/block_transform_fixture.rs +++ b/crates/horizon-client/examples/probe/block_transform_fixture.rs @@ -51,8 +51,8 @@ impl Around for Column { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/probe/breaking_fixture.rs similarity index 96% rename from crates/horizon-client/examples/breaking_fixture.rs rename to crates/horizon-client/examples/probe/breaking_fixture.rs index da696b88e..c5a816ccd 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/probe/breaking_fixture.rs @@ -16,8 +16,8 @@ use std::{ }; /// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). const STAGE: [f32; 2] = [0.25, 0.5]; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; let render = assets.reload(root)?; diff --git a/crates/horizon-client/examples/camera_probe.rs b/crates/horizon-client/examples/probe/camera_probe.rs similarity index 99% rename from crates/horizon-client/examples/camera_probe.rs rename to crates/horizon-client/examples/probe/camera_probe.rs index 2d7f716f0..38f3c23be 100644 --- a/crates/horizon-client/examples/camera_probe.rs +++ b/crates/horizon-client/examples/probe/camera_probe.rs @@ -323,8 +323,8 @@ fn avatar(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/probe/cauldron_fixture.rs similarity index 98% rename from crates/horizon-client/examples/cauldron_fixture.rs rename to crates/horizon-client/examples/probe/cauldron_fixture.rs index 6aa942d42..95b075d70 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/probe/cauldron_fixture.rs @@ -70,8 +70,8 @@ fn describe(state: &BlockState) -> String { format!("{}|{}", state.name, props.join(",")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/chat_screen_fixture.rs b/crates/horizon-client/examples/probe/chat_screen_fixture.rs similarity index 95% rename from crates/horizon-client/examples/chat_screen_fixture.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture.rs index c5cba6b9d..229d8d861 100644 --- a/crates/horizon-client/examples/chat_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/chat_screen_fixture.rs @@ -5,6 +5,7 @@ //! the oracle's JSON form. //! //! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT +use crate::pack_screen_fixture; use horizon_client::{ chat::{ChatAction, ChatScreen, Commands}, command::vanilla, @@ -15,14 +16,11 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fmt::Write as _, fs, path::PathBuf}; use winit::keyboard::KeyCode as K; -#[path = "pack_screen_fixture.rs"] -#[allow(dead_code)] -mod pack_screen_fixture; #[path = "chat_screen_fixture/registries.rs"] mod registries; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, registries, inputs, output] = args.as_slice() else { return Err("usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/chat_screen_fixture/registries.rs b/crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs similarity index 100% rename from crates/horizon-client/examples/chat_screen_fixture/registries.rs rename to crates/horizon-client/examples/probe/chat_screen_fixture/registries.rs diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/probe/cloud_fixture.rs similarity index 92% rename from crates/horizon-client/examples/cloud_fixture.rs rename to crates/horizon-client/examples/probe/cloud_fixture.rs index 7c00bfb3a..4ba072dbb 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/probe/cloud_fixture.rs @@ -1,8 +1,8 @@ //! CloudRenderer face selection and mesh traversal, without a GPU. use horizon_client::clouds; use std::{fmt::Write, fs}; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let values: Vec = line diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/probe/command_parse_fixture.rs similarity index 99% rename from crates/horizon-client/examples/command_parse_fixture.rs rename to crates/horizon-client/examples/probe/command_parse_fixture.rs index 1cc1f95d5..17437cd72 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/probe/command_parse_fixture.rs @@ -132,8 +132,8 @@ fn tree(d: &Dispatcher, node: usize) -> Value { v } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); if args.get(1).map(String::as_str) == Some("tree") { let d = &vanilla::registered(false); let mut v = tree(d, 0); diff --git a/crates/horizon-client/examples/container_screen_probe.rs b/crates/horizon-client/examples/probe/container_screen_probe.rs similarity index 97% rename from crates/horizon-client/examples/container_screen_probe.rs rename to crates/horizon-client/examples/probe/container_screen_probe.rs index b89b23a2a..e82b5bdf5 100644 --- a/crates/horizon-client/examples/container_screen_probe.rs +++ b/crates/horizon-client/examples/probe/container_screen_probe.rs @@ -24,8 +24,8 @@ fn input_name(input: Input) -> &'static str { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/creative_search_fixture.rs b/crates/horizon-client/examples/probe/creative_search_fixture.rs similarity index 95% rename from crates/horizon-client/examples/creative_search_fixture.rs rename to crates/horizon-client/examples/probe/creative_search_fixture.rs index 628e0486d..1f4f04b37 100644 --- a/crates/horizon-client/examples/creative_search_fixture.rs +++ b/crates/horizon-client/examples/probe/creative_search_fixture.rs @@ -11,8 +11,8 @@ use horizon_client::{ use serde_json::{Value, json}; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: creative_search_fixture RESOURCES CREATIVE_JSON VANILLA_JSON OUTPUT"; let names = Names::load(Path::new(args.get(1).ok_or(usage)?)); let creative = Creative::from_json(&serde_json::from_slice(&fs::read( diff --git a/crates/horizon-client/examples/probe/dispatch.rs b/crates/horizon-client/examples/probe/dispatch.rs new file mode 100644 index 000000000..b40cf1a6e --- /dev/null +++ b/crates/horizon-client/examples/probe/dispatch.rs @@ -0,0 +1,49 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +/// args(), as OsStrings. +pub fn args_os() -> std::vec::IntoIter { + let mut args: Vec<_> = std::env::args_os().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-client/examples/emitter_particles_probe.rs b/crates/horizon-client/examples/probe/emitter_particles_probe.rs similarity index 96% rename from crates/horizon-client/examples/emitter_particles_probe.rs rename to crates/horizon-client/examples/probe/emitter_particles_probe.rs index 7469bb368..6349eb8dc 100644 --- a/crates/horizon-client/examples/emitter_particles_probe.rs +++ b/crates/horizon-client/examples/probe/emitter_particles_probe.rs @@ -14,8 +14,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/enchanting_fixture.rs b/crates/horizon-client/examples/probe/enchanting_fixture.rs similarity index 94% rename from crates/horizon-client/examples/enchanting_fixture.rs rename to crates/horizon-client/examples/probe/enchanting_fixture.rs index 736b9189e..4c0fe6350 100644 --- a/crates/horizon-client/examples/enchanting_fixture.rs +++ b/crates/horizon-client/examples/probe/enchanting_fixture.rs @@ -10,8 +10,8 @@ use horizon_client::{ }; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: enchanting_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_anim_fixture.rs rename to crates/horizon-client/examples/probe/entity_anim_fixture.rs index e5a146ef9..0a2e2951f 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -3,7 +3,7 @@ //! posed model with `mobs::render::draw` under the case's living-entity root //! transform and writes each drawn part's packed vertex normals. //! -//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ +//! cargo run --profile fast -p horizon-client --example probe -- entity_anim_fixture \ //! RESOURCES VANILLA.jsonl OUT.jsonl use horizon_client::mesher::Vertex; use horizon_client::mobs::{ @@ -288,8 +288,8 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from(&args[0]); let types = MobTypes::load(&root)?; let animations = MobData::load_animations(&root); diff --git a/crates/horizon-client/examples/entity_components_probe.rs b/crates/horizon-client/examples/probe/entity_components_probe.rs similarity index 96% rename from crates/horizon-client/examples/entity_components_probe.rs rename to crates/horizon-client/examples/probe/entity_components_probe.rs index 0d4a51e8c..2b1c3233f 100644 --- a/crates/horizon-client/examples/entity_components_probe.rs +++ b/crates/horizon-client/examples/probe/entity_components_probe.rs @@ -61,8 +61,8 @@ fn species(id: &str) -> Species { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs similarity index 99% rename from crates/horizon-client/examples/entity_death_loot_fixture.rs rename to crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index a8eceb8ca..86ef275d9 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -53,8 +53,8 @@ fn line(s: &LootStack) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: entity_death_loot_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/entity_particles_probe.rs b/crates/horizon-client/examples/probe/entity_particles_probe.rs similarity index 95% rename from crates/horizon-client/examples/entity_particles_probe.rs rename to crates/horizon-client/examples/probe/entity_particles_probe.rs index ef38f1000..cdb0344df 100644 --- a/crates/horizon-client/examples/entity_particles_probe.rs +++ b/crates/horizon-client/examples/probe/entity_particles_probe.rs @@ -13,8 +13,8 @@ fn d(v: f64) -> String { format!("{:016x}", v.to_bits()) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/probe/environment_fixture.rs similarity index 97% rename from crates/horizon-client/examples/environment_fixture.rs rename to crates/horizon-client/examples/probe/environment_fixture.rs index 7f331962a..27846fe82 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/probe/environment_fixture.rs @@ -9,8 +9,8 @@ use horizon_client::{ }; use std::{collections::HashMap, fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/finalize_spawn_fixture.rs rename to crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index 9b1ba4f38..b1b25e723 100644 --- a/crates/horizon-client/examples/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -388,8 +388,8 @@ fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String { t.join(" ") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?, diff --git a/crates/horizon-client/examples/fire_starter_sound_probe.rs b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs similarity index 91% rename from crates/horizon-client/examples/fire_starter_sound_probe.rs rename to crates/horizon-client/examples/probe/fire_starter_sound_probe.rs index 62fab117a..18c1b487a 100644 --- a/crates/horizon-client/examples/fire_starter_sound_probe.rs +++ b/crates/horizon-client/examples/probe/fire_starter_sound_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs similarity index 92% rename from crates/horizon-client/examples/firework_tooltip_fixture.rs rename to crates/horizon-client/examples/probe/firework_tooltip_fixture.rs index 7f10278b7..385776837 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/probe/firework_tooltip_fixture.rs @@ -4,8 +4,8 @@ use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/first_person_probe.rs b/crates/horizon-client/examples/probe/first_person_probe.rs similarity index 99% rename from crates/horizon-client/examples/first_person_probe.rs rename to crates/horizon-client/examples/probe/first_person_probe.rs index 7b1143114..cb4c38e58 100644 --- a/crates/horizon-client/examples/first_person_probe.rs +++ b/crates/horizon-client/examples/probe/first_person_probe.rs @@ -458,8 +458,8 @@ impl HandWorld for ResetWorld<'_, '_> { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/probe/frame_limiter_probe.rs similarity index 97% rename from crates/horizon-client/examples/frame_limiter_probe.rs rename to crates/horizon-client/examples/probe/frame_limiter_probe.rs index 7a5d4e437..b11338afc 100644 --- a/crates/horizon-client/examples/frame_limiter_probe.rs +++ b/crates/horizon-client/examples/probe/frame_limiter_probe.rs @@ -50,8 +50,8 @@ impl LimiterClock for Script { } } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/probe/game_loop_probe.rs similarity index 99% rename from crates/horizon-client/examples/game_loop_probe.rs rename to crates/horizon-client/examples/probe/game_loop_probe.rs index 66a428162..598f480e6 100644 --- a/crates/horizon-client/examples/game_loop_probe.rs +++ b/crates/horizon-client/examples/probe/game_loop_probe.rs @@ -291,8 +291,8 @@ fn key(c: &Value, out: &mut impl Write) -> Result<()> { Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let c: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/ghost_recipe_fixture.rs b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs similarity index 96% rename from crates/horizon-client/examples/ghost_recipe_fixture.rs rename to crates/horizon-client/examples/probe/ghost_recipe_fixture.rs index 0860fd409..b8c6553be 100644 --- a/crates/horizon-client/examples/ghost_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/ghost_recipe_fixture.rs @@ -13,8 +13,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: ghost_recipe_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/probe/held_drop_fixture.rs similarity index 98% rename from crates/horizon-client/examples/held_drop_fixture.rs rename to crates/horizon-client/examples/probe/held_drop_fixture.rs index a0c5d92ba..1275021bb 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/probe/held_drop_fixture.rs @@ -2,7 +2,7 @@ use horizon_client::command::args::GameMode; use horizon_client::items::{ItemStack, take_held_drop}; -fn main() { +pub fn main() { for mode in [ GameMode::Survival, GameMode::Creative, diff --git a/crates/horizon-client/examples/hotbar_fixture.rs b/crates/horizon-client/examples/probe/hotbar_fixture.rs similarity index 94% rename from crates/horizon-client/examples/hotbar_fixture.rs rename to crates/horizon-client/examples/probe/hotbar_fixture.rs index beac564ec..4c89a919f 100644 --- a/crates/horizon-client/examples/hotbar_fixture.rs +++ b/crates/horizon-client/examples/probe/hotbar_fixture.rs @@ -10,8 +10,8 @@ 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(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::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(); diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs similarity index 98% rename from crates/horizon-client/examples/hud_fixture.rs rename to crates/horizon-client/examples/probe/hud_fixture.rs index 4a4c78869..a6f27fcda 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -20,8 +20,8 @@ type Result = std::result::Result>; #[path = "hud_fixture/kinds.rs"] mod kinds; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs similarity index 99% rename from crates/horizon-client/examples/hud_fixture/kinds.rs rename to crates/horizon-client/examples/probe/hud_fixture/kinds.rs index 850db5218..d1450f2e1 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs @@ -306,6 +306,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { height_focused: option("chatHeightFocused"), height_unfocused: option("chatHeightUnfocused"), line_spacing: option("chatLineSpacing"), + colors: c["chatColors"].as_bool().unwrap_or(true), }; for m in c["messages"].as_array().into_iter().flatten() { // GuiMessageTag indicator colours: systemSinglePlayer and chatError. diff --git a/crates/horizon-client/examples/input_probe.rs b/crates/horizon-client/examples/probe/input_probe.rs similarity index 94% rename from crates/horizon-client/examples/input_probe.rs rename to crates/horizon-client/examples/probe/input_probe.rs index b628bce5d..ae66f77a6 100644 --- a/crates/horizon-client/examples/input_probe.rs +++ b/crates/horizon-client/examples/probe/input_probe.rs @@ -11,8 +11,8 @@ fn number(v: &Value) -> f32 { fn bits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/interaction_input_fixture.rs b/crates/horizon-client/examples/probe/interaction_input_fixture.rs similarity index 96% rename from crates/horizon-client/examples/interaction_input_fixture.rs rename to crates/horizon-client/examples/probe/interaction_input_fixture.rs index bb408dd88..a6beffc05 100644 --- a/crates/horizon-client/examples/interaction_input_fixture.rs +++ b/crates/horizon-client/examples/probe/interaction_input_fixture.rs @@ -82,8 +82,8 @@ impl TargetUseWorld for World { } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for (i, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/lan_probe.rs b/crates/horizon-client/examples/probe/lan_probe.rs similarity index 96% rename from crates/horizon-client/examples/lan_probe.rs rename to crates/horizon-client/examples/probe/lan_probe.rs index 43ce51f9d..3be556e3b 100644 --- a/crates/horizon-client/examples/lan_probe.rs +++ b/crates/horizon-client/examples/probe/lan_probe.rs @@ -14,8 +14,8 @@ fn unhex(s: &str) -> Vec { .collect() } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let cases = std::fs::read_to_string(&args[1]).unwrap(); let mut out = String::new(); let mut games: Vec = Vec::new(); diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/probe/light_parity.rs similarity index 98% rename from crates/horizon-client/examples/light_parity.rs rename to crates/horizon-client/examples/probe/light_parity.rs index f660189a2..41c2ba784 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/probe/light_parity.rs @@ -2,7 +2,7 @@ //! server with Horizon's light engine and compare every SkyLight/BlockLight //! value with the arrays vanilla stored. //! -//! cargo run --profile fast -p horizon-client --example light_parity -- \ +//! cargo run --profile fast -p horizon-client --example probe -- light_parity \ //! RESOURCES DIMENSION_DIR [--nether] [--chunks X0 Z0 X1 Z1] use horizon_client::{ assets::Assets, @@ -21,8 +21,8 @@ use std::{collections::HashMap, path::PathBuf}; type Arrays = HashMap>, Option>)>; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let root = PathBuf::from( args.first() .ok_or("usage: light_parity RESOURCES DIMENSION_DIR")?, diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs new file mode 100644 index 000000000..d110ea790 --- /dev/null +++ b/crates/horizon-client/examples/probe/main.rs @@ -0,0 +1,178 @@ +//! Every horizon-client parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py, tools/oracle_harness.py, tools/audio_harness.py). Linking ~80 examples, +//! each with the whole client in it, was most of the parity job's probe build; one binary builds it once. +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::{args, args_os}; + +mod ambient_fixture; +mod arrow_probe; +mod audio_attributes_fixture; +/// Sound-engine fakes the audio probes share. +mod audio_common; +mod auto_jump_probe; +mod block_entity_anim_fixture; +mod block_entity_render_fixture; +mod block_entity_tickers_fixture; +mod block_particles_fixture; +mod block_transform_fixture; +mod breaking_fixture; +mod camera_probe; +mod cauldron_fixture; +mod chat_screen_fixture; +mod cloud_fixture; +mod command_parse_fixture; +mod container_screen_probe; +mod creative_search_fixture; +mod emitter_particles_probe; +mod enchanting_fixture; +mod entity_anim_fixture; +mod entity_components_probe; +mod entity_death_loot_fixture; +mod entity_particles_probe; +mod environment_fixture; +mod finalize_spawn_fixture; +mod fire_starter_sound_probe; +mod firework_tooltip_fixture; +mod first_person_probe; +mod frame_limiter_probe; +mod game_loop_probe; +mod ghost_recipe_fixture; +mod held_drop_fixture; +mod hotbar_fixture; +mod hud_fixture; +mod input_probe; +mod interaction_input_fixture; +mod lan_probe; +mod light_parity; +mod marker_particles_probe; +mod menu_fixture; +mod mipmap_probe; +mod mob_ai_probe; +mod mob_attributes_fixture; +mod music_fixture; +mod natural_spawn_fixture; +mod options_probe; +mod pack_resources_fixture; +mod pack_screen_fixture; +mod pack_selection_fixture; +mod particle_providers_probe; +mod pick_block_data_fixture; +mod place_recipe_fixture; +mod player_sync_fixture; +mod raid_fixture; +mod random_tick_sections_probe; +mod recipe_book_fixture; +mod recipe_book_render_fixture; +mod recipe_book_view_fixture; +mod recipe_fixture; +mod scene_collision_probe; +mod scene_motion_probe; +mod scoreboard_fixture; +mod screen_layout_fixture; +mod section_mesh_fixture; +mod server_files_probe; +mod situational_music_fixture; +mod skin_image_fixture; +mod sound_engine_fixture; +mod sound_event_fixture; +mod spawn_rules_fixture; +mod sprint_probe; +mod subtitle_fixture; +mod tab_list_fixture; +mod team_rules_fixture; +mod toggle_keys_probe; +mod tooltip_display_fixture; +mod trading_fixture; +mod translucency_fixture; +mod weather_fixture; +mod world_border_render_fixture; +mod world_options_fixture; + +probes! { + ambient_fixture, + arrow_probe, + audio_attributes_fixture, + auto_jump_probe, + block_entity_anim_fixture, + block_entity_render_fixture, + block_entity_tickers_fixture, + block_particles_fixture, + block_transform_fixture, + breaking_fixture, + camera_probe, + cauldron_fixture, + chat_screen_fixture, + cloud_fixture, + command_parse_fixture, + container_screen_probe, + creative_search_fixture, + emitter_particles_probe, + enchanting_fixture, + entity_anim_fixture, + entity_components_probe, + entity_death_loot_fixture, + entity_particles_probe, + environment_fixture, + finalize_spawn_fixture, + fire_starter_sound_probe, + firework_tooltip_fixture, + first_person_probe, + frame_limiter_probe, + game_loop_probe, + ghost_recipe_fixture, + held_drop_fixture, + hotbar_fixture, + hud_fixture, + input_probe, + interaction_input_fixture, + lan_probe, + light_parity, + marker_particles_probe, + menu_fixture, + mipmap_probe, + mob_ai_probe, + mob_attributes_fixture, + music_fixture, + natural_spawn_fixture, + options_probe, + pack_resources_fixture, + pack_screen_fixture, + pack_selection_fixture, + particle_providers_probe, + pick_block_data_fixture, + place_recipe_fixture, + player_sync_fixture, + raid_fixture, + random_tick_sections_probe, + recipe_book_fixture, + recipe_book_render_fixture, + recipe_book_view_fixture, + recipe_fixture, + scene_collision_probe, + scene_motion_probe, + scoreboard_fixture, + screen_layout_fixture, + section_mesh_fixture, + server_files_probe, + situational_music_fixture, + skin_image_fixture, + sound_engine_fixture, + sound_event_fixture, + spawn_rules_fixture, + sprint_probe, + subtitle_fixture, + tab_list_fixture, + team_rules_fixture, + toggle_keys_probe, + tooltip_display_fixture, + trading_fixture, + translucency_fixture, + weather_fixture, + world_border_render_fixture, + world_options_fixture, +} diff --git a/crates/horizon-client/examples/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs similarity index 97% rename from crates/horizon-client/examples/marker_particles_probe.rs rename to crates/horizon-client/examples/probe/marker_particles_probe.rs index edf624e73..190751d79 100644 --- a/crates/horizon-client/examples/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -22,8 +22,8 @@ use std::{ sync::Arc, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new(".local/horizon-client/26.3"); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/probe/menu_fixture.rs similarity index 97% rename from crates/horizon-client/examples/menu_fixture.rs rename to crates/horizon-client/examples/probe/menu_fixture.rs index 1da4a0278..3c83b20bc 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/probe/menu_fixture.rs @@ -58,11 +58,12 @@ fn state(menu: &Menu) -> String { .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); let line = format!( - "{} | {} |{data} | {} | {}", + "{} | {} |{data} | {} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), - equipped.join(";") + equipped.join(";"), + menu.player_sounds.join(";") ); if menu.kind() != Kind::Lectern { return line; @@ -74,8 +75,8 @@ fn state(menu: &Menu) -> String { format!("{line} | inv{items}") } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?, @@ -171,6 +172,7 @@ fn main() -> horizon_client::Result<()> { }); menu.drops.clear(); menu.equipped.clear(); + menu.player_sounds.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; diff --git a/crates/horizon-client/examples/mipmap_probe.rs b/crates/horizon-client/examples/probe/mipmap_probe.rs similarity index 94% rename from crates/horizon-client/examples/mipmap_probe.rs rename to crates/horizon-client/examples/probe/mipmap_probe.rs index 99155fb32..fa94f4e90 100644 --- a/crates/horizon-client/examples/mipmap_probe.rs +++ b/crates/horizon-client/examples/probe/mipmap_probe.rs @@ -4,8 +4,8 @@ //! rows like VanillaMipmapOracle. use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); let input = fs::read_to_string(&args[0])?; let mut lines = input.lines(); let root = Path::new(lines.next().ok_or("no resources root")?); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs similarity index 99% rename from crates/horizon-client/examples/mob_ai_probe.rs rename to crates/horizon-client/examples/probe/mob_ai_probe.rs index a3abb54d9..d773a509b 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -759,8 +759,8 @@ fn villager(m: &Mob) -> String { s } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT".into()); } diff --git a/crates/horizon-client/examples/mob_attributes_fixture.rs b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs similarity index 95% rename from crates/horizon-client/examples/mob_attributes_fixture.rs rename to crates/horizon-client/examples/probe/mob_attributes_fixture.rs index 7f8359920..f1fcec701 100644 --- a/crates/horizon-client/examples/mob_attributes_fixture.rs +++ b/crates/horizon-client/examples/probe/mob_attributes_fixture.rs @@ -6,8 +6,8 @@ use horizon_client::mobs::{Mob, MobTypes}; use horizon_core::geometry::Vec3; use std::{fmt::Write as _, fs, path::Path, sync::Arc}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: mob_attributes_fixture RESOURCES OUTPUT")?, diff --git a/crates/horizon-client/examples/music_fixture.rs b/crates/horizon-client/examples/probe/music_fixture.rs similarity index 97% rename from crates/horizon-client/examples/music_fixture.rs rename to crates/horizon-client/examples/probe/music_fixture.rs index 29ccb99b2..02aecb373 100644 --- a/crates/horizon-client/examples/music_fixture.rs +++ b/crates/horizon-client/examples/probe/music_fixture.rs @@ -1,7 +1,6 @@ //! Replays `tools/test_music_parity.py` scripts through Horizon's //! `MusicManager` over its `SoundEngine`: `music_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, describe, f, flush}; use horizon_client::music::{Music, MusicFrequency, MusicManager}; use horizon_client::sound_engine::{Bound, MUSIC, SoundEngine, TickContext}; @@ -21,8 +20,8 @@ fn music(spec: &str) -> Option { )) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs similarity index 99% rename from crates/horizon-client/examples/natural_spawn_fixture.rs rename to crates/horizon-client/examples/probe/natural_spawn_fixture.rs index e4c9b1ce6..c19adc4e1 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/natural_spawn_fixture.rs @@ -508,8 +508,8 @@ fn yaw_text(entity: &str, v: f32) -> String { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: natural_spawn_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/options_probe.rs b/crates/horizon-client/examples/probe/options_probe.rs similarity index 94% rename from crates/horizon-client/examples/options_probe.rs rename to crates/horizon-client/examples/probe/options_probe.rs index f186af994..97c76c030 100644 --- a/crates/horizon-client/examples/options_probe.rs +++ b/crates/horizon-client/examples/probe/options_probe.rs @@ -7,8 +7,8 @@ use horizon_client::{ }; use std::{fs, io::Write}; -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut names: Vec<_> = fs::read_dir(&args[0])? .map(|e| e.map(|e| e.path())) .collect::>()?; diff --git a/crates/horizon-client/examples/pack_resources_fixture.rs b/crates/horizon-client/examples/probe/pack_resources_fixture.rs similarity index 97% rename from crates/horizon-client/examples/pack_resources_fixture.rs rename to crates/horizon-client/examples/probe/pack_resources_fixture.rs index 00238fa94..80dbf3496 100644 --- a/crates/horizon-client/examples/pack_resources_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_resources_fixture.rs @@ -30,8 +30,8 @@ fn types(root: &std::path::Path, file: PathBuf, key: &str) -> String { }) .collect() } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = fs::read_to_string(&args[1])?; let mut lines = input.lines(); let root: Vec<&str> = lines.next().ok_or("empty input")?.split(' ').collect(); diff --git a/crates/horizon-client/examples/pack_screen_fixture.rs b/crates/horizon-client/examples/probe/pack_screen_fixture.rs similarity index 98% rename from crates/horizon-client/examples/pack_screen_fixture.rs rename to crates/horizon-client/examples/probe/pack_screen_fixture.rs index ca7cba7b8..881570990 100644 --- a/crates/horizon-client/examples/pack_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_screen_fixture.rs @@ -66,8 +66,8 @@ pub fn encode(draws: &[Draw]) -> Value { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: pack_screen_fixture RESOURCES CASES OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/pack_selection_fixture.rs b/crates/horizon-client/examples/probe/pack_selection_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pack_selection_fixture.rs rename to crates/horizon-client/examples/probe/pack_selection_fixture.rs index 65ed2471a..91c587343 100644 --- a/crates/horizon-client/examples/pack_selection_fixture.rs +++ b/crates/horizon-client/examples/probe/pack_selection_fixture.rs @@ -35,8 +35,8 @@ fn lists(m: &SelectionModel) -> Value { json!({"unselected": side(false), "selected": side(true)}) } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: pack_selection_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/probe/particle_providers_probe.rs similarity index 99% rename from crates/horizon-client/examples/particle_providers_probe.rs rename to crates/horizon-client/examples/probe/particle_providers_probe.rs index 8b8bd1e0d..c8cd9d88d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/probe/particle_providers_probe.rs @@ -140,8 +140,8 @@ fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Resul Ok(world) } -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let root = &Path::new(".local/horizon-client").join(horizon_core::VANILLA_VERSION); let assets = Assets::load(root)?; let facts = BlockFacts::load(root, assets.registry)?; diff --git a/crates/horizon-client/examples/pick_block_data_fixture.rs b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs similarity index 96% rename from crates/horizon-client/examples/pick_block_data_fixture.rs rename to crates/horizon-client/examples/probe/pick_block_data_fixture.rs index b47f56733..7496ceb8e 100644 --- a/crates/horizon-client/examples/pick_block_data_fixture.rs +++ b/crates/horizon-client/examples/probe/pick_block_data_fixture.rs @@ -78,8 +78,8 @@ fn case(line: &str) -> Option { Some(out) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let input = fs::read_to_string( args.get(1) .ok_or("usage: pick_block_data_fixture INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/probe/place_recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/place_recipe_fixture.rs rename to crates/horizon-client/examples/probe/place_recipe_fixture.rs index 1e2b66dbf..e59750aaf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/place_recipe_fixture.rs @@ -28,8 +28,8 @@ fn state(menu: &Menu) -> String { ) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: place_recipe_fixture RESOURCES CASES ORDERS OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/player_sync_fixture.rs b/crates/horizon-client/examples/probe/player_sync_fixture.rs similarity index 96% rename from crates/horizon-client/examples/player_sync_fixture.rs rename to crates/horizon-client/examples/probe/player_sync_fixture.rs index b50a672af..034aa6400 100644 --- a/crates/horizon-client/examples/player_sync_fixture.rs +++ b/crates/horizon-client/examples/probe/player_sync_fixture.rs @@ -8,8 +8,8 @@ fn number(value: &Value) -> f64 { f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()) } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); for line in input.lines() { diff --git a/crates/horizon-client/examples/raid_fixture.rs b/crates/horizon-client/examples/probe/raid_fixture.rs similarity index 99% rename from crates/horizon-client/examples/raid_fixture.rs rename to crates/horizon-client/examples/probe/raid_fixture.rs index dfe517e51..648851474 100644 --- a/crates/horizon-client/examples/raid_fixture.rs +++ b/crates/horizon-client/examples/probe/raid_fixture.rs @@ -459,8 +459,8 @@ fn run_codec(c: &BTreeMap<&str, &str>) -> Result { Ok(log.join(" ; ")) } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: raid_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/random_tick_sections_probe.rs b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs similarity index 98% rename from crates/horizon-client/examples/random_tick_sections_probe.rs rename to crates/horizon-client/examples/probe/random_tick_sections_probe.rs index 91c861f45..27eaf8196 100644 --- a/crates/horizon-client/examples/random_tick_sections_probe.rs +++ b/crates/horizon-client/examples/probe/random_tick_sections_probe.rs @@ -51,8 +51,8 @@ impl LevelAccess for Air { fn emit(&mut self, _: LevelEvent) {} } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1])?; let root = input .lines() diff --git a/crates/horizon-client/examples/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_fixture.rs index e165dea9b..7117d4bbe 100644 --- a/crates/horizon-client/examples/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -57,8 +57,8 @@ fn compound(tag: &Tag) -> String { out } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_render_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs similarity index 99% rename from crates/horizon-client/examples/recipe_book_render_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_render_fixture.rs index cd904db79..702471700 100644 --- a/crates/horizon-client/examples/recipe_book_render_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_render_fixture.rs @@ -30,8 +30,8 @@ fn round(v: f32) -> f32 { (v * 1e4).round() / 1e4 } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_book_view_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs similarity index 98% rename from crates/horizon-client/examples/recipe_book_view_fixture.rs rename to crates/horizon-client/examples/probe/recipe_book_view_fixture.rs index 8a1e5da0e..b94952ec5 100644 --- a/crates/horizon-client/examples/recipe_book_view_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_view_fixture.rs @@ -15,8 +15,8 @@ use horizon_client::{ use serde_json::Value; use std::{fmt::Write as _, fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: recipe_book_view_fixture RESOURCES CASES OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/recipe_fixture.rs b/crates/horizon-client/examples/probe/recipe_fixture.rs similarity index 97% rename from crates/horizon-client/examples/recipe_fixture.rs rename to crates/horizon-client/examples/probe/recipe_fixture.rs index e68258e4d..8bdffecd0 100644 --- a/crates/horizon-client/examples/recipe_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_fixture.rs @@ -12,8 +12,8 @@ use horizon_client::{ }; use std::{fs, path::Path}; -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/probe/scene_collision_probe.rs similarity index 97% rename from crates/horizon-client/examples/scene_collision_probe.rs rename to crates/horizon-client/examples/probe/scene_collision_probe.rs index 2dae2204c..7f22a1173 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/probe/scene_collision_probe.rs @@ -28,8 +28,8 @@ fn vector(value: &Value) -> Result { }; Ok(Vec3::new(number(0)?, number(1)?, number(2)?)) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err("usage: scene_collision_probe RESOURCES FIXTURE_DIRECTORY RADIUS".into()); } diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs similarity index 99% rename from crates/horizon-client/examples/scene_motion_probe.rs rename to crates/horizon-client/examples/probe/scene_motion_probe.rs index f4ff07ebf..21977eeab 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -233,8 +233,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { writeln!(out, "events {}", events.join(" | "))?; Ok(()) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: scene_motion_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into(), diff --git a/crates/horizon-client/examples/scoreboard_fixture.rs b/crates/horizon-client/examples/probe/scoreboard_fixture.rs similarity index 99% rename from crates/horizon-client/examples/scoreboard_fixture.rs rename to crates/horizon-client/examples/probe/scoreboard_fixture.rs index 1fe5bab91..4a2534b32 100644 --- a/crates/horizon-client/examples/scoreboard_fixture.rs +++ b/crates/horizon-client/examples/probe/scoreboard_fixture.rs @@ -370,8 +370,8 @@ fn score_json(sc: &sb::Score) -> Value { }) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registries: Value = serde_json::from_str(&fs::read_to_string(&args[1]).expect("registries")).expect("json"); let list = |k: &str| -> Vec { diff --git a/crates/horizon-client/examples/screen_layout_fixture.rs b/crates/horizon-client/examples/probe/screen_layout_fixture.rs similarity index 98% rename from crates/horizon-client/examples/screen_layout_fixture.rs rename to crates/horizon-client/examples/probe/screen_layout_fixture.rs index f364037ab..1103f3647 100644 --- a/crates/horizon-client/examples/screen_layout_fixture.rs +++ b/crates/horizon-client/examples/probe/screen_layout_fixture.rs @@ -60,8 +60,8 @@ fn draw_json(d: &ScreenDraw) -> Value { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT"; let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?)); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs similarity index 99% rename from crates/horizon-client/examples/section_mesh_fixture.rs rename to crates/horizon-client/examples/probe/section_mesh_fixture.rs index 13f1a0f1a..98a4fdc34 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs @@ -170,8 +170,8 @@ fn scene( } Ok(json!({"name": row["name"], "quads": quads})) } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); if args.len() != 3 { return Err( "usage: section_mesh_fixture RESOURCES (INPUT.jsonl | facts) OUTPUT.jsonl".into(), diff --git a/crates/horizon-client/examples/server_files_probe.rs b/crates/horizon-client/examples/probe/server_files_probe.rs similarity index 99% rename from crates/horizon-client/examples/server_files_probe.rs rename to crates/horizon-client/examples/probe/server_files_probe.rs index ce146be78..85b33a764 100644 --- a/crates/horizon-client/examples/server_files_probe.rs +++ b/crates/horizon-client/examples/probe/server_files_probe.rs @@ -11,8 +11,8 @@ use horizon_client::server::{ use horizon_protocol::crypto::uuid_string; use std::{fmt::Write as _, path::Path}; -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let root = std::path::PathBuf::from(args.next().ok_or("CASES OUTPUT")?); let output = args.next().ok_or("OUTPUT")?; let mut cases: Vec<_> = std::fs::read_dir(&root)? diff --git a/crates/horizon-client/examples/situational_music_fixture.rs b/crates/horizon-client/examples/probe/situational_music_fixture.rs similarity index 96% rename from crates/horizon-client/examples/situational_music_fixture.rs rename to crates/horizon-client/examples/probe/situational_music_fixture.rs index ae47426bb..898893c09 100644 --- a/crates/horizon-client/examples/situational_music_fixture.rs +++ b/crates/horizon-client/examples/probe/situational_music_fixture.rs @@ -5,8 +5,8 @@ use horizon_client::music::{BackgroundMusic, Music, MusicTables, Situation}; use horizon_client::sound_events::normalize; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let tables = MusicTables::load(std::path::Path::new(&args[1])); let input = std::fs::read_to_string(&args[2]).expect("input"); let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output")); diff --git a/crates/horizon-client/examples/skin_image_fixture.rs b/crates/horizon-client/examples/probe/skin_image_fixture.rs similarity index 90% rename from crates/horizon-client/examples/skin_image_fixture.rs rename to crates/horizon-client/examples/probe/skin_image_fixture.rs index 9373fb1f5..e85be6a16 100644 --- a/crates/horizon-client/examples/skin_image_fixture.rs +++ b/crates/horizon-client/examples/probe/skin_image_fixture.rs @@ -9,8 +9,8 @@ use std::{ }; type Result = std::result::Result>; -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: skin_image_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/sound_engine_fixture.rs b/crates/horizon-client/examples/probe/sound_engine_fixture.rs similarity index 98% rename from crates/horizon-client/examples/sound_engine_fixture.rs rename to crates/horizon-client/examples/probe/sound_engine_fixture.rs index c42ea8bf9..327a8e9d1 100644 --- a/crates/horizon-client/examples/sound_engine_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_engine_fixture.rs @@ -1,8 +1,7 @@ //! Replays `tools/test_sound_engine_parity.py` scripts through Horizon's //! `SoundEngine` with a backend recording what an OpenAL source would hold: //! `sound_engine_fixture ROOT INPUT OUTPUT`. -#[path = "audio_common/mod.rs"] -mod common; +use crate::audio_common as common; use common::{Fake, d, describe, f, flush, result_name}; use horizon_client::sound_engine::{ Attenuation, Backend, CartSound, InstanceId, SoundEngine, SoundInstance, TickContext, @@ -12,8 +11,8 @@ use horizon_core::random::LegacyRandom; use std::collections::BTreeMap; use std::io::Write; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut engine = SoundEngine::new(SoundRegistry::load(std::path::Path::new(&args[1]))); engine.listening = true; let mut backend = Fake::default(); diff --git a/crates/horizon-client/examples/sound_event_fixture.rs b/crates/horizon-client/examples/probe/sound_event_fixture.rs similarity index 97% rename from crates/horizon-client/examples/sound_event_fixture.rs rename to crates/horizon-client/examples/probe/sound_event_fixture.rs index 57c6dd7be..6b52dfc9c 100644 --- a/crates/horizon-client/examples/sound_event_fixture.rs +++ b/crates/horizon-client/examples/probe/sound_event_fixture.rs @@ -9,8 +9,8 @@ fn bits(v: f32) -> String { format!("{:08x}", v.to_bits()) } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let registry = SoundRegistry::load(std::path::Path::new(&args[1])); let mut engine = SoundEngine::new(registry); let input = std::fs::read_to_string(&args[2]).expect("input"); diff --git a/crates/horizon-client/examples/spawn_rules_fixture.rs b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs similarity index 98% rename from crates/horizon-client/examples/spawn_rules_fixture.rs rename to crates/horizon-client/examples/probe/spawn_rules_fixture.rs index dc491be00..661194f6d 100644 --- a/crates/horizon-client/examples/spawn_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/spawn_rules_fixture.rs @@ -136,8 +136,8 @@ fn reason(name: &str) -> Reason { } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let root = Path::new( args.get(1) .ok_or("usage: spawn_rules_fixture RESOURCES INPUT OUTPUT")?, diff --git a/crates/horizon-client/examples/sprint_probe.rs b/crates/horizon-client/examples/probe/sprint_probe.rs similarity index 97% rename from crates/horizon-client/examples/sprint_probe.rs rename to crates/horizon-client/examples/probe/sprint_probe.rs index ab538ffe1..5c161da4f 100644 --- a/crates/horizon-client/examples/sprint_probe.rs +++ b/crates/horizon-client/examples/probe/sprint_probe.rs @@ -20,8 +20,8 @@ fn keys(mask: u64) -> Keys { analog: None, } } -fn main() -> Result<()> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec<_> = crate::args().skip(1).collect(); let mut out = BufWriter::new(File::create(&args[1])?); for line in BufReader::new(File::open(&args[0])?).lines() { let f: Value = serde_json::from_str(&line?)?; diff --git a/crates/horizon-client/examples/subtitle_fixture.rs b/crates/horizon-client/examples/probe/subtitle_fixture.rs similarity index 97% rename from crates/horizon-client/examples/subtitle_fixture.rs rename to crates/horizon-client/examples/probe/subtitle_fixture.rs index ac8e8d4d8..8f690f130 100644 --- a/crates/horizon-client/examples/subtitle_fixture.rs +++ b/crates/horizon-client/examples/probe/subtitle_fixture.rs @@ -21,8 +21,8 @@ fn pose(m: [f32; 6]) -> Value { json!(m) } -fn main() -> Result<(), Box> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: subtitle_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/tab_list_fixture.rs b/crates/horizon-client/examples/probe/tab_list_fixture.rs similarity index 98% rename from crates/horizon-client/examples/tab_list_fixture.rs rename to crates/horizon-client/examples/probe/tab_list_fixture.rs index aca50e204..6ea822fba 100644 --- a/crates/horizon-client/examples/tab_list_fixture.rs +++ b/crates/horizon-client/examples/probe/tab_list_fixture.rs @@ -53,8 +53,8 @@ fn runs(t: &Text) -> Value { out.into_iter().map(|(r, k)| json!([r, k])).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args_os().skip(1).map(PathBuf::from).collect(); let [root, inputs, output] = args.as_slice() else { return Err("usage: tab_list_fixture RESOURCES INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/team_rules_fixture.rs b/crates/horizon-client/examples/probe/team_rules_fixture.rs similarity index 97% rename from crates/horizon-client/examples/team_rules_fixture.rs rename to crates/horizon-client/examples/probe/team_rules_fixture.rs index ec56b67ee..9a2d716ff 100644 --- a/crates/horizon-client/examples/team_rules_fixture.rs +++ b/crates/horizon-client/examples/probe/team_rules_fixture.rs @@ -8,8 +8,8 @@ use horizon_client::scoreboard::{self as sb, CollisionRule, NameView, Scoreboard use serde_json::{Value, json}; use std::{fs, io::Write}; -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let mut out = std::io::BufWriter::new(fs::File::create(&args[2]).expect("output")); for line in fs::read_to_string(&args[1]).expect("inputs").lines() { let c: Value = serde_json::from_str(line).expect("case"); diff --git a/crates/horizon-client/examples/toggle_keys_probe.rs b/crates/horizon-client/examples/probe/toggle_keys_probe.rs similarity index 95% rename from crates/horizon-client/examples/toggle_keys_probe.rs rename to crates/horizon-client/examples/probe/toggle_keys_probe.rs index 01ef5fd4d..d05acdd5c 100644 --- a/crates/horizon-client/examples/toggle_keys_probe.rs +++ b/crates/horizon-client/examples/probe/toggle_keys_probe.rs @@ -11,8 +11,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, }; -fn main() -> Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().collect(); let input = BufReader::new(File::open(&args[1])?); let mut out = BufWriter::new(File::create(&args[2])?); for (n, line) in input.lines().enumerate() { diff --git a/crates/horizon-client/examples/tooltip_display_fixture.rs b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs similarity index 93% rename from crates/horizon-client/examples/tooltip_display_fixture.rs rename to crates/horizon-client/examples/probe/tooltip_display_fixture.rs index ec61159cd..8a7525785 100644 --- a/crates/horizon-client/examples/tooltip_display_fixture.rs +++ b/crates/horizon-client/examples/probe/tooltip_display_fixture.rs @@ -3,8 +3,8 @@ use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack}; use horizon_world::nbt::Tag; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/probe/trading_fixture.rs similarity index 99% rename from crates/horizon-client/examples/trading_fixture.rs rename to crates/horizon-client/examples/probe/trading_fixture.rs index 58824257c..c2215d327 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/probe/trading_fixture.rs @@ -231,8 +231,8 @@ fn prepare(m: &mut Merchant, gossips: &mut Gossips, kv: &HashMap } } -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().collect(); +pub fn main() -> horizon_client::Result<()> { + let args: Vec = crate::args().collect(); let usage = "usage: trading_fixture RESOURCES INPUT VANILLA_OUTPUT OUTPUT"; let root = Path::new(args.get(1).ok_or(usage)?); let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; diff --git a/crates/horizon-client/examples/translucency_fixture.rs b/crates/horizon-client/examples/probe/translucency_fixture.rs similarity index 93% rename from crates/horizon-client/examples/translucency_fixture.rs rename to crates/horizon-client/examples/probe/translucency_fixture.rs index 11083d6b2..8ea42c1dc 100644 --- a/crates/horizon-client/examples/translucency_fixture.rs +++ b/crates/horizon-client/examples/probe/translucency_fixture.rs @@ -14,8 +14,8 @@ struct Case { cameras: Vec<[f64; 3]>, } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().skip(1).collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().skip(1).collect(); let [input, output] = args.as_slice() else { return Err("usage: translucency_fixture INPUT OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/probe/weather_fixture.rs similarity index 95% rename from crates/horizon-client/examples/weather_fixture.rs rename to crates/horizon-client/examples/probe/weather_fixture.rs index 3cf6c31be..b85dd3e09 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/probe/weather_fixture.rs @@ -8,8 +8,8 @@ fn bits(value: f32) -> String { format!("{:x}", value.to_bits()) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut output = String::new(); let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { diff --git a/crates/horizon-client/examples/world_border_render_fixture.rs b/crates/horizon-client/examples/probe/world_border_render_fixture.rs similarity index 98% rename from crates/horizon-client/examples/world_border_render_fixture.rs rename to crates/horizon-client/examples/probe/world_border_render_fixture.rs index 1de15eeeb..535118959 100644 --- a/crates/horizon-client/examples/world_border_render_fixture.rs +++ b/crates/horizon-client/examples/probe/world_border_render_fixture.rs @@ -24,8 +24,8 @@ fn doubles(v: &[f64]) -> Value { v.iter().map(|f| f.to_bits() as i64).collect() } -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); +pub fn main() -> Result<()> { + let args: Vec = crate::args().skip(1).collect(); let [inputs, output] = args.as_slice() else { return Err("usage: world_border_render_fixture INPUTS OUTPUT".into()); }; diff --git a/crates/horizon-client/examples/world_options_fixture.rs b/crates/horizon-client/examples/probe/world_options_fixture.rs similarity index 93% rename from crates/horizon-client/examples/world_options_fixture.rs rename to crates/horizon-client/examples/probe/world_options_fixture.rs index 5bbf9f1c7..5bd3026bc 100644 --- a/crates/horizon-client/examples/world_options_fixture.rs +++ b/crates/horizon-client/examples/probe/world_options_fixture.rs @@ -2,8 +2,8 @@ use horizon_protocol::{buf::Reader, packets::play::*}; use std::{error::Error, fmt::Write}; -fn main() -> Result<(), Box> { - let args: Vec = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec = crate::args().collect(); let mut output = String::new(); for line in std::fs::read_to_string(&args[1])?.lines() { let fields: Vec<&str> = line.split('\t').collect(); diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs deleted file mode 100644 index 30625be65..000000000 --- a/crates/horizon-client/examples/save_bench.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! The region writer on real chunks, without a window: how long a world's -//! chunks take to be encoded, compressed and written by `SaveDir`, against -//! the same encoding and compression done one chunk after another (what the -//! writer thread did alone before it had helpers). -//! -//! save_bench RESOURCES DIMENSION_DIR [--rounds N] -//! -//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ -//! overworld`); its chunks are read once, then each round saves them all into -//! a scratch folder with `save_later` + `flush`, and times the one-thread -//! baseline. The written chunks are checked byte for byte against the -//! baseline's compressed records. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - save::{SaveDir, SaveTables, encode_with}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - compression::Compression, - nbt::Limits, - region::{ChunkRecord, RegionFile}, -}; -use std::{path::PathBuf, sync::Arc, time::Instant}; - -type Result = std::result::Result>; - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; - let root = PathBuf::from(args.first().ok_or(usage)?); - let dimension = PathBuf::from(args.get(1).ok_or(usage)?); - let rounds: usize = args - .iter() - .position(|a| a == "--rounds") - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(5); - - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); - let registry = assets.registry; - - let source = SaveDir::new(dimension.clone()); - let _ = source.tables.set(tables.clone()); - let mut chunks = Vec::new(); - for entry in std::fs::read_dir(dimension.join("region"))? { - let path = entry?.path(); - if path.extension().is_none_or(|e| e != "mca") { - continue; - } - let region = RegionFile::open(&path)?; - for (pos, _) in region.chunks() { - if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { - chunks.push(Arc::new(chunk)); - } - } - } - chunks.sort_by_key(|c| (c.x, c.z)); - println!("{} chunks from {}", chunks.len(), dimension.display()); - - let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); - // Encoding and compressing on one thread (what the writer did alone), - // then SaveDir's writer with its helpers. - let mut times = [Vec::new(), Vec::new(), Vec::new()]; - let mut written = Vec::new(); - for round in 0..rounds { - let started = Instant::now(); - let tags: Vec<_> = chunks - .iter() - .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) - .collect(); - times[0].push(started.elapsed().as_secs_f64()); - let started = Instant::now(); - let baseline: Vec = tags - .iter() - .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) - .collect::>()?; - times[1].push(started.elapsed().as_secs_f64()); - drop(tags); - - let _ = std::fs::remove_dir_all(&scratch); - let save = SaveDir::new(scratch.clone()); - let _ = save.tables.set(tables.clone()); - let started = Instant::now(); - save.save_later(&chunks, registry, &biomes)?; - save.flush().unwrap(); - times[2].push(started.elapsed().as_secs_f64()); - drop(save); - - if round == 0 { - for (chunk, want) in chunks.iter().zip(&baseline) { - let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); - let got = RegionFile::open(&path)? - .read(ChunkPos::new(chunk.x, chunk.z))? - .ok_or("a saved chunk is missing")?; - if got.compressed != want.compressed { - return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); - } - } - written = baseline.iter().map(|r| r.compressed.len()).collect(); - } - } - let _ = std::fs::remove_dir_all(&scratch); - println!( - "{} KiB compressed, identical to the one-thread records", - written.iter().sum::() / 1024 - ); - let per_chunk = 1000.0 / chunks.len() as f64; - let names = [ - "one thread: encode", - "one thread: compress", - "SaveDir (encode, compress, write)", - ]; - for (name, t) in names.iter().zip(&mut times) { - t.sort_by(f64::total_cmp); - println!( - "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", - t[0] * 1000.0, - t[t.len() / 2] * 1000.0, - t[0] * per_chunk - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs deleted file mode 100644 index 3954e3bb3..000000000 --- a/crates/horizon-client/examples/save_parity.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Differential save test: load every full chunk of a world written by the -//! vanilla 26.3 server, light it, encode it again with Horizon's chunk writer -//! and compare the result with the original NBT: block states, biomes, -//! heightmaps, light layers (by value), block entities and scheduled ticks. -//! -//! cargo run --profile fast -p horizon-client --example save_parity -- \ -//! RESOURCES DIMENSION_DIR [--nether] -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - chunk::{Chunk, MIN_Y, SECTIONS}, - light::{LightTables, apply_lighting, light_chunk}, - save::{self, SaveTables}, -}; -use horizon_core::position::ChunkPos; -use horizon_world::{ - chunk::BlockState, - nbt::{Limits, NamedTag, Tag}, - region::RegionFile, -}; -use std::{ - collections::{BTreeMap, HashMap}, - path::PathBuf, -}; - -/// Block state names per section index, decoded independently of Horizon. -fn block_names(tag: &Tag) -> BTreeMap> { - let mut out = BTreeMap::new(); - let Some(Tag::List(sections)) = tag.get("sections") else { - return out; - }; - for s in sections { - let Some(Tag::Byte(y)) = s.get("Y") else { - continue; - }; - let Some(states) = s.get("block_states") else { - continue; - }; - let Some(Tag::List(palette)) = states.get("palette") else { - continue; - }; - let names: Vec = palette - .iter() - .map(|p| { - let st = BlockState::from_nbt(p).expect("palette entry"); - format!("{}{:?}", st.name, st.properties) - }) - .collect(); - let bits = (usize::BITS - (names.len().max(1) - 1).leading_zeros()).max(4); - let per = 64 / bits as usize; - let data = match states.get("data") { - Some(Tag::LongArray(d)) => d.clone(), - _ => Vec::new(), - }; - let blocks = (0..4096) - .map(|i| { - if names.len() == 1 { - return names[0].clone(); - } - let v = (data[i / per] as u64 >> ((i % per) as u32 * bits)) & ((1 << bits) - 1); - names[v as usize].clone() - }) - .collect(); - out.insert(i64::from(*y), blocks); - } - out -} -fn light(tag: &Tag, key: &str) -> HashMap> { - let mut out = HashMap::new(); - if let Some(Tag::List(sections)) = tag.get("sections") { - for s in sections { - if let (Some(Tag::Byte(y)), Some(Tag::ByteArray(a))) = (s.get("Y"), s.get(key)) { - out.insert(i64::from(*y), a.clone()); - } - } - } - out -} -/// Light value with vanilla's reading of missing layers. -fn value( - layers: &HashMap>, - sy: i64, - i: usize, - sky: bool, - empty: bool, - top: i64, -) -> u8 { - let nibble = |a: &Vec, i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15; - if let Some(a) = layers.get(&sy) { - return nibble(a, i); - } - if !sky || !empty { - return 0; - } - ((sy + 1)..=top) - .find_map(|y| layers.get(&y)) - .map_or(15, |a| nibble(a, i & 255)) -} -fn count(tag: &Tag, key: &str) -> usize { - match tag.get(key) { - Some(Tag::List(l)) => l.len(), - _ => 0, - } -} - -fn main() -> horizon_client::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from( - args.first() - .ok_or("usage: save_parity RESOURCES DIMENSION_DIR")?, - ); - let dim = PathBuf::from(args.get(1).ok_or("missing dimension directory")?); - let sky_light = !args.iter().any(|a| a == "--nether"); - let assets = Assets::load(&root)?; - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Biomes::load(&root)?; - let lights = LightTables::load(&root, assets.registry, &facts)?; - let tables = SaveTables::new(&assets).with_block_entities(&facts); - let mut originals: HashMap<(i32, i32), NamedTag> = HashMap::new(); - let mut chunks: HashMap<(i32, i32), Chunk> = HashMap::new(); - for entry in std::fs::read_dir(dim.join("region"))? { - let mut region = RegionFile::open(entry?.path())?; - let positions: Vec = region.chunks().map(|(p, _)| p).collect(); - for p in positions { - let Some(record) = region.read(p)? else { - continue; - }; - let tag = record.nbt(Limits::default())?; - if tag.tag.get("isLightOn") != Some(&Tag::Byte(1)) { - continue; - } - if let Some(c) = save::decode_with(&tag, assets.registry, &biomes, Some(&tables)) { - chunks.insert((c.x, c.z), c); - originals.insert((p.x, p.z), tag); - } - } - } - let mut keys: Vec<_> = chunks - .keys() - .copied() - .filter(|&(x, z)| { - (-1..=1).all(|dz| (-1..=1).all(|dx| chunks.contains_key(&(x + dx, z + dz)))) - }) - .collect(); - keys.sort_unstable(); - let ( - mut blocks_bad, - mut biomes_bad, - mut heightmaps_bad, - mut light_bad, - mut light_total, - mut other_bad, - ) = (0, 0, 0, 0u64, 0u64, 0); - for &(x, z) in &keys { - let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { - std::array::from_fn(|dx| chunks.get(&(x + dx as i32 - 1, z + dz as i32 - 1))) - }); - let mut chunk = chunks[&(x, z)].clone(); - apply_lighting(&mut chunk, light_chunk(®ion, &lights, sky_light)); - chunk.lit = true; - let ours = save::encode_with(&chunk, assets.registry, &biomes, Some(&tables), sky_light); - let theirs = &originals[&(x, z)]; - let (a, b) = (&ours.tag, &theirs.tag); - // Block states: compare every non-empty vanilla section. - let (na, nb) = (block_names(a), block_names(b)); - for (y, vb) in &nb { - match na.get(y) { - Some(va) if va == vb => {} - Some(va) => { - let n = va.iter().zip(vb).filter(|(p, q)| p != q).count(); - if blocks_bad < 5 { - let i = va.iter().zip(vb).position(|(p, q)| p != q).unwrap_or(0); - eprintln!( - "chunk {x} {z} section {y}: {n} blocks differ, e.g. {} vs {}", - va[i], vb[i] - ); - } - blocks_bad += 1; - } - None if vb.iter().all(|s| s.starts_with("minecraft:air")) => {} - None => blocks_bad += 1, - } - } - let biome_of = |t: &Tag| -> Vec { - match t.get("sections") { - Some(Tag::List(l)) => l.iter().filter_map(|s| s.get("biomes").cloned()).collect(), - _ => Vec::new(), - } - }; - if biome_of(a) != biome_of(b) { - biomes_bad += 1; - } - for kind in [ - "WORLD_SURFACE", - "OCEAN_FLOOR", - "MOTION_BLOCKING", - "MOTION_BLOCKING_NO_LEAVES", - ] { - let get = |t: &Tag| t.get("Heightmaps").and_then(|h| h.get(kind)).cloned(); - if get(a) != get(b) { - if heightmaps_bad < 5 { - eprintln!("chunk {x} {z}: heightmap {kind} differs"); - } - heightmaps_bad += 1; - } - } - for (key, sky) in [("SkyLight", true), ("BlockLight", false)] { - if sky && !sky_light { - continue; - } - let (la, lb) = (light(a, key), light(b, key)); - let top = i64::from((MIN_Y >> 4) + SECTIONS as i32); - for si in 0..SECTIONS { - let sy = i64::from((MIN_Y >> 4) + si as i32); - let empty = chunk.sections[si].is_uniform(tables_air(&assets)); - for i in 0..4096 { - light_total += 1; - if value(&la, sy, i, sky, empty, top) != value(&lb, sy, i, sky, empty, top) { - light_bad += 1; - } - } - } - } - for key in ["block_entities", "block_ticks", "fluid_ticks"] { - if count(a, key) != count(b, key) { - if other_bad < 5 { - eprintln!( - "chunk {x} {z}: {key} {} vs {}", - count(a, key), - count(b, key) - ); - } - other_bad += 1; - } - } - for key in [ - "structures", - "PostProcessing", - "InhabitedTime", - "Status", - "DataVersion", - "yPos", - ] { - if a.get(key) != b.get(key) { - if other_bad < 5 { - eprintln!("chunk {x} {z}: {key} differs"); - } - other_bad += 1; - } - } - } - println!( - "{} chunks: {blocks_bad} sections with different blocks, {biomes_bad} chunks with different biomes, \ - {heightmaps_bad} different heightmaps, {light_bad} of {light_total} light values differ, {other_bad} other differences", - keys.len() - ); - Ok(()) -} -fn tables_air(assets: &Assets) -> u32 { - assets - .registry - .default_state("minecraft:air") - .map_or(0, |s| s.0) -} diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs deleted file mode 100644 index b8c56b28c..000000000 --- a/crates/horizon-client/examples/streaming_bench.rs +++ /dev/null @@ -1,284 +0,0 @@ -//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker -//! pool, without a window: how fast a render distance fills with N workers, and -//! what the render thread pays for it in `Streaming::update`. -//! -//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] -//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] -//! -//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x -//! at that speed for T seconds while frames run at F per second. Each phase reports -//! its wall time, chunks generated and sections meshed, and the time `update` -//! took on the calling thread (the render thread in the game): total, median, -//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the -//! allocations made on the calling thread during updates and by everything. -use horizon_client::{ - assets::Assets, - biome::Biomes, - blocks::BlockFacts, - light::LightTables, - mesher::MeshTables, - models, - streaming::{Streaming, WorkerContext}, - vanillagen::VanillaTerrain, - world::World, -}; -use std::{ - alloc::{GlobalAlloc, Layout, System}, - cell::Cell, - path::PathBuf, - sync::{ - Arc, - atomic::{AtomicU64, Ordering::Relaxed}, - }, - time::{Duration, Instant}, -}; - -const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some(); -static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); -static BYTES: AtomicU64 = AtomicU64::new(0); -thread_local! { - static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; -} -fn count(size: usize) { - if TRACK { - ALLOCATIONS.fetch_add(1, Relaxed); - BYTES.fetch_add(size as u64, Relaxed); - let _ = LOCAL.try_with(|c| { - let (n, b) = c.get(); - c.set((n + 1, b + size as u64)); - }); - } -} -struct CountingAllocator; -// Delegates every operation and layout unchanged to System. -unsafe impl GlobalAlloc for CountingAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc(layout) } - } - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - count(layout.size()); - unsafe { System.alloc_zeroed(layout) } - } - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - unsafe { System.dealloc(ptr, layout) }; - } - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { - count(size); - unsafe { System.realloc(ptr, layout, size) } - } -} -#[global_allocator] -static ALLOCATOR: CountingAllocator = CountingAllocator; - -type Result = std::result::Result>; - -fn cpu_seconds() -> f64 { - std::fs::read_to_string("/proc/self/stat") - .ok() - .and_then(|stat| { - let fields = stat - .rsplit_once(')')? - .1 - .split_whitespace() - .collect::>(); - Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) - }) - .unwrap_or(0.0) -} - -#[derive(Default)] -struct Phase { - updates: Vec, - local: (u64, u64), - uploads: usize, - stage_samples: [u64; 7], - cpu_start: f64, -} -impl Phase { - fn update(&mut self, streaming: &mut Streaming, world: &mut World) { - if self.updates.is_empty() { - self.cpu_start = cpu_seconds(); - } - let before = LOCAL.with(Cell::get); - let started = Instant::now(); - let (uploads, _) = streaming.update(world); - self.updates.push(started.elapsed().as_secs_f64() * 1e3); - let after = LOCAL.with(Cell::get); - self.local.0 += after.0 - before.0; - self.local.1 += after.1 - before.1; - self.uploads += uploads.len(); - drop(uploads); - for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { - *sum += count as u64; - } - } - fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { - let mut sorted = self.updates.clone(); - sorted.sort_by(f64::total_cmp); - let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)]; - let total: f64 = sorted.iter().sum(); - println!( - "{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms", - wall.as_secs_f64(), - streaming.generated_total - generated, - self.uploads, - total, - sorted.len(), - at(0.5), - at(0.99), - sorted.last().copied().unwrap_or(0.0), - ); - println!( - "BENCH {}", - serde_json::json!({ - "phase": name, "wall_s": wall.as_secs_f64(), - "cpu_s": cpu_seconds() - self.cpu_start, - "chunks": streaming.generated_total - generated, "sections": self.uploads, - "updates": self.updates.len(), "update_ms": total, - "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), - }) - ); - if TRACK { - println!( - " update allocations: {} ({:.1} MiB)", - self.local.0, - self.local.1 as f64 / 1048576.0 - ); - } - } -} - -/// Nothing queued or in flight. Sections at the edge of the area stay dirty -/// (their outer neighbours are never lit), so they don't count. -fn settled(streaming: &Streaming) -> bool { - streaming - .stages() - .iter() - .all(|&(name, n)| name == "protos" || n == 0) -} - -fn main() -> Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?); - let flag = |name: &str, default: f64| -> f64 { - args.iter() - .position(|a| a == name) - .and_then(|i| args.get(i + 1)) - .and_then(|v| v.parse().ok()) - .unwrap_or(default) - }; - let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1); - let threads = flag("--threads", auto as f64) as usize; - let radius = flag("--radius", 8.0) as i32; - let seed = flag("--seed", 1234.0) as i64; - let fly = flag("--fly", 0.0); - let seconds = flag("--seconds", 10.0); - let hz = flag("--hz", 240.0); - let dimension = args - .iter() - .position(|a| a == "--dimension") - .and_then(|i| args.get(i + 1)) - .map(|d| { - if d.contains(':') { - d.clone() - } else { - format!("minecraft:{d}") - } - }) - .unwrap_or_else(|| "minecraft:overworld".into()); - let center = ( - flag("--center-x", 0.0) as i32, - flag("--center-z", 0.0) as i32, - ); - - let assets = Arc::new(Assets::load(&root)?); - let render = Arc::new(assets.reload(&root)?); - let facts = BlockFacts::load(&root, assets.registry)?; - let biomes = Arc::new(Biomes::load(&root)?); - let tables = Arc::new(MeshTables::new( - &assets, - &render, - &facts, - models::load_visibility(&root, assets.registry)?, - )?); - let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::for_dimension( - &root.join("worldgen"), - assets.registry, - &biomes, - seed, - &dimension, - )?); - let context = Arc::new(WorkerContext { - assets, - render: render.clone(), - tables, - biomes, - light, - }); - let mut world = World::new(facts.air, seed); - let mut streaming = Streaming::new(terrain, context, threads); - streaming.radius = radius; - streaming.center = center; - streaming.nether_shading = dimension == "minecraft:the_nether"; - streaming.sky_light = dimension != "minecraft:the_nether"; - println!( - "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" - ); - let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); - - // Fill: update as often as the game would uncapped, until settled. - let mut phase = Phase::default(); - let started = Instant::now(); - let mut quiet = 0; - while quiet < 20 { - let uploads = phase.uploads; - phase.update(&mut streaming, &mut world); - quiet = if settled(&streaming) && phase.uploads == uploads { - quiet + 1 - } else { - 0 - }; - std::thread::sleep(Duration::from_micros(500)); - } - phase.report("fill", started.elapsed(), &streaming, 0); - - if fly > 0.0 { - let mut phase = Phase::default(); - let generated = streaming.generated_total; - let frame = Duration::from_secs_f64(1.0 / hz); - let started = Instant::now(); - let mut behind = Vec::new(); - while started.elapsed().as_secs_f64() < seconds { - let next = Instant::now() + frame; - let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, center.1); - phase.update(&mut streaming, &mut world); - // Columns within 2 chunks of the player still missing their meshes. - let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) - .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) - .count(); - behind.push(near); - if let Some(wait) = next.checked_duration_since(Instant::now()) { - std::thread::sleep(wait); - } - } - phase.report("fly", started.elapsed(), &streaming, generated); - let unlit = behind.iter().filter(|&&n| n > 0).count(); - println!( - " frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)", - behind.len(), - unlit as f64 * 100.0 / behind.len().max(1) as f64 - ); - } - if TRACK { - println!( - "all threads: {} allocations ({:.1} MiB)", - ALLOCATIONS.load(Relaxed) - allocations, - (BYTES.load(Relaxed) - bytes) as f64 / 1048576.0 - ); - } - Ok(()) -} diff --git a/crates/horizon-client/examples/tick_chunk_membership_bench.rs b/crates/horizon-client/examples/tick_chunk_membership_bench.rs deleted file mode 100644 index 6b9cb8a0a..000000000 --- a/crates/horizon-client/examples/tick_chunk_membership_bench.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Resident-key synchronization used by Game (registration callback work excluded). -//! Run: CARGO_INCREMENTAL=0 cargo run -p horizon-client --profile fast --example tick_chunk_membership_bench -use horizon_client::{ - chunk::Chunk, chunk_map::ChunkMap, tick_chunk_membership::TickChunkMembership, -}; -use std::{collections::HashSet, hint::black_box, sync::Arc, time::Instant}; - -type Key = (i32, i32); -#[derive(Default)] -struct Old { - keys: HashSet, -} -impl Old { - fn sync(&mut self, map: &ChunkMap) -> (usize, usize) { - let loaded: HashSet<_> = map.keys().copied().collect(); - let mut counts = (0, 0); - for key in loaded.difference(&self.keys.clone()) { - black_box(key); - counts.0 += 1; - } - for key in self.keys.difference(&loaded) { - black_box(key); - counts.1 += 1; - } - self.keys = loaded; - counts - } -} -fn new_sync(cache: &mut TickChunkMembership, map: &ChunkMap) -> (usize, usize) { - if !cache.synchronize(map) { - return (0, 0); - } - let added = cache.take_added(); - for key in &added { - black_box(key); - } - for key in cache.removed() { - black_box(key); - } - let counts = (added.len(), cache.removed().len()); - cache.recycle_added(added); - counts -} -fn map(offset: i32) -> ChunkMap { - let mut map = ChunkMap::default(); - // Share a payload: the synchronization path reads only keys, not block data. - let chunk = Arc::new(Chunk::empty(0, 0)); - for x in -16..=16 { - for z in -16..=16 { - map.insert((x + offset, z), chunk.clone()); - } - } - map -} -fn run(new: bool, scenario: usize, iterations: usize) -> (f64, (usize, usize)) { - let mut a = map(0); - let b = map(33); - let chunk = Arc::new(Chunk::empty(0, 0)); - let mut old = Old::default(); - let mut cache = TickChunkMembership::default(); - for _ in 0..64 { - if new { - black_box(new_sync(&mut cache, &a)); - } else { - black_box(old.sync(&a)); - } - } - let mut total = (0, 0); - let start = Instant::now(); - for i in 0..iterations { - let resident = match scenario { - 0 => &a, - 1 => { - let (previous, next) = if i % 2 == 0 { - ((-16, -16), (-17, -16)) - } else { - ((-17, -16), (-16, -16)) - }; - a.remove(&previous); - a.insert(next, chunk.clone()); - &a - } - 2 => { - if i % 2 == 0 { - &b - } else { - &a - } - } - _ => unreachable!(), - }; - let counts = if new { - new_sync(black_box(&mut cache), black_box(resident)) - } else { - old.sync(black_box(resident)) - }; - total.0 += counts.0; - total.1 += counts.1; - } - ( - start.elapsed().as_secs_f64() * 1e9 / iterations as f64, - black_box(total), - ) -} -fn main() { - println!("1089 keys, 64 warmup calls, 9 samples; ns/sync, median"); - for (scenario, name, iterations) in [ - (0, "stable", 10_000), - (1, "one-key same-count replacement", 2_000), - (2, "whole-map replacement", 1_000), - ] { - let mut before = Vec::new(); - let mut after = Vec::new(); - for sample in 0..9 { - let (old, new) = if sample % 2 == 0 { - ( - run(false, scenario, iterations), - run(true, scenario, iterations), - ) - } else { - let new = run(true, scenario, iterations); - (run(false, scenario, iterations), new) - }; - assert_eq!(old.1, new.1); - let expected = match scenario { - 0 => (0, 0), - 1 => (iterations, iterations), - _ => (1089 * iterations, 1089 * iterations), - }; - assert_eq!(new.1, expected); - before.push(old.0); - after.push(new.0); - } - before.sort_by(f64::total_cmp); - after.sort_by(f64::total_cmp); - println!( - "{name}: {:.1} -> {:.1} ns, {:.2}x; {iterations} iterations/sample", - before[4], - after[4], - before[4] / after[4] - ); - } -} diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs new file mode 100644 index 000000000..8658b5815 --- /dev/null +++ b/crates/horizon-client/src/bundle.rs @@ -0,0 +1,192 @@ +//! `BundleContents.Mutable`: what a bundle takes in and gives back, by +//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click +//! overrides on it. +use crate::items::{ItemStack, Items}; +use horizon_world::nbt::Tag; + +/// A bundle weight: vanilla's `Fraction`, exact and kept reduced. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Weight { + n: i128, + d: i128, +} + +fn gcd(a: i128, b: i128) -> i128 { + let (mut a, mut b) = (a.abs(), b.abs()); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +impl Weight { + const ZERO: Self = Self { n: 0, d: 1 }; + const ONE: Self = Self { n: 1, d: 1 }; + + fn new(n: i128, d: i128) -> Self { + let g = gcd(n, d); + Self { n: n / g, d: d / g } + } + + fn add(self, o: Self) -> Self { + Self::new(self.n * o.d + o.n * self.d, self.d * o.d) + } + + fn sub(self, o: Self) -> Self { + self.add(Self { n: -o.n, d: o.d }) + } + + fn times(self, count: u32) -> Self { + Self::new(self.n * i128::from(count), self.d) + } + + /// `this.divideBy(item).intValue()` (truncated), at least 0. + fn how_many(self, item: Self) -> u32 { + let q = (self.n * item.d) / (self.d * item.n); + u32::try_from(q.max(0)).unwrap_or(u32::MAX) + } +} + +/// The sounds of `BundleItem` (`Entity.playSound` at the player): insert +/// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed +/// insert at 1, 1. +pub const INSERT: &str = "minecraft:item.bundle.insert"; +pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail"; +pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one"; + +fn max_stack(items: &Items, stack: &ItemStack) -> u32 { + items.get(&stack.item).map_or(64, |i| i.max_stack).max(1) +} + +/// The stack's `bundle_contents`, when it has the component. +fn contents_of<'a>(items: &Items, stack: &'a ItemStack) -> Option<&'a [ItemStack]> { + let inside = stack.data().map_or(&[][..], |d| &d.bundle_contents[..]); + let bundle = items.get(&stack.item).is_some_and(|i| i.bundle); + (bundle || !inside.is_empty()).then_some(inside) +} + +/// `BundleContents.getWeight`: a nested bundle weighs its contents plus +/// 1/16, a beehive with bees 1, the rest 1 / max stack size. +fn item_weight(items: &Items, stack: &ItemStack) -> Weight { + if let Some(inside) = contents_of(items, stack) { + return contents_weight(items, inside).add(Weight::new(1, 16)); + } + let bees = stack + .data() + .and_then(|d| d.other("minecraft:bees")) + .is_some_and(|b| matches!(b, Tag::List(l) if !l.is_empty())); + if bees { + Weight::ONE + } else { + Weight::new(1, i128::from(max_stack(items, stack))) + } +} + +fn contents_weight(items: &Items, inside: &[ItemStack]) -> Weight { + inside.iter().fold(Weight::ZERO, |w, s| { + w.add(item_weight(items, s).times(s.count)) + }) +} + +/// `BundleContents.canItemBeInBundle`: shulker boxes don't fit. +pub fn can_be_in_bundle(stack: &ItemStack) -> bool { + stack.count > 0 && !stack.item.ends_with("shulker_box") +} + +/// `BundleContents.Mutable`. +pub struct Contents { + items: Vec, + weight: Weight, +} + +impl Contents { + /// The bundle's contents; None when the stack is no bundle. + pub fn of(items: &Items, stack: &ItemStack) -> Option { + let inside = contents_of(items, stack)?.to_vec(); + let weight = contents_weight(items, &inside); + Some(Self { + items: inside, + weight, + }) + } + + /// `getMaxAmountToAdd` for `stack`'s kind of item. + pub fn room_for(&self, items: &Items, stack: &ItemStack) -> u32 { + Weight::ONE + .sub(self.weight) + .how_many(item_weight(items, stack)) + } + + /// `tryInsert`: what fits moves to the front, merged with its kind. + pub fn try_insert(&mut self, items: &Items, stack: &mut ItemStack) -> u32 { + if !can_be_in_bundle(stack) { + return 0; + } + let weight = item_weight(items, stack); + let amount = stack + .count + .min(Weight::ONE.sub(self.weight).how_many(weight)); + if amount == 0 { + return 0; + } + self.weight = self.weight.add(weight.times(amount)); + // ItemStack.isStackable: a damaged stack is damageable. + let stackable = max_stack(items, stack) > 1 && stack.damage == 0; + let same = self + .items + .iter() + .position(|s| stackable && s.same_item_same_components(stack)); + let added = match same { + Some(i) => { + let mut merged = self.items.remove(i); + merged.count += amount; + stack.count -= amount; + merged + } + None => { + let mut part = stack.clone(); + part.count = amount; + stack.count -= amount; + part + } + }; + self.items.insert(0, added); + amount + } + + /// `removeOne`: the first stack (Horizon keeps no selected item). + pub fn remove_one(&mut self, items: &Items) -> Option { + if self.items.is_empty() { + return None; + } + let stack = self.items.remove(0); + self.weight = self + .weight + .sub(item_weight(items, &stack).times(stack.count)); + Some(stack) + } + + /// `toImmutable`, written back into the bundle's component. + pub fn store(self, bundle: &mut ItemStack) { + bundle.data_mut().bundle_contents = self.items; + bundle.tidy(); + } +} + +#[cfg(test)] +mod tests { + use super::Weight; + + #[test] + fn weights_add_up_exactly() { + let w = Weight::new(1, 64) + .times(32) + .add(Weight::new(1, 16).times(4)); + assert_eq!(w, Weight::new(3, 4)); + assert_eq!(Weight::ONE.sub(w).how_many(Weight::new(1, 64)), 16); + assert_eq!(Weight::ONE.sub(Weight::ONE).how_many(Weight::ONE), 0); + // An over-full bundle (made by a command) has no room. + let over = Weight::ONE.sub(Weight::new(5, 4)); + assert_eq!(over.how_many(Weight::new(1, 64)), 0); + } +} diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 7c51a40f1..273b87153 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -29,10 +29,14 @@ pub struct ChatOptions { pub height_focused: f64, pub height_unfocused: f64, pub line_spacing: f64, + /// Chat Colors (`chatColors`): legacy `§` codes format the text, or are + /// left out. + pub colors: bool, } impl Default for ChatOptions { fn default() -> Self { Self { + colors: true, opacity: 1.0, background_opacity: 0.5, scale: 1.0, @@ -136,7 +140,8 @@ impl Chat { } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); - for line in atlas.font.wrap_components(&message.content, width) { + let content = self.displayed(&message.content); + for line in atlas.font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -152,6 +157,16 @@ impl Chat { } self.lines.truncate(100); } + /// What a message's lines wrap (ComponentRenderUtils.wrapComponents): + /// without Chat Colors its `§` codes are stripped (stripColor); with + /// them the font draws them as formatting. + fn displayed(&self, content: &Text) -> Text { + if self.options.colors { + content.resolve_legacy() + } else { + content.strip_legacy() + } + } /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). pub fn rescale(&mut self, atlas: &HudAtlas) { self.scroll = 0; @@ -308,6 +323,21 @@ impl Chat { x: f64, y: f64, ) -> Option { + self.style_at(font, height, x, y)?.click + } + /// The hover text under a GUI-space cursor while chat is focused + /// (ChatScreen.render's `renderComponentHoverEffect`). + pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { + self.style_at(font, height, x, y)?.hover.map(|h| *h) + } + /// ChatComponent.getClickedComponentStyleAt. + fn style_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { let scale = self.options.scale as f32; let mut x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); @@ -324,7 +354,7 @@ impl Chat { for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); if x < 0.0 { - return style.click.clone(); + return Some(style.clone()); } } None @@ -337,6 +367,14 @@ impl Chat { .map(|m| m.content.plain()) .collect() } + /// The newest messages as components, styles included (control socket). + pub fn recent_components(&self, n: usize) -> Vec { + self.messages + .iter() + .take(n) + .map(|m| m.content.component()) + .collect() + } } /// `CommandSuggestions.SuggestionsList`. diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index e1bf2feda..d0ce3f458 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -285,3 +285,45 @@ fn ask_server_nodes_wait_for_the_servers_completions() { screen.type_text(&m, &c, "/bossbar get pt"); assert_eq!(screen.take_request(), None); } + +#[test] +fn legacy_codes_colour_the_line_or_vanish_without_chat_colours() { + let mut chat = Chat::default(); + let red = Text::literal("\u{a7}cRED"); + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color == Some(0xFF5555))); + chat.options.colors = false; + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color.is_none())); + // A lone section sign or an unknown code stays as written. + assert_eq!( + chat.displayed(&Text::literal("a\u{a7}zb")).plain(), + "a\u{a7}zb" + ); +} + +#[test] +fn a_server_component_keeps_its_click_and_hover_events() { + let font = font(); + let json = serde_json::json!({ + "text": "CLICK", "color": "green", "bold": true, + "click_event": {"action": "suggest_command", "command": "/say clicked"}, + "hover_event": {"action": "show_text", "value": {"text": "Tip", "color": "aqua"}}, + }); + let line = crate::component::to_text(&json, &mut |s| Text::literal(s)); + let mut chat = Chat::default(); + add(&mut chat, &font, line); + let x = 4.0 + f64::from(font.width("CL")); + let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { + panic!("the line must suggest its command"); + }; + assert_eq!(command, "/say clicked"); + let hover = chat.hover_at(&font, 360, x, 315.0).expect("a hover text"); + assert_eq!(hover.plain(), "Tip"); + assert_eq!(hover.spans[0].style.color, Some(text::AQUA)); + // Past the (bold, so wider) text, nothing. + let past = 4.0 + f64::from(font.width("CLICK")) + 20.0; + assert!(chat.hover_at(&font, 360, past, 315.0).is_none()); +} diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 1aebf644a..27cc714bf 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -300,6 +300,10 @@ pub struct FixedStep { /// How many times `/tick step` started or stopped a step /// (`ServerTickRateManager.updateStepTicks` broadcasts each one). step_changes: u32, + /// In-frame ticks dropped since the last overload warning (`drop_ticks`). + dropped: u32, + /// When the last overload warning was due, on the frame clock. + last_overload_warning: std::time::Duration, } impl Default for FixedStep { @@ -316,6 +320,8 @@ impl Default for FixedStep { tick_count: 0, client: false, step_changes: 0, + dropped: 0, + last_overload_warning: std::time::Duration::ZERO, } } } @@ -430,6 +436,41 @@ impl FixedStep { pub fn sprinting(&self) -> bool { self.manager.is_sprinting() } + /// Whether a frame that ran its world in the frame, and whose ticks so + /// far took `spent`, may run another one. Vanilla's world ticks on the + /// integrated server's thread, so a slow tick costs its frames nothing: + /// the server falls behind and says so (`MinecraftServer.runServer`'s + /// "Can't keep up!"). In the frame, a world whose ticks take longer than + /// their length falls behind every frame, so every frame ran the client + /// timer's ten: at 57 ms a tick, 1.7 FPS. So a frame stops once its + /// ticks have taken a tick's length: ticks of a few milliseconds keep the + /// full ten, and a world that cannot keep up runs one tick a frame, + /// slower but drawn. A sprint (`/tick sprint`) runs its own frame's worth. + pub fn tick_fits(&self, spent: std::time::Duration) -> bool { + self.sprinting() || spent < self.tick_duration() + } + /// The frame skips its remaining `ticks` (`tick_fits`): the world runs + /// slower than its tick rate. Returns vanilla's overload warning when one + /// is due: a second's worth of ticks behind, at most every ten seconds + /// (`OVERLOADED_THRESHOLD_NANOS`, `OVERLOADED_WARNING_INTERVAL_NANOS`). + pub fn drop_ticks(&mut self, ticks: u32) -> Option { + self.dropped = self.dropped.saturating_add(ticks); + let tick = self.tick_duration(); + let behind = tick * self.dropped; + let threshold = std::time::Duration::from_secs(1) + tick * 20; + let interval = std::time::Duration::from_secs(10) + tick * 100; + if behind <= threshold || self.now < self.last_overload_warning + interval { + return None; + } + let warning = format!( + "Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", + behind.as_millis(), + self.dropped + ); + self.dropped = 0; + self.last_overload_warning = self.now; + Some(warning) + } /// `requestGameToSprint`: true when a sprint was already running. pub fn start_sprint(&mut self, ticks: u32) -> bool { self.manager @@ -490,6 +531,37 @@ impl FixedStep { mod tests { use super::*; + #[test] + fn a_frame_stops_ticking_after_a_ticks_length() { + let clock = FixedStep::default(); + let ms = std::time::Duration::from_millis; + // Ticks of 4 ms: the ten the timer allows fit in 50 ms. + assert!(clock.tick_fits(ms(4 * 9))); + // Ticks of 40 ms: the second one runs, not a third. + assert!(clock.tick_fits(ms(40))); + assert!(!clock.tick_fits(ms(80))); + // One tick longer than its length still runs, once a frame. + assert!(clock.tick_fits(ms(0))); + assert!(!clock.tick_fits(ms(120))); + } + #[test] + fn dropped_ticks_warn_once_a_second_behind_and_not_again_for_ten() { + let mut clock = FixedStep::default(); + let s = std::time::Duration::from_secs; + clock.now = s(20); + assert_eq!( + clock.drop_ticks(40), + None, + "two seconds: not past 1 s + 20 ticks" + ); + let warning = clock.drop_ticks(1).expect("past the threshold"); + assert!(warning.contains("2050ms or 41 ticks behind"), "{warning}"); + clock.now = s(25); + assert_eq!(clock.drop_ticks(100), None, "within ten seconds"); + clock.now = s(36); + assert!(clock.drop_ticks(0).unwrap().contains("100 ticks behind")); + } + #[test] fn timer_carries_fractions_and_caps_nothing_itself() { let mut t = Timer::new(20.0, 0); diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 68460054b..fced49898 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -168,6 +168,25 @@ fn object_style(o: &serde_json::Map) -> Style { style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); style.font = o.get("font").and_then(crate::text::font_id); + // ClickEvent.CODEC: the actions a chat line acts on here. A component + // from a server never opens a file. + if let Some(e) = o.get("click_event").and_then(Value::as_object) { + let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); + style.click = match e.get("action").and_then(Value::as_str) { + Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), + Some("copy_to_clipboard") => { + text("value").map(crate::text::ClickEvent::CopyToClipboard) + } + _ => None, + }; + } + // HoverEvent.ShowText. + if let Some(e) = o.get("hover_event").and_then(Value::as_object) + && e.get("action").and_then(Value::as_str) == Some("show_text") + && let Some(value) = e.get("value") + { + style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + } style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 02132d942..0735ce2ba 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -137,6 +137,48 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - m } +/// How `submitArmWithItem` holds a stack with a `minecraft:map_id`: in both +/// hands when it is the main hand's and the off hand is empty +/// (`renderTwoHandedMap`), else in its own hand (`renderOneHandedMap`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MapHold { + TwoHanded, + OneHanded, +} +impl MapHold { + pub fn of(hand: Hand, off_hand_empty: bool) -> Self { + if hand == Hand::Main && off_hand_empty { + Self::TwoHanded + } else { + Self::OneHanded + } + } +} + +/// `renderOneHandedMap` up to `renderMap`: the pose of a map in the hand on +/// the `left` or right arm (the arm under it is not drawn). +pub fn one_handed_map_pose(left: bool, inverse_height: f32, attack: f32) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + use horizon_core::geometry::trig::Mth; + let invert = if left { -1.0 } else { 1.0 }; + let pi = std::f32::consts::PI; + let root = attack.sqrt(); + let x_swing = (root * pi).msin(); + Mat4::from_translation(Vec3::new(invert * 0.125, -0.125, 0.0)) + * Mat4::from_translation(Vec3::new( + invert * 0.51, + -0.08 + inverse_height * -1.2, + -0.75, + )) + * Mat4::from_translation(Vec3::new( + invert * -0.5 * x_swing, + 0.4 * (root * std::f32::consts::TAU).msin() - 0.3 * x_swing, + -0.3 * (attack * pi).msin(), + )) + * Mat4::from_rotation_x((x_swing * -45.0).to_radians()) + * Mat4::from_rotation_y((invert * x_swing * -30.0).to_radians()) +} + /// `FirstPersonHandsAndItems.evaluateWhichHandsToRender`: whether the main /// and the off hand show, from what each holds (item and whether it is a /// charged crossbow) and the item in use with its hand. A bow or crossbow @@ -819,6 +861,84 @@ mod tests { mod item_pose_tests { use super::*; #[test] + fn a_map_is_two_handed_only_in_the_main_hand_with_an_empty_off_hand() { + assert_eq!(MapHold::of(Hand::Main, true), MapHold::TwoHanded); + assert_eq!(MapHold::of(Hand::Main, false), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, true), MapHold::OneHanded); + assert_eq!(MapHold::of(Hand::Off, false), MapHold::OneHanded); + } + #[test] + fn one_handed_maps_follow_render_one_handed_map() { + // PoseStack.last().pose() from vanilla's renderOneHandedMap + // transforms (column-major), for (left, inverse height, attack). + let cases: [(bool, f32, f32, [f32; 16]); 3] = [ + ( + false, + 0.0, + 0.0, + [ + 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.635, -0.205, + -0.75, 1.0, + ], + ), + ( + true, + 0.25, + 0.3, + [ + 0.86894435, + -0.34686038, + -0.35302067, + 0.0, + 0.0, + 0.713303, + -0.70085573, + 0.0, + 0.4949098, + 0.6090046, + 0.61982065, + 0.0, + -0.1406033, + -0.9197687, + -0.9926984, + 1.0, + ], + ), + ( + false, + 0.6, + 0.85, + [ + 0.9919303, + 0.024030307, + 0.12448644, + 0.0, + 0.0, + 0.9818737, + -0.18953651, + 0.0, + -0.12678458, + 0.18800701, + 0.97395027, + 0.0, + 0.5136029, + -1.1862278, + -0.88621765, + 1.0, + ], + ), + ]; + for (left, inverse_height, attack, want) in cases { + let got = one_handed_map_pose(left, inverse_height, attack).to_cols_array(); + for (g, w) in got.iter().zip(want) { + assert!( + (g - w).abs() < 1e-5, + "{left} {inverse_height} {attack}: {got:?}" + ); + } + } + } + #[test] fn ranged_draw_uses_native_charge_curves_and_caps() { for (ticks, stretch) in [ (0.0, 1.0), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0a077aa75..495c3398b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -123,6 +123,7 @@ mod raids; mod recipe_book; mod remote; mod remote_mob_data; +mod remote_mob_use; mod remote_objects; mod remote_projectiles; mod remote_stations; @@ -505,6 +506,9 @@ enum FallStep { enum GuestUse { OnBlock(Hand), Item(Hand), + /// `handleInteract`: `Player.interactOn` with the hand, nothing else (the + /// client sends UseItem itself when the entity passed). + Entity(Hand), } /// The client world as seen by the vanilla block-behaviour library. @@ -3322,6 +3326,9 @@ impl Game<'_> { // A guest's use packets name one hand and touch no entity: the client // sends one per hand and part of its click, and Interact for entities. let guest = self.guest_use; + if let Some(GuestUse::Entity(hand)) = guest { + return Ok(self.with_hand(hand, Game::interact_entity)?.then_some(hand)); + } let on_block = matches!(guest, Some(GuestUse::OnBlock(_))); if !on_block && self.riding.is_some() @@ -3330,14 +3337,7 @@ impl Game<'_> { { return Ok(Some(Hand::Main)); } - if guest.is_none() - && (self.interact_frame() - || self.interact_armor_stand() - || self.interact_boat() - || self.interact_cart() - || self.interact_mob()? - || self.interact_knot()) - { + if guest.is_none() && self.interact_entity()? { return Ok(Some(Hand::Main)); } // An EntityHitResult may fall through to Item.use, never to useItemOn. @@ -3347,16 +3347,33 @@ impl Game<'_> { self.pick() }; let hands = match guest { - Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand)) => vec![hand], + Some(GuestUse::OnBlock(hand) | GuestUse::Item(hand) | GuestUse::Entity(hand)) => { + vec![hand] + } None => Hand::BOTH.to_vec(), }; + let entity = guest.is_none() && self.entity_targeted(); for hand in hands { + // The off hand's turn starts on the entity too (Minecraft.startUseItem). + if entity && hand == Hand::Off && self.with_hand(hand, Game::interact_entity)? { + return Ok(Some(hand)); + } if self.with_hand(hand, |game| game.use_hand(block_hit.as_ref()))? { return Ok(Some(hand)); } } Ok(None) } + /// `Player.interactOn` for the entity under the crosshair with the + /// acting hand: whether it took the click. + fn interact_entity(&mut self) -> Result { + Ok(self.interact_frame() + || self.interact_armor_stand() + || self.interact_boat() + || self.interact_cart() + || self.interact_mob()? + || self.interact_knot()) + } /// One hand's turn in `startUseItem`: `useItemOn` the block aimed at, /// then `useItem`. Whether the click ends here (it acted or failed). fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result { @@ -5509,6 +5526,20 @@ impl Game<'_> { Some(true) }) } + /// A sound a menu click made the player play (a bundle's insert or + /// remove): `Entity.playSound` at the player. + pub(super) fn player_menu_sound(&mut self, sound: &str) { + let Some(p) = self.player.as_ref() else { + return; + }; + let at = [p.position.x, p.position.y, p.position.z]; + let (volume, pitch) = if sound == horizon_client::bundle::INSERT_FAIL { + (1.0, 1.0) + } else { + (0.8, 0.8 + self.world.random.next_float() * 0.4) + }; + self.audio.play(sound, Some(at), volume, pitch); + } /// The open menu as the verified engine (`horizon_client::menu`): the /// game's slots are copied in, `run` acts on it, and the slots, carried /// stack, menu data and drops are copied back when it returns Some(true) @@ -5898,6 +5929,11 @@ impl Game<'_> { let carried = menu.carried.take(); let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); + // A bundle's sounds are the player's own (`Entity.playSound`): the + // client plays them as it clicks, predicting or not. + for sound in std::mem::take(&mut menu.player_sounds) { + self.player_menu_sound(sound); + } let crafted = std::mem::take(&mut menu.crafted); let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { @@ -6142,6 +6178,17 @@ impl Game<'_> { } return; } + // mouseClicked: an empty hand's PICKUP is the menu's click at once + // (a right click on a bundle takes its first stack out). + if let (Some(input), Some(_)) = (input, slot) + && self.remote.is_none() + && self.menu_click(slot, i32::from(right), input) + { + if let Some(key) = self.container { + self.container_changed(key); + } + return; + } self.click_inventory(right); } /// Mouse movement while a quick craft drag is running. @@ -8826,20 +8873,15 @@ impl Game<'_> { ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let deg = |d: f32| d.to_radians(); - if self.held_map_geometry(to_world, attacks[0], inverse_heights[0], packed, &mut out) { - return out; - } let shown = self.hands_to_render(); let used_hand = self.used_hand(); let spinning = self .player .as_ref() .is_some_and(|p| p.auto_spin_attack_ticks > 0); - for (i, (hand, item)) in Hand::BOTH - .into_iter() - .zip(self.visible_hand_items()) - .enumerate() - { + let items = self.visible_hand_items(); + let off_hand_empty = items[1].is_none(); + for (i, (hand, item)) in Hand::BOTH.into_iter().zip(items).enumerate() { if !shown[i] { continue; } @@ -8902,6 +8944,26 @@ impl Game<'_> { ); continue; }; + if let Some(id) = maps::map_id(&stack) { + use horizon_client::first_person::{MapHold, one_handed_map_pose}; + match MapHold::of(hand, off_hand_empty) { + MapHold::TwoHanded => self.two_handed_map_geometry( + to_world, + attack, + inverse_height, + id, + packed, + &mut out, + ), + MapHold::OneHanded => self.held_map( + to_world * one_handed_map_pose(left, inverse_height, attack), + id, + packed, + &mut out, + ), + } + continue; + } let mut owner = self.player_owner(Some(&stack)); // The other hand may hold an equal stack: only the used // hand's item is in use, only the main hand's selected. @@ -11323,7 +11385,17 @@ impl ApplicationHandler for Game<'_> { // For the "I'm playing" ping: an atomic, sent on when it changes. horizon_client::heartbeat::set_lan(self.is_published()); let steps = self.clock.advance(elapsed); - for _ in 0..steps { + // The world ticking in the frame: once its ticks took a + // tick's length, the rest are dropped (`FixedStep::tick_fits`). + let in_frame = self.remote.is_none(); + let mut spent = Duration::ZERO; + for step in 0..steps { + if in_frame && !self.clock.tick_fits(spent) { + if let Some(warning) = self.clock.drop_ticks(steps - step) { + log::warn!("{warning}"); + } + break; + } let started = Instant::now(); if self.title.is_none() && !self.pause { let tick = Instant::now(); @@ -11340,6 +11412,7 @@ impl ApplicationHandler for Game<'_> { self.tick_music(); self.tick_sound_engine(); self.clock.record(started.elapsed()); + spent += started.elapsed(); if let Some(report) = self.clock.take_sprint_report() { self.sprint_report(&report); } diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 89fec4254..9305f88ad 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -685,6 +685,8 @@ impl Game<'_> { json!({ "chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)), "order": "newest first", + // The chat lines as drawn: colours, click and hover events. + "styled": self.ui.chat.recent_components(n), "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), "actionbar": (titles.overlay_time > 0).then(|| titles.overlay.as_ref().map(|t| t.plain())).flatten(), diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 6e06f21b0..f175af401 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -461,14 +461,14 @@ impl Game<'_> { count: 1, ..h.clone() }); - self.inventory[self.selected] = Some(ItemStack { + *self.held_mut() = Some(ItemStack { count: h.count - 1, ..h }); } h => { self.armor_stands[i].equipment[slot] = h; - self.inventory[self.selected] = current; + *self.held_mut() = current; } } let p = self.armor_stands[i].position; diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 0247896f5..bc2daf6ea 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -450,11 +450,11 @@ impl Game<'_> { // Connected to a server (single player's own included), the chat on // screen is the connection's: the game's own messages join it. if self.remote.is_some() { - self.chat_line(text.plain()); + self.chat_line(text); return; } let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| text.plain()); + let heard = self.mods.running().then(|| text.plain()); self.ui.chat.add( &self.gui.atlas, text, @@ -583,7 +583,7 @@ impl Game<'_> { &[Text::literal(PLAYER_NAME), Text::literal(message)], ); let focused = self.screen == Screen::Chat; - let heard = self.mods.mods.is_running().then(|| line.plain()); + let heard = self.mods.running().then(|| line.plain()); self.ui .chat .add(&self.gui.atlas, line, None, self.ticks, focused); @@ -681,6 +681,16 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + // The hovered message part's tooltip, one row per line of its text. + if let Some(hover) = self.ui.chat.hover_at( + &self.gui.atlas.font, + batch.height as i32, + f64::from(self.cursor.0), + f64::from(self.cursor.1), + ) { + let lines = hover_rows(&hover); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. @@ -949,3 +959,26 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: fn owner_permission(allow_commands: bool) -> u8 { if allow_commands { 4 } else { 0 } } + +/// A hover text's rows for the tooltip: split at line breaks, each in the +/// colour of its first styled character (white without one). +fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> { + let mut rows = vec![(String::new(), None)]; + for (c, style) in hover.resolve_legacy().chars() { + if c == '\n' { + rows.push((String::new(), None)); + continue; + } + let row = rows.last_mut().expect("one row"); + if row.0.is_empty() { + row.1 = style.color; + } + row.0.push(c); + } + rows.into_iter() + .map(|(text, color)| { + let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes(); + (text, horizon_client::hud::rgba(r, g, b, 255)) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index fb1e57ad6..c5a3fc456 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1039,6 +1039,11 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); } } + // containerMenu.broadcastChanges: InventoryChangeTrigger + // (and its announcement) comes before the command's message. + if g.player.is_some() { + g.check_inventory_trigger(); + } }); } // The prototype stack: one item. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 70a4009b8..6f47fd632 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2415,13 +2415,14 @@ impl Game<'_> { self.spawn_item(rest, self.eye_position().unwrap_or([0.0; 3]), [0.0; 3], 40); } } else { - self.inventory[self.selected] = Some(filled); + *self.held_mut() = Some(filled); } self.swing_arm(); return Ok(true); } let creative = self.creative; - let selected = self.selected; + // The hand's slot (Player.interactOn passes the hand). + let selected = self.held_slot(); if self.interact_zombie_villager(index, &item) { return Ok(true); } @@ -2453,10 +2454,10 @@ impl Game<'_> { // PiglinAi.mobInteract: hand over something gold to admire. if self.mobs[index].alive() && self.give_piglin(index, &item) { self.swing_arm(); - if !creative && let Some(stack) = self.inventory[selected].as_mut() { + if !creative && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } return Ok(true); @@ -2767,11 +2768,11 @@ impl Game<'_> { } if consume && !creative - && let Some(stack) = self.inventory[selected].as_mut() + && let Some(stack) = self.stack_in_mut(selected).as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[selected] = None; + *self.stack_in_mut(selected) = None; } } if let Some(g) = give { @@ -2781,8 +2782,8 @@ impl Game<'_> { damage: 0, extra: None, }; - if self.inventory[selected].is_none() { - self.inventory[selected] = Some(stack); + if self.stack_in(selected).is_none() { + *self.stack_in_mut(selected) = Some(stack); } else if let Some(rest) = self.give(stack) { let at = self.eye_position().unwrap_or(center); self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40); @@ -2814,13 +2815,17 @@ impl Game<'_> { if self.creative { return; } - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items().get(&stack.item) - && info.max_damage > 0 + let slot = self.held_slot(); + let max_damage = self + .held() + .and_then(|s| self.res.items().get(&s.item)) + .map_or(0, |i| i.max_damage); + if max_damage > 0 + && let Some(stack) = self.stack_in_mut(slot).as_mut() { stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + if stack.damage >= max_damage { + *self.stack_in_mut(slot) = None; } } } diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index c16c54447..cee173fda 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -237,7 +237,7 @@ impl Game<'_> { /// the caller). The top left corner gives way to the debug screen. pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { let e = &self.settings.extras; - let mod_panels = self.mods.mods.panels().next().is_some(); + let mod_panels = self.mods.has_panels(); if !e.fps && !e.keystrokes && !e.minimap && !mod_panels { return; } diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 49266a855..b387d5b4f 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -468,8 +468,10 @@ impl Game<'_> { host = self.lan.take().expect("a command puts the hub back"); self.leave_guest(&mut host, swap); host.hub.sync_all_effects(); - // A teleport into another level happens before its feedback is sent. + // A teleport into another level happens before its feedback is + // sent, and what the command earned is announced before it too. self.run_level_teleports(&mut host); + self.announce_guest_advancements(&mut host); for line in lines { out.push(line.plain()); host.hub.send_to( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bb43fe660..55975c040 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -91,7 +91,7 @@ pub(super) struct GuestCommand { conn: u32, command: String, permission: u8, - /// An integrated server's: no admin feedback or level teleports (yet). + /// An integrated server's: no level teleports (yet). integrated: bool, } @@ -164,6 +164,9 @@ impl GuestPlay { struct ItemRules<'a>(&'a horizon_client::items::Items); impl Rules for ItemRules<'_> { + fn items(&self) -> &horizon_client::items::Items { + self.0 + } fn max_stack(&self, item: &str) -> u32 { self.0.get(item).map_or(64, |i| i.max_stack) } @@ -991,9 +994,14 @@ impl Game<'_> { .look_at_entity(host, gi, p.id, Some(p.location)) .is_some() { + // handleInteract: the entity and that hand only; a click the + // entity passes comes back as UseItem. + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; let swung = self.as_guest(host, conn, |g| { + g.guest_use = Some(GuestUse::Entity(hand)); let swings = g.swings_started; let _ = g.use_item(); + g.guest_use = None; g.swings_started != swings }); self.lan_swing_back(host, conn, swung); @@ -1434,6 +1442,8 @@ impl Game<'_> { // A teleport into another level happens before its feedback is sent. self.run_level_teleports(&mut host); } + // What the command earned is announced before its feedback. + self.announce_guest_advancements(&mut host); for line in lines { host.hub.send_to( c.conn, @@ -1443,9 +1453,8 @@ impl Game<'_> { }), ); } - if !c.integrated { - self.send_admin_feedback(&mut host, Some(c.conn)); - } + // The other operators hear of it; never the player whose command it was. + self.send_admin_feedback(&mut host, Some(c.conn)); self.lan = Some(host); } } @@ -1847,7 +1856,7 @@ impl Game<'_> { /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). - fn announce_guest_advancements(&mut self, host: &mut LanHost) { + pub(super) fn announce_guest_advancements(&mut self, host: &mut LanHost) { for text in std::mem::take(&mut self.adv.announced) { host.hub .system_message(horizon_client::lan::data::component_nbt(&text.component())); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index ae5d87fff..3a5112967 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -202,10 +202,10 @@ impl Game<'_> { self.mobs[index].extra.leash = Some(Holder::Player); self.lead_sound("tied", at); // The lead is always used up. - if let Some(stack) = self.inventory[self.selected].as_mut() { + if let Some(stack) = self.held_mut().as_mut() { stack.count -= 1; if stack.count == 0 { - self.inventory[self.selected] = None; + *self.held_mut() = None; } } return true; diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index e256352ad..6da65c592 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -1189,21 +1189,17 @@ impl Game<'_> { ); } } - /// `renderTwoHandedMap`: the held map (main hand, empty off hand) in view space. - pub(super) fn held_map_geometry( + /// `renderTwoHandedMap`: map `id` held in both hands, in view space (the + /// arms under it are not drawn). + pub(super) fn two_handed_map_geometry( &mut self, to_world: glam::Mat4, attack: f32, inverse_height: f32, + id: i32, light: u32, out: &mut Vec, - ) -> bool { - let Some(id) = self.inventory[self.selected].as_ref().and_then(map_id) else { - return false; - }; - if self.offhand.is_some() { - return false; - } + ) { let deg = |d: f32| d.to_radians(); let sqrt_attack = attack.sqrt(); let y_swing = -0.2 * (attack * std::f32::consts::PI).sin(); @@ -1220,10 +1216,16 @@ impl Game<'_> { )) * glam::Mat4::from_rotation_x(deg(tilt * -85.0)); let swing = (sqrt_attack * std::f32::consts::PI).sin(); - // renderMap: background (with 7-pixel border) then the map. let m = base * glam::Mat4::from_rotation_x(deg(swing * 20.0)) - * glam::Mat4::from_scale(glam::Vec3::splat(2.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(2.0)); + self.held_map(m, id, light, out); + } + /// `renderMap`: map `id` at pose `m`, its background (with a 7-pixel + /// border) then the map. + pub(super) fn held_map(&mut self, m: glam::Mat4, id: i32, light: u32, out: &mut Vec) { + let deg = |d: f32| d.to_radians(); + let m = m * glam::Mat4::from_rotation_y(deg(180.0)) * glam::Mat4::from_rotation_z(deg(180.0)) * glam::Mat4::from_scale(glam::Vec3::splat(0.38)) @@ -1255,7 +1257,6 @@ impl Game<'_> { if has_data { self.map_vertices(id, m, light, out); } - true } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 01787ec02..572f9fe2b 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -2,43 +2,76 @@ //! their tick, frame, chat and command hooks, their HUD panels and what //! they print. With no mod on, `horizon_mods::Mods` holds no engine and //! every hook here returns after one check. -use super::{Game, Screen}; +//! +//! Code mods run only in builds with the `mods` feature (release builds): +//! without it the game links no wasmtime, and every hook does nothing. +//! Content mods (`content_root`) load in every build. +use super::Game; use horizon_client::{ command::{Dispatcher, vanilla}, - extras::Corner, - extras_hud::{self, Corners}, + extras_hud::Corners, hud::HudBatch, - mod_list::{self, Installed}, - text::{self, Text}, + mod_list, }; -use horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}; -use std::{ - path::PathBuf, - time::{Duration, Instant}, +use std::{path::PathBuf, time::Duration}; +#[cfg(feature = "mods")] +use { + super::Screen, + horizon_client::{ + extras::Corner, + extras_hud, + mod_list::Installed, + text::{self, Text}, + }, + horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status}, + std::time::Instant, }; #[derive(Default)] pub(super) struct ModsState { - pub(super) mods: Mods, + #[cfg(feature = "mods")] + mods: Mods, /// `--dev-mod PATH`: always on, reloaded when rebuilt. pub(super) dev: Vec, /// When dev mods were last checked for a rebuild. + #[cfg(feature = "mods")] checked: Option, /// The chat's command tree while a running mod owns commands. + #[cfg(feature = "mods")] tree: Option, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. pub(super) fn dispatcher(&self) -> &Dispatcher { - self.tree - .as_ref() - .unwrap_or_else(|| vanilla::game_dispatcher()) + #[cfg(feature = "mods")] + if let Some(tree) = &self.tree { + return tree; + } + vanilla::game_dispatcher() + } + /// Whether a mod runs: the chat keeps its lines for them. + pub(super) fn running(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.is_running() { + return true; + } + false + } + /// Whether a mod draws a HUD panel. + pub(super) fn has_panels(&self) -> bool { + #[cfg(feature = "mods")] + if self.mods.panels().next().is_some() { + return true; + } + false } } /// How often dev mods are checked for a rebuild. +#[cfg(feature = "mods")] const RELOAD_CHECK: Duration = Duration::from_secs(1); /// A vanilla command name: mods may not take it. +#[cfg(feature = "mods")] fn vanilla_command(name: &str) -> bool { let d = vanilla::game_dispatcher(); d.nodes[0] @@ -112,6 +145,30 @@ pub(super) fn content_root( } } +/// A build without the `mods` feature: no mod runs. +#[cfg(not(feature = "mods"))] +impl Game<'_> { + /// Says why the installed and dev mods don't run. + pub(super) fn start_mods(&mut self) { + let dir = Self::options_path().with_file_name(mod_list::DIR); + let found = horizon_mods::find(&dir).len() + self.mods.dev.len(); + if found > 0 { + log::warn!( + "Horizon: {found} mod(s) not started: this build has no mod runtime (build with --features mods)" + ); + } + } + pub(super) fn sync_mods(&mut self) {} + pub(super) fn tick_mods(&mut self) {} + pub(super) fn mods_frame(&mut self, _elapsed: Duration) {} + pub(super) fn mod_command(&mut self, _command: &str) -> bool { + false + } + pub(super) fn mods_chat(&mut self, _line: &str) {} + pub(super) fn draw_mod_panels(&self, _batch: &mut HudBatch, _corners: &mut Corners) {} +} + +#[cfg(feature = "mods")] impl Game<'_> { /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. pub(super) fn start_mods(&mut self) { diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index c10d7a458..fa4bbc209 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -104,7 +104,7 @@ impl Game<'_> { } /// `AbstractHorse.mobInteract`. Returns whether the click was used. pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool { - let held = self.inventory[self.selected].clone(); + let held = self.held().cloned(); let m = &self.mobs[index]; let species = m.species(); // A server player rides it already (`isVehicle`: no seat, no feeding). diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 4b6fd4871..d831d92f8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -38,7 +38,7 @@ use horizon_protocol::{ play::{self, Clientbound as C, Serverbound as S}, }, registry::{Builtin, DimensionType, Dynamic, ceil_log2}, - text::{Language, format_java, plain}, + text::{Language, plain}, }; use horizon_world::{ nbt::Tag, @@ -710,11 +710,14 @@ impl Game<'_> { } Some(stack) } - pub(super) fn chat_line(&mut self, text: String) { + /// A line in the connection's chat, with its styles, click and hover + /// events (ChatComponent.addMessage). + pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) { + let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( &self.gui.atlas, - horizon_client::text::Text::literal(text.clone()), + content, None, self.ticks, self.screen == Screen::Chat, @@ -2397,42 +2400,27 @@ impl Game<'_> { } } C::SystemChat(p) => { - let text = plain( - &p.content, - &self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(), - ); - // ChatListener.handleOverlay. + // The component as sent, translated in the client's own + // language. ChatListener.handleOverlay for the action bar. + let text = remote_text(&p.content); if p.overlay { - self.titles.set_overlay(remote_text(&p.content), false); + self.titles.set_overlay(text, false); } else { self.chat_line(text); } } C::PlayerChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); + use horizon_client::scoreboard::tag_to_json; let content = p .unsigned_content .as_ref() - .map_or_else(|| p.content.clone(), |t| plain(t, &lang)); - let line = self.format_chat(&p.chat_type, &content); + .map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::DisguisedChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let content = plain(&p.message, &lang); - let line = self.format_chat(&p.chat_type, &content); + let content = horizon_client::scoreboard::tag_to_json(&p.message); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::PlayerInfoUpdate(p) => { @@ -2866,11 +2854,17 @@ impl Game<'_> { true } /// ChatType decoration: `chat.translation_key` with sender/content parameters. - fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + /// ChatType.Bound.decorate: the chat type's translation, with the + /// sender, the target and the message as its parameters, in its style. + fn format_chat( + &self, + bound: &play::ChatTypeBound, + content: serde_json::Value, + ) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; let Some(r) = self.remote.as_ref() else { - return content.to_owned(); + return comp_text(&content); }; - let sender = plain(&bound.name, &r.lang); let decoration = r .registries .data("minecraft:chat_type", bound.chat_type) @@ -2879,30 +2873,31 @@ impl Game<'_> { Some(Tag::String(s)) => s.to_string_lossy(), _ => "chat.type.text".into(), }; - let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + let parameter = |name: &str| match name { + "sender" => tag_to_json(&bound.name), + "target" => bound + .target + .as_ref() + .map_or_else(|| serde_json::Value::from(""), tag_to_json), + _ => content.clone(), + }; + let with: Vec = match decoration.and_then(|d| d.get("parameters")) { Some(Tag::List(list)) => list .iter() .map(|p| match p { - Tag::String(s) => match s.to_string_lossy().as_str() { - "sender" => sender.clone(), - "target" => bound - .target - .as_ref() - .map(|t| plain(t, &r.lang)) - .unwrap_or_default(), - _ => content.to_owned(), - }, - _ => String::new(), + Tag::String(s) => parameter(&s.to_string_lossy()), + _ => serde_json::Value::from(""), }) .collect(), - _ => vec![sender, content.to_owned()], + _ => vec![parameter("sender"), parameter("content")], }; - let pattern = r - .lang - .get(&key) - .cloned() - .unwrap_or_else(|| "<%s> %s".into()); - format_java(&pattern, ¶ms) + let mut component = match decoration.and_then(|d| d.get("style")) { + Some(style @ Tag::Compound(_)) => tag_to_json(style), + _ => serde_json::json!({}), + }; + component["translate"] = key.into(); + component["with"] = with.into(); + comp_text(&component) } fn remote_item_data(&mut self, id: i32, stack: &Option) { let Some(stack) = self.to_stack(stack) else { @@ -3765,7 +3760,10 @@ impl Game<'_> { horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity); } - fn remote_use_entity(&mut self) -> bool { + /// `Minecraft.startUseItem`'s entity turn for `hand`: Interact goes to + /// the server, and whether the click ends there is what this client's + /// copy of the entity answers (`MultiPlayerGameMode.interact`). + fn remote_use_entity(&mut self, hand: Hand) -> bool { let sneaking = self.keys.contains(&KeyCode::ShiftLeft); // A boat, minecart, item frame, armor stand or painting nearer than // any mob: the server uses it (AbstractBoat.interact boards it). @@ -3773,6 +3771,10 @@ impl Game<'_> { && self.mob_hit().is_none_or(|(_, d)| hit.distance < d) && self.before_block(hit.distance) { + // The main hand's turn takes it; there is no off hand turn. + if hand == Hand::Off { + return false; + } self.send(S::Interact(play::Interact { id: hit.id, hand: 0, @@ -3788,18 +3790,18 @@ impl Game<'_> { let id = self.mobs[i].id as i32; self.send(S::Interact(play::Interact { id, - hand: 0, + hand: hand_id(hand), location: [0.0, 1.0, 0.0], secondary: sneaking, })); - // Player.interactOn: another player passes, and the held item is - // used instead (Minecraft.startUseItem). + // Player.interactOn: another player passes, and so does a mob + // the held item means nothing to: the item is used instead. let player = self .remote .as_ref() .is_some_and(|r| r.level_players.contains_key(&id)); - if !player { - self.swing_arm(); + if !player && self.remote_mob_takes(i, hand) { + self.with_hand(hand, Game::swing_arm); return true; } } @@ -4095,7 +4097,13 @@ impl Game<'_> { if self.remote_use_item(Hand::Main) { return; } - if !self.entity_targeted() && self.remote_use_block(Hand::Off) { + // The off hand's turn: the entity again, or the block. + let off_target = if self.entity_targeted() { + self.remote_use_entity(Hand::Off) + } else { + self.remote_use_block(Hand::Off) + }; + if off_target { return; } self.remote_use_item(Hand::Off); @@ -4746,7 +4754,9 @@ impl Game<'_> { self.send(S::ContainerClose(play::ContainerClose { container: p.container, })); - self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + self.chat_line(horizon_client::text::Text::literal(format!( + "(Horizon cannot show {menu} screens yet)" + ))); return; } }; @@ -5202,7 +5212,7 @@ struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>); impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_> { fn use_entity(&mut self) -> bool { - self.0.remote_use_entity() + self.0.remote_use_entity(Hand::Main) } fn use_block(&mut self) -> bool { self.0.remote_use_block(Hand::Main) diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs new file mode 100644 index 000000000..9575cf925 --- /dev/null +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -0,0 +1,91 @@ +//! A server's client right-clicking a mob: vanilla's client runs +//! `Player.interactOn` on its own level (`MultiPlayerGameMode.interact`) to +//! learn whether the click ends on the mob or goes on to the held item +//! (`Minecraft.startUseItem` then sends UseItem). The server does the real +//! interaction; this is what the client's copy of the mob answers. +use super::Game; +use horizon_client::{ + first_person::Hand, + mobs::{Species, equine, llama}, +}; + +impl Game<'_> { + /// Whether mob `i` takes a right click with `hand`'s item on this + /// client (`Mob.interact`'s result consumes the action). + pub(super) fn remote_mob_takes(&self, i: usize, hand: Hand) -> bool { + let Some(m) = self.mobs.get(i).filter(|m| m.alive()) else { + return false; + }; + let stack = match hand { + Hand::Main => self.stack_in(self.selected), + Hand::Off => self.offhand.as_ref(), + }; + let item = stack.map_or("", |s| &*s.item); + let baby = m.is_baby(); + // Mob.checkAndHandleImportantInteractions: a lead, a named name tag, + // a spawn egg of the mob's own kind. + if item == "minecraft:lead" + || item == "minecraft:name_tag" && stack.is_some_and(|s| s.custom_name().is_some()) + || item.strip_suffix("_spawn_egg") == Some(m.kind.id.as_str()) + { + return true; + } + // Animal.mobInteract: its food is CONSUME on a client. + if m.kind.flags.animal && m.kind.food.iter().any(|f| f.as_str() == item) { + return true; + } + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft); + match m.species() { + // Villager / WanderingTrader.mobInteract: trading, or a baby's head shake. + Species::Villager | Species::WanderingTrader => item != "minecraft:villager_spawn_egg", + // AbstractHorse, Camel: ridden (or their inventory opened); a baby only eats. + s if equine::is_equine(s) + || llama::is_llama(s) + || matches!(s, Species::Camel | Species::CamelHusk) => + { + !baby + } + // Pig / Strider.mobInteract: a saddled one is ridden. + Species::Pig | Species::Strider => m.extra.saddled && !sneaking, + // HappyGhast.mobInteract: a harnessed adult is ridden. + Species::HappyGhast => !baby && m.extra.head.is_some(), + // TamableAnimal (wolf, cat, parrot) on a client: CONSUME once tame. + Species::Wolf | Species::Cat | Species::Parrot => m.extra.tame, + // Allay.mobInteract: gives an item or takes it back. + Species::Allay => !item.is_empty() || m.extra.main_hand.is_some(), + Species::Cow | Species::Goat => item == "minecraft:bucket" && !baby, + Species::Mooshroom => { + matches!( + item, + "minecraft:bucket" | "minecraft:bowl" | "minecraft:shears" + ) && !baby + } + Species::Sheep => item == "minecraft:shears" || item.ends_with("_dye"), + // Bucketable.bucketMobPickup. + Species::Cod + | Species::Salmon + | Species::TropicalFish + | Species::Pufferfish + | Species::Axolotl + | Species::Tadpole => item == "minecraft:water_bucket", + Species::Armadillo => item == "minecraft:brush", + // ZombieVillager.mobInteract: CONSUME for a golden apple. + Species::ZombieVillager => item == "minecraft:golden_apple", + // Creeper.mobInteract: CREEPER_IGNITERS. + Species::Creeper => { + matches!(item, "minecraft:flint_and_steel" | "minecraft:fire_charge") + } + // PiglinAi.mobInteract: an adult admires what it loves. + Species::Piglin => { + !baby + && self + .res + .items() + .item_tags + .get("minecraft:piglin_loved") + .is_some_and(|tag| tag.contains(item)) + } + _ => false, + } + } +} diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index a501543bd..41ce50d3f 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -69,7 +69,7 @@ impl Game<'_> { } }; if let Some(r) = self.renderer.as_mut() - && let Err(e) = r.set_shader_pack(pack.as_ref()) + && let Err(e) = r.set_shader_pack(pack.as_ref(), &self.pack.render.sprite_layers) { return self.shader_pack_error(&id, &e.to_string()); } @@ -79,7 +79,10 @@ impl Game<'_> { /// Give the loaded pack to the renderer (also after it is rebuilt). pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { match self.renderer.as_mut() { - Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()), + Some(r) => r.set_shader_pack( + self.shader_packs.pack.as_ref(), + &self.pack.render.sprite_layers, + ), None => Ok(()), } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index fc217bf5c..054ed25a9 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -65,7 +65,8 @@ mod arena; mod cull; mod end_sky; mod flat; -mod java_stages; +pub(crate) mod java_stages; +pub(crate) mod java_terrain; pub mod lightning; mod lod; mod occlusion; @@ -491,6 +492,15 @@ pub struct Renderer { world_post: world_post::Post, /// The selected shader pack's stages (Horizon setting; none by default). pack: Option, + /// A Java pack's terrain programs (`gfx/java_terrain.rs`): their page + /// groups' layout, the glue's table, each arena page's group. + java_page_layout: wgpu::BindGroupLayout, + /// The device renders to and filters 16-bit normalized formats. + java_norm16: bool, + java_table: Option, + java_pages: Vec>, + /// The sprite layers and mip levels `animate` wrote this frame. + animated: Vec<(u32, u32)>, pub hud: HudRenderer, /// Vanilla's menu background blur, made on first use. menu_blur: Option, @@ -839,7 +849,10 @@ async fn open_device( | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE - | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)); + | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS + // Java shader packs' 16-bit colour targets. + | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)); let driver = format!("{} {}", info.driver, info.driver_info); startup_step(format_args!( "requesting the device (driver {}) with features [{features}] and the adapter's \ @@ -1369,8 +1382,10 @@ impl Renderer { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, + // COPY_SRC: animated sprites into a Java pack's atlas. usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::STORAGE_BINDING, view_formats: &[], }, @@ -2214,6 +2229,8 @@ impl Renderer { std::mem::size_of::() as u64, 1 << 20, ); + let java_page_layout = java_terrain::page_layout(&device); + let java_norm16 = java_terrain::norm16_targets(&adapter, &device); // Sections as one index list per frame where multi-draw is emulated. let flat = flat::wanted(&adapter, &device).then(|| { let buffers = [Some(wgpu::VertexBufferLayout { @@ -2414,6 +2431,11 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack: None, + java_page_layout, + java_norm16, + java_table: None, + java_pages: Vec::new(), + animated: Vec::new(), hud, menu_blur: None, info, @@ -2722,6 +2744,18 @@ impl Renderer { base: u32, first: u32, count: u32, + ) { + self.draw_sections_with(pass, indirect, base, first, count, |_, _| {}); + } + /// [`Self::draw_sections`]; `page` binds what else a page's draws need. + fn draw_sections_with( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + page_group: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { @@ -2731,6 +2765,7 @@ impl Renderer { .take_while(|&&p| p == (page, index_page)) .count(); pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..)); + page_group(pass, page); let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { @@ -2744,6 +2779,88 @@ impl Renderer { i += run; } } + /// Horizon's terrain, solid or `translucent`, with a Java pack's + /// geometry pipelines (`java_terrain::DrawTerrain`): the frame's flat + /// draws or its section draws, each page with its group 3. + fn draw_java_terrain( + &self, + pass: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines, + flat_frame: bool, + draws: [u32; 2], + ) { + let page = |pass: &mut wgpu::RenderPass<'_>, page: u32| { + if let Some(Some((_, group))) = self.java_pages.get(page as usize) { + pass.set_bind_group(3, group, &[]); + } + }; + pass.set_bind_group(2, pipelines.group, &[]); + match (self.flat.as_ref().filter(|_| flat_frame), pipelines.flat) { + (Some(flat), Some(pipeline)) => { + pass.set_pipeline(pipeline); + let calls = if translucent { + &flat.calls[flat.solid_calls..] + } else { + &flat.calls[..flat.solid_calls] + }; + flat.draw(pass, calls, |p| self.arena.buffer(p), page); + } + (Some(_), None) => {} + (None, _) => { + pass.set_pipeline(pipelines.instanced); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + let [solid, translucent_draws] = draws; + let (first, count) = if translucent { + (solid, translucent_draws) + } else { + (0, solid) + }; + self.draw_sections_with(pass, &self.indirect, 0, first, count, page); + } + } + } + /// Each arena page's group for a Java pack's terrain programs: its + /// vertices and the glue's table. + fn prepare_java_pages(&mut self) { + let Some(table) = &self.java_table else { + return; + }; + let count = self.arena.page_count() as usize; + self.java_pages.resize_with(count, || None); + let limit = self.device.limits().max_storage_buffer_binding_size; + for page in 0..count { + if !self.arena.has_page(page as u32) { + self.java_pages[page] = None; + continue; + } + let buffer = self.arena.buffer(page as u32); + if matches!(&self.java_pages[page], Some((b, _)) if b == buffer) { + continue; + } + let size = buffer.size().min(limit / 4 * 4); + let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack terrain page"), + layout: &self.java_page_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: 0, + size: std::num::NonZeroU64::new(size), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: table.as_entire_binding(), + }, + ], + }); + self.java_pages[page] = Some((buffer.clone(), group)); + } + } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { self.release_mesh(s); @@ -2827,9 +2944,29 @@ impl Renderer { } } /// Run `pack`'s stages over the world from now on (`None`: no pack, the - /// vanilla frame). On error the previous pack stays. - pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> { + /// vanilla frame). On error the previous pack stays. `sprite_layers` + /// names the block sprites, for a Java pack's `block.properties`. + pub fn set_shader_pack( + &mut self, + pack: Option<&crate::shader_pack::ShaderPack>, + sprite_layers: &std::collections::BTreeMap, + ) -> Result<()> { let format = self.config.format.remove_srgb_suffix(); + let layouts = java_stages::GeometryLayouts { + flat: self.flat.as_ref().map(|f| f.draw_layout()), + page: &self.java_page_layout, + }; + let table = pack.and_then(|p| p.java.as_ref()).map(|java| { + let table = java_terrain::table(sprite_layers, &java.block_ids); + wgpu::util::DeviceExt::create_buffer_init( + &self.device, + &wgpu::util::BufferInitDescriptor { + label: Some("Java shader pack terrain table"), + contents: bytemuck::cast_slice(&table), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + }, + ) + }); self.pack = match pack { Some(pack) => Some(match &pack.java { Some(java) => Pack::Java(java_stages::JavaStages::new( @@ -2838,6 +2975,8 @@ impl Renderer { format, &pack.id, java, + &layouts, + self.java_norm16, )?), None => Pack::Horizon(pack_stages::PackStages::new( &self.device, @@ -2848,6 +2987,8 @@ impl Renderer { }), None => None, }; + self.java_table = table; + self.java_pages.clear(); Ok(()) } /// The folder name of the pack `set_shader_pack` gave. @@ -2988,6 +3129,15 @@ impl Renderer { } fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) { self.animations.animate(encoder, &mut self.uploads, tick); + // A Java pack's atlas copies what changed, every level. + let levels = self.mip_levels; + self.animated.clear(); + self.animated.extend( + self.animations + .changed + .iter() + .flat_map(|&layer| (0..levels).map(move |level| (layer, level))), + ); } pub fn render(&mut self, frame: &Frame) -> Result { let rendered = self.draw_frame(frame); @@ -3272,6 +3422,12 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); + // A Java pack that draws the terrain (`gfx/java_terrain.rs`): the + // world pass leaves it out, and occlusion culling (which tests + // against its depth) is off. + let java_terrain = !frame.title + && self.java_table.is_some() + && matches!(&self.pack, Some(Pack::Java(j)) if j.draws_terrain(frame.shader.dimension)); // Occlusion culling leaves the sections its last result did not see // to phase 2, after the others, with instance counts of 0. Whether // the frame has draws enough goes by the last one's. @@ -3279,7 +3435,11 @@ impl Renderer { .cull .as_mut() .filter(|c| { - self.cull_on && !frame.title && self.multi_draw && self.section_draws >= c.min_draws + self.cull_on + && !frame.title + && self.multi_draw + && self.section_draws >= c.min_draws + && !java_terrain }) .and_then(|cull| cull.begin(&self.device).then_some(cull)); self.phase2_draws.clear(); @@ -3729,6 +3889,14 @@ impl Renderer { bytemuck::cast_slice(&self.draws), ); } + if java_terrain { + self.prepare_java_pages(); + if let Some(table) = &self.java_table { + let nether = i32::from(frame.shader.dimension == -1); + self.queue + .write_buffer(table, 4, bytemuck::bytes_of(&nether)); + } + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -3890,6 +4058,7 @@ impl Renderer { } } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.solid); let vertices = |p| self.arena.buffer(p); @@ -3897,7 +4066,12 @@ impl Renderer { // As below: phase 1, the test, then phase 2's draws // that the test saw, copied after it. Some(cull) => { - flat.draw(&mut pass, &flat.calls[..flat.phase1_calls], vertices); + flat.draw( + &mut pass, + &flat.calls[..flat.phase1_calls], + vertices, + |_, _| {}, + ); cull.test(&mut pass); drop(pass); cull.test_pass(&mut encoder); @@ -3912,7 +4086,12 @@ impl Renderer { pass.set_pipeline(&flat.solid); flat.draw_phase2(&mut pass, vertices); } - None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices), + None => flat.draw( + &mut pass, + &flat.calls[..flat.solid_calls], + vertices, + |_, _| {}, + ), } pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); @@ -4041,11 +4220,15 @@ impl Renderer { pass.set_bind_group(0, &self.group, &[]); } match self.flat.as_ref().filter(|_| flat_frame) { + _ if java_terrain => {} Some(flat) => { pass.set_pipeline(&flat.translucent); - flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { - self.arena.buffer(p) - }); + flat.draw( + &mut pass, + &flat.calls[flat.solid_calls..], + |p| self.arena.buffer(p), + |_, _| {}, + ); pass.set_bind_group(0, &self.group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); } @@ -4120,10 +4303,26 @@ impl Renderer { frame.shader.rain, ); } - if let (true, Some((color, depth)), Some(size), Some(stages)) = - (pack, &scaled, self.world_post.size(), self.pack.as_mut()) + if pack + && let (Some((color, depth)), Some(size)) = (&scaled, self.world_post.size()) + && let Some(mut stages) = self.pack.take() { - let output = match stages { + // The pack's terrain programs draw with the frame's draws. + let draws = [solid_draws, translucent_draws]; + let draw = |render: &mut wgpu::RenderPass<'_>, + translucent: bool, + pipelines: &java_terrain::TerrainPipelines| { + self.draw_java_terrain(render, translucent, pipelines, flat_frame, draws); + }; + let world = java_terrain::JavaWorld { + sprites: &self.sprite_textures, + split: sprite_split(), + levels: self.mipmaps, + animated: &self.animated, + lightmap: &self.lightmap_view, + draw: &draw, + }; + let output = match &mut stages { Pack::Horizon(stages) => stages.run( &self.device, &self.queue, @@ -4149,10 +4348,12 @@ impl Renderer { sun_angle: frame.sky.sun_angle, moon_angle: frame.sky.moon_angle, }, + java_terrain.then_some(&world), ), }; self.world_post .finish_with(&mut encoder, &view_target, output); + self.pack = Some(stages); } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } diff --git a/crates/horizon-client/src/gfx/animate.rs b/crates/horizon-client/src/gfx/animate.rs index f4528902b..b16c4af17 100644 --- a/crates/horizon-client/src/gfx/animate.rs +++ b/crates/horizon-client/src/gfx/animate.rs @@ -51,6 +51,9 @@ pub(super) struct SpriteAnimator { pipeline: wgpu::ComputePipeline, /// Edge of the arrays' layers. size: u32, + /// The sprite layers (across the arrays) the last `animate` rewrote, at + /// every mip level: a Java pack's atlas copies them. + pub changed: Vec, } impl SpriteAnimator { @@ -205,6 +208,7 @@ impl SpriteAnimator { jobs, pipeline, size, + changed: Vec::new(), } } @@ -216,6 +220,7 @@ impl SpriteAnimator { uploads: &mut Uploads, tick: u64, ) { + self.changed.clear(); if self.collect(tick) == 0 { return; } @@ -251,6 +256,7 @@ impl SpriteAnimator { continue; } sprite.shown = Some(blend); + self.changed.push(sprite.animation.layer); let job = [ sprite.layer, sprite.frames[blend.frame], diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 8da835aa2..14a264cd2 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -65,8 +65,11 @@ pub struct Arena { } impl Arena { + /// Vertices; also storage, which a Java shader pack's terrain programs + /// read a quad's corners from (`gfx/java_terrain.rs`). pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { - Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX) + let usage = wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE; + Self::with_usage(device, stride, capacity, usage) } /// Sorted translucent indices; `storage` when compute passes read them. pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self { @@ -145,6 +148,10 @@ impl Arena { pub fn page_vertices(&self) -> u64 { self.page_limit } + /// One past the last page index. + pub fn page_count(&self) -> u32 { + self.pages.len() as u32 + } pub fn has_page(&self, page: u32) -> bool { self.pages.get(page as usize).is_some_and(Option::is_some) } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index 2d0a8d27c..f6e4e2d7a 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -640,17 +640,26 @@ impl Flat { pass.set_bind_group(0, group, &[]); pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1); } + /// The bind group layout of the draws' group 1 (block slots, slot + /// origins). + pub fn draw_layout(&self) -> &wgpu::BindGroupLayout { + &self.draw_layout + } + /// Draws `calls` with a flat pipeline set and `vertices` giving each - /// page's vertex buffer. + /// page's vertex buffer; `page` binds what else a page's draws need (a + /// Java pack's terrain reads the page's vertices). pub fn draw<'a>( &self, pass: &mut wgpu::RenderPass<'_>, calls: &[Call], vertices: impl Fn(u32) -> &'a wgpu::Buffer, + page: impl Fn(&mut wgpu::RenderPass<'_>, u32), ) { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); for call in calls { self.bind_page(pass, call.page, &vertices); + page(pass, call.page); pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); } } diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index 14d25745e..ebb8acfc7 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -6,17 +6,23 @@ //! pack's terrain program draws to (`colortex0` for most packs) and //! `depthtex0` after `prepare`, where Iris's gbuffers programs would have //! drawn (`depthtex1`/`depthtex2`: its depth before translucent geometry), -//! and the last picture goes to `world_post`. The -//! targets keep GL's layout (row 0 at the bottom, which the translated vertex -//! programs produce), so the world is flipped going in and the picture coming -//! out. +//! and the last picture goes to `world_post`. The targets keep GL's layout +//! (row 0 at the bottom, which the translated vertex programs produce), so +//! the world is flipped going in and the picture coming out. +//! +//! When the pack has terrain programs (`gfx/java_terrain.rs`), Horizon's +//! world comes without its terrain: the pack's `gbuffers_terrain` draws it +//! into the pack's targets right after, against the world's depth, and its +//! `gbuffers_water` draws the translucent terrain after `deferred`, as in +//! Iris. `depthtex1` and `depthtex2` then hold the depth before it. +use super::java_terrain::{Atlas, JavaWorld, TerrainPipelines}; use super::pack_stages::{FrameUniform, noise, rgba_view}; -use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, texture_key}; +use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, blend_state, pass_blends, texture_key}; use crate::shader_pack::Rgba; use glam::{Mat3, Mat4, Vec3, Vec4}; +use horizon_shaderpack::pipeline::GeometryProgram; use horizon_shaderpack::pipeline::TargetSettings; use horizon_shaderpack::pipeline::{Directives, Program, target_index}; -use horizon_shaderpack::properties::Blend; use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -35,7 +41,7 @@ pub struct JavaFrame { /// The vertex buffers a pass may read (wgpu's default limit). const MAX_ATTRIBUTES: usize = 8; -const BLIT: &str = r#" +pub(super) const BLIT: &str = r#" @group(0) @binding(0) var color: texture_2d; @group(0) @binding(1) var depth: texture_depth_2d; @group(0) @binding(2) var opaque_depth: texture_depth_2d; @@ -54,8 +60,7 @@ struct World { // The world's colour, depth and pre-translucent depth, upside down into GL's // layout; Horizon's reversed depth (near 1) as GL's (near 0). -@fragment -fn world_in(@builtin(position) p: vec4f) -> World { +fn world_texel(p: vec4f) -> World { let size = textureDimensions(depth); let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y)); return World( @@ -65,6 +70,44 @@ fn world_in(@builtin(position) p: vec4f) -> World { ); } +@fragment +fn world_in(@builtin(position) p: vec4f) -> World { + return world_texel(p); +} + +struct WorldDepth { + @location(0) color: vec4f, + @location(1) depth: vec4f, + @location(2) opaque_depth: vec4f, + @builtin(frag_depth) test: f32, +} + +// The same, and the depth into the depth buffer the pack's geometry +// programs test against. +@fragment +fn world_in_depth(@builtin(position) p: vec4f) -> WorldDepth { + let world = world_texel(p); + return WorldDepth(world.color, world.depth, world.opaque_depth, world.depth.x); +} + +struct Depths { + @location(0) all: vec4f, + @location(1) solid: vec4f, +} + +// The depth buffer after the pack's geometry into `depthtex0` (and +// `depthtex1`, after solid terrain), both in GL's layout already. +@fragment +fn depth_out_both(@builtin(position) p: vec4f) -> Depths { + let d = vec4f(textureLoad(depth, vec2u(p.xy), 0)); + return Depths(d, d); +} + +@fragment +fn depth_out(@builtin(position) p: vec4f) -> @location(0) vec4f { + return vec4f(textureLoad(depth, vec2u(p.xy), 0)); +} + // A target, upside down back into wgpu's layout. @fragment fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { @@ -73,46 +116,13 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { } "#; -/// Convert a GL `Blend` override from `shaders.properties` into a wgpu `BlendState`. -fn blend_state(blend: &Blend) -> Option { - let Blend::Factors(factors) = blend else { - return None; - }; - let map_factor = |name: &str| -> wgpu::BlendFactor { - use wgpu::BlendFactor as B; - match name { - "ZERO" => B::Zero, - "ONE" => B::One, - "SRC_COLOR" => B::Src, - "ONE_MINUS_SRC_COLOR" => B::OneMinusSrc, - "DST_COLOR" => B::Dst, - "ONE_MINUS_DST_COLOR" => B::OneMinusDst, - "SRC_ALPHA" => B::SrcAlpha, - "ONE_MINUS_SRC_ALPHA" => B::OneMinusSrcAlpha, - "DST_ALPHA" => B::DstAlpha, - "ONE_MINUS_DST_ALPHA" => B::OneMinusDstAlpha, - "SRC_ALPHA_SATURATE" => B::SrcAlphaSaturated, - _ => B::One, - } - }; - Some(wgpu::BlendState { - color: wgpu::BlendComponent { - src_factor: map_factor(&factors[0]), - dst_factor: map_factor(&factors[1]), - operation: wgpu::BlendOperation::Add, - }, - alpha: wgpu::BlendComponent { - src_factor: map_factor(&factors[2]), - dst_factor: map_factor(&factors[3]), - operation: wgpu::BlendOperation::Add, - }, - }) -} - /// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable /// everywhere: 8-bit unsigned normalized formats stay, signed normalized, /// 16-bit and packed float ones become half floats, integer ones 32-bit. -fn target_format(iris: &str) -> wgpu::TextureFormat { +/// `norm16`: the device has 16-bit normalized formats, which keep packed +/// G-buffers (Chocapic13' packs two 8-bit values per `RGBA16` channel) +/// exact where a half float rounds them. +fn target_format(iris: &str, norm16: bool) -> wgpu::TextureFormat { use wgpu::TextureFormat as F; let channels = if iris.starts_with("RGB") || iris.contains("_B") { 4 @@ -129,6 +139,12 @@ fn target_format(iris: &str) -> wgpu::TextureFormat { match iris { "R8" | "RG8" | "RGB8" | "RGBA8" | "RGBA" | "RGBA2" | "RGBA4" | "R3_G3_B2" | "RGB5_A1" | "RGB565" => pick(F::R8Unorm, F::Rg8Unorm, F::Rgba8Unorm), + "R16" | "RG16" | "RGB16" | "RGBA16" if norm16 => { + pick(F::R16Unorm, F::Rg16Unorm, F::Rgba16Unorm) + } + "R16_SNORM" | "RG16_SNORM" | "RGB16_SNORM" | "RGBA16_SNORM" if norm16 => { + pick(F::R16Snorm, F::Rg16Snorm, F::Rgba16Snorm) + } "RGB10_A2" => F::Rgb10a2Unorm, "RGB10_A2UI" => F::Rgb10a2Uint, f if f.ends_with("32F") => pick(F::R32Float, F::Rg32Float, F::Rgba32Float), @@ -154,6 +170,14 @@ fn sample_type(format: wgpu::TextureFormat) -> wgpu::TextureSampleType { } } +/// The textures besides the targets a pass may read. +struct Views<'a> { + depth: &'a wgpu::TextureView, + depth_solid: &'a wgpu::TextureView, + atlas: Option<&'a wgpu::TextureView>, + lightmap: Option<&'a wgpu::TextureView>, +} + /// A colour target's two sides. struct Target { format: wgpu::TextureFormat, @@ -170,20 +194,32 @@ enum Source { Target(u32), /// `depthtex0` / `gdepthtex`: the world's depth (including translucent water). Depth, - /// `depthtex1` / `depthtex2`: the opaque world's depth (before translucent water). - OpaqueDepth, + /// `depthtex1` / `depthtex2`: the depth before translucent terrain: after + /// the pack's own solid terrain when it draws it, else Horizon's world's + /// before translucent water. + DepthSolid, Noise, /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); /// also Distant Horizons' and Voxy's depth, as without those mods. Shadow, /// Anything else (`shadowcolor*`, custom textures): white or black. Blank(bool), + /// In geometry programs: the block atlas (`gtexture`), the lightmap, + /// and a flat normal map for `normals` (sprites have no LabPBR maps). + Atlas, + Lightmap, + FlatNormal, } -fn source(name: &str) -> Source { +/// What sampler `name` reads, in a geometry program or a full-screen one. +fn source(name: &str, geometry: bool) -> Source { match name { + "texture" | "gtexture" | "tex" if geometry => Source::Atlas, + "lightmap" if geometry => Source::Lightmap, + "normals" if geometry => Source::FlatNormal, + "specular" if geometry => Source::Blank(false), "depthtex0" | "gdepthtex" => Source::Depth, - "depthtex1" | "depthtex2" => Source::OpaqueDepth, + "depthtex1" | "depthtex2" => Source::DepthSolid, "noisetex" => Source::Noise, "shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow, n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow, @@ -223,11 +259,48 @@ struct PassGpu { draw_buffers: Vec, reads_alt: BTreeSet, scale: f32, + /// Geometry programs: the flat draws' pipeline (where the renderer has + /// them), and the targets written on their alternate side. + flat_pipeline: Option, + geometry: Option>, +} + +/// What a pass draws into. +enum Output<'a> { + /// A full-screen pass: its targets, or for `final` the screen's format. + Screen(Option), + /// A geometry program over Horizon's terrain. + Geometry(GeometrySetup<'a>), +} + +struct GeometrySetup<'a> { + /// The vertex program for flat draws. + flat_vertex: &'a horizon_shaderpack::translate::Translated, + /// Each draw buffer's blending. + blends: &'a [Option], + layouts: &'a GeometryLayouts<'a>, +} + +/// The renderer's bind group layouts a geometry program's pipelines use: +/// the flat draws' group 1 (`gfx/flat.rs`, when it has them) and the page +/// group 3 ([`super::java_terrain::page_layout`]). +pub struct GeometryLayouts<'a> { + pub flat: Option<&'a wgpu::BindGroupLayout>, + pub page: &'a wgpu::BindGroupLayout, +} + +/// A folder's terrain and water programs. +struct FolderGeometry { + terrain: PassGpu, + water: Option, + translucent_at: usize, } /// What every pass of the pack shares. struct Common { linear: wgpu::Sampler, + /// The block atlas's, as vanilla's: nearest, mipmapped. + atlas: wgpu::Sampler, nearest: wgpu::Sampler, repeat: wgpu::Sampler, compare: wgpu::Sampler, @@ -237,6 +310,8 @@ struct Common { vertices: [wgpu::Buffer; 4], world_layout: wgpu::BindGroupLayout, present_layout: wgpu::BindGroupLayout, + /// The geometry's depth buffer, read into `depthtex0` and `depthtex1`. + depth_layout: wgpu::BindGroupLayout, blit: wgpu::ShaderModule, } @@ -248,9 +323,11 @@ struct Bound { post_generation: u64, targets: BTreeMap, depth: wgpu::TextureView, - opaque_depth: wgpu::TextureView, + /// `depthtex1`: `depth` before translucent terrain, or `depth` itself. + depth_solid: wgpu::TextureView, /// Per pass, then `final`. groups: Vec, + geometry: Option, world_in: (wgpu::RenderPipeline, wgpu::BindGroup), /// The world's target, and whether the world goes to its alternate side. world_target: u32, @@ -263,6 +340,21 @@ struct Bound { _blank: Vec, } +/// What a folder's geometry programs draw with at one size. +struct BoundGeometry { + /// The depth buffer the geometry tests against: the world's, then the + /// terrain's. + test: wgpu::TextureView, + terrain: wgpu::BindGroup, + water: Option, + /// `world_in` that also fills `test`. + world_in: wgpu::RenderPipeline, + /// `test` into `depthtex0` and `depthtex1`, and into `depthtex0` alone. + out_both: wgpu::RenderPipeline, + out: wgpu::RenderPipeline, + out_group: wgpu::BindGroup, +} + struct Folder { targets: Vec, world_at: usize, @@ -272,6 +364,7 @@ struct Folder { passes: Vec, final_pass: Option, directives: Directives, + geometry: Option, } pub struct JavaStages { @@ -292,19 +385,27 @@ pub struct JavaStages { uniform_state: UniformState, /// `eyeBrightnessSmooth`, block then sky. eye_smooth: [SmoothFloat; 2], + /// The block atlas of the geometry programs. + atlas: Option, + /// The device has 16-bit normalized formats ([`target_format`]). + norm16: bool, /// `wetness`: `rainStrength` smoothed with `wetnessHalflife` going up /// and `drynessHalflife` going down. wetness_smooth: SmoothFloat, } impl JavaStages { - /// The pipelines of a loaded Java pack, or wgpu's error. + /// The pipelines of a loaded Java pack, or wgpu's error. `norm16`: the + /// device has 16-bit normalized targets ([`target_format`]). + #[allow(clippy::too_many_arguments)] pub fn new( device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, id: &str, pack: &JavaPasses, + layouts: &GeometryLayouts, + norm16: bool, ) -> Result { let common = Common::new(device, queue, &pack.custom_textures); let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d)); @@ -316,17 +417,17 @@ impl JavaStages { let formats: Vec = plan .targets .iter() - .map(|t| target_format(&t.format)) + .map(|t| target_format(&t.format, norm16)) .collect(); let passes = plan .passes .iter() - .map(|p| PassGpu::new(device, p, &formats, None)) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(None))) .collect::, _>>()?; let final_pass = plan .final_pass .as_ref() - .map(|p| PassGpu::new(device, p, &formats, Some(format))) + .map(|p| PassGpu::new(device, p, &formats, Output::Screen(Some(format)))) .transpose()?; Ok::<_, String>(Folder { targets: plan.targets.clone(), @@ -337,6 +438,7 @@ impl JavaStages { passes, final_pass, directives: plan.directives, + geometry: folder_geometry(device, plan, &formats, layouts), }) }) .collect::, _>>()?; @@ -347,7 +449,7 @@ impl JavaStages { .iter() .flat_map(|f| f.passes.iter().chain(&f.final_pass)) .flat_map(|p| &p.samplers) - .any(|s| s.source == Source::OpaqueDepth); + .any(|s| s.source == Source::DepthSolid); Ok(Self { id: id.to_owned(), reads_opaque_depth, @@ -363,12 +465,27 @@ impl JavaStages { uniforms: pack.uniforms.clone(), uniform_state: UniformState::default(), eye_smooth: [SmoothFloat::default(); 2], + atlas: None, + norm16, wetness_smooth: SmoothFloat::default(), }) } + /// Whether the pack draws the terrain in `dimension` (0 overworld, -1 + /// the Nether, 1 the End): the renderer then leaves it out of the world + /// and gives `run` a [`JavaWorld`]. + pub fn draws_terrain(&self, dimension: i8) -> bool { + let d = i32::from(dimension).clamp(-1, 1); + let folder = self.folder_for[(d + 1) as usize].unwrap_or(0); + self.folders + .get(folder) + .is_some_and(|f| f.geometry.is_some()) + } + /// Run the passes of the world's dimension over its `color` and `depth` - /// (`size`) and return `post`'s bindings of the picture. + /// (`size`) and return `post`'s bindings of the picture. `world` is given + /// when the world was drawn without its terrain ([`Self::draws_terrain`]): + /// the pack's geometry programs draw it. #[allow(clippy::too_many_arguments)] pub fn run( &mut self, @@ -381,13 +498,24 @@ impl JavaStages { post: &super::world_post::Post, frame: FrameUniform, world: JavaFrame, + terrain: Option<&JavaWorld>, ) -> &wgpu::BindGroup { let dimension = (frame.dimension[0] as i32).clamp(-1, 1); let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0); + let terrain = terrain.filter(|_| self.folders[folder].geometry.is_some()); + if let Some(w) = terrain + && self.atlas.as_ref().is_none_or(|a| !a.fits(w)) + { + self.atlas = Atlas::new(device, queue, w); + self.bound = None; + } if self.bound.as_ref().is_none_or(|b| { - b.folder != folder || b.size != size || b.post_generation != post.generation() + b.folder != folder + || b.size != size + || b.post_generation != post.generation() + || b.geometry.is_some() != terrain.is_some() }) { - self.bound = Some(self.bind(device, queue, folder, color, depth, size, post)); + self.bound = Some(self.bind(device, queue, folder, color, depth, size, post, terrain)); } let now = std::time::Instant::now(); let frame_time = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); @@ -402,6 +530,9 @@ impl JavaStages { self.previous, ); inputs.set_world(&world, directives.sun_path_rotation); + if let Some(atlas) = &self.atlas { + inputs.atlas_size = atlas.size().map(|v| v as f32); + } let half_life = directives.eye_brightness_half_life; for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); @@ -430,15 +561,40 @@ impl JavaStages { } } } - let world_at = folder.world_at; - for (i, (pass, group)) in folder.passes.iter().zip(&bound.groups).enumerate() { + if let (Some(w), Some(atlas)) = (terrain, &mut self.atlas) { + atlas.update(device, encoder, w); + } + // The world after `prepare`, the terrain with it; translucent + // terrain after `deferred`. + let world_at = folder.world_at.min(folder.passes.len()); + let geometry = folder + .geometry + .as_ref() + .zip(bound.geometry.as_ref()) + .zip(terrain); + let translucent_at = geometry.map_or(usize::MAX, |((g, _), _)| { + g.translucent_at.min(folder.passes.len()) + }); + for i in 0..=folder.passes.len() { if i == world_at { world_in(encoder, bound); + if let Some(((g, b), w)) = geometry { + g.terrain.draw_geometry( + queue, encoder, bound, &b.terrain, &b.test, &inputs, w, false, + ); + depth_out(encoder, bound, true); + } + } + if i == translucent_at + && let Some(((g, b), w)) = geometry + && let (Some(water), Some(group)) = (&g.water, &b.water) + { + water.draw_geometry(queue, encoder, bound, group, &b.test, &inputs, w, true); + depth_out(encoder, bound, false); + } + if let (Some(pass), Some(group)) = (folder.passes.get(i), bound.groups.get(i)) { + pass.draw(queue, encoder, bound, group, &self.common, &inputs); } - pass.draw(queue, encoder, bound, group, &self.common, &inputs); - } - if folder.passes.len() <= world_at { - world_in(encoder, bound); } if let (Some(pass), Some(view)) = (&folder.final_pass, &bound.final_target) { let group = bound.groups.last().expect("final's group"); @@ -486,14 +642,19 @@ impl JavaStages { world_depth: &wgpu::TextureView, size: [u32; 2], post: &super::world_post::Post, + world: Option<&JavaWorld>, ) -> Bound { let folder = &self.folders[folder_index]; let plan = folder; let all = folder.passes.iter().chain(&folder.final_pass); + let geometry = folder.geometry.as_ref().filter(|_| world.is_some()); + let geometry_passes = geometry + .into_iter() + .flat_map(|g| std::iter::once(&g.terrain).chain(&g.water)); // Every target a pass reads or writes, colortex0 (shown without // `final`) and the world's. let mut used: BTreeSet = [0, folder.world_target].into(); - for pass in all.clone() { + for pass in all.clone().chain(geometry_passes) { used.extend(pass.draw_buffers.iter().copied()); used.extend(pass.samplers.iter().filter_map(|s| match s.source { Source::Target(i) => Some(i), @@ -524,7 +685,7 @@ impl JavaStages { .iter() .filter_map(|&i| { let settings = plan.targets.get(i as usize)?; - let format = target_format(&settings.format); + let format = target_format(&settings.format, self.norm16); let target_size = match settings.size { Some(horizon_shaderpack::pipeline::TargetSize::Relative(w, h)) if i != 0 => [ (size[0] as f32 * w).round() as u32, @@ -570,28 +731,77 @@ impl JavaStages { size, ) .create_view(&Default::default()); - let opaque_depth = texture( - "Java shader pack opaque depth", + // Written by `world_in` (Horizon's depth before translucent water), + // then by the pack's solid terrain when it draws it. + let depth_solid = texture( + "Java shader pack depth before translucent terrain", wgpu::TextureFormat::R32Float, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, size, ) .create_view(&Default::default()); + let views = Views { + depth: &depth, + depth_solid: &depth_solid, + atlas: self.atlas.as_ref().map(|a| &a.view), + lightmap: world.map(|w| w.lightmap), + }; let mut blank = Vec::new(); let groups = all .clone() - .map(|pass| { - pass.bind( - device, - queue, - &targets, - &depth, - &opaque_depth, - &self.common, - &mut blank, - ) - }) + .map(|pass| pass.bind(device, queue, &targets, &views, &self.common, &mut blank)) .collect(); + let geometry = geometry.map(|g| { + let test = texture( + "Java shader pack geometry depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()); + let r32 = wgpu::TextureFormat::R32Float; + let out_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack geometry depth"), + layout: &self.common.depth_layout, + entries: &[wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&test), + }], + }); + let mut bind = |pass: &PassGpu| { + pass.bind(device, queue, &targets, &views, &self.common, &mut blank) + }; + BoundGeometry { + terrain: bind(&g.terrain), + water: g.water.as_ref().map(&mut bind), + world_in: blit_pipeline( + device, + &self.common, + &self.common.world_layout, + "world_in_depth", + &[targets[&folder.world_target].format, r32, r32], + true, + ), + out_both: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out_both", + &[r32, r32], + false, + ), + out: blit_pipeline( + device, + &self.common, + &self.common.depth_layout, + "depth_out", + &[r32], + false, + ), + out_group, + test, + } + }); // The world goes into its target's side the gbuffers would write. let world_target = &targets[&folder.world_target]; @@ -605,6 +815,7 @@ impl JavaStages { wgpu::TextureFormat::R32Float, wgpu::TextureFormat::R32Float, ], + false, ); let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack world"), @@ -649,6 +860,7 @@ impl JavaStages { &self.common.present_layout, "present", &[self.format], + false, ); let present_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack picture"), @@ -672,8 +884,9 @@ impl JavaStages { post_generation: post.generation(), targets, depth, - opaque_depth, + depth_solid, groups, + geometry, world_in: (world_pipeline, world_group), world_target: folder.world_target, world_alt: plan.flipped_after_prepare.contains(&folder.world_target), @@ -686,6 +899,54 @@ impl JavaStages { } } +/// A folder's terrain and water programs on the GPU, or `None` (with a +/// warning: the terrain is then Horizon's) when wgpu refuses them. +fn folder_geometry( + device: &wgpu::Device, + plan: &JavaFolder, + formats: &[wgpu::TextureFormat], + layouts: &GeometryLayouts, +) -> Option { + let terrain = plan.terrain.as_ref()?; + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let gpu = |g: &GeometryProgram, blends: &[Option]| { + PassGpu::new( + device, + &g.program, + formats, + Output::Geometry(GeometrySetup { + flat_vertex: g.variants.first().unwrap_or(&g.program.vertex), + blends, + layouts, + }), + ) + }; + let made = gpu(terrain, &plan.terrain_blends).and_then(|terrain| { + let water = plan + .water + .as_ref() + .map(|w| gpu(w, &plan.water_blends)) + .transpose()?; + Ok(FolderGeometry { + terrain, + water, + translucent_at: plan.translucent_at, + }) + }); + let error = pollster::block_on(scope.pop()); + match (made, error) { + (Ok(geometry), None) => Some(geometry), + (Err(e), _) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + (_, Some(e)) => { + log::warn!("Horizon: shader pack {}: {e}", terrain.program.pass.program); + None + } + } +} + fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let target = &bound.targets[&bound.world_target]; let side = if bound.world_alt { @@ -696,18 +957,51 @@ fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let attachments = [ Some(color_attachment(side, None)), Some(color_attachment(&bound.depth, None)), - Some(color_attachment(&bound.opaque_depth, None)), + Some(color_attachment(&bound.depth_solid, None)), ]; let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Java shader pack world"), color_attachments: &attachments, + depth_stencil_attachment: bound.geometry.as_ref().map(|g| { + wgpu::RenderPassDepthStencilAttachment { + view: &g.test, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + } + }), ..Default::default() }); - render.set_pipeline(&bound.world_in.0); + match &bound.geometry { + Some(g) => render.set_pipeline(&g.world_in), + None => render.set_pipeline(&bound.world_in.0), + } render.set_bind_group(0, &bound.world_in.1, &[]); render.draw(0..3, 0..1); } +/// The geometry's depth buffer into `depthtex0`, and `depthtex1` too after +/// solid terrain. +fn depth_out(encoder: &mut wgpu::CommandEncoder, bound: &Bound, solid: bool) { + let Some(g) = &bound.geometry else { + return; + }; + let mut attachments = vec![Some(color_attachment(&bound.depth, None))]; + if solid { + attachments.push(Some(color_attachment(&bound.depth_solid, None))); + } + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack geometry depth"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(if solid { &g.out_both } else { &g.out }); + render.set_bind_group(0, &g.out_group, &[]); + render.draw(0..3, 0..1); +} + fn color_attachment( view: &wgpu::TextureView, clear: Option, @@ -732,12 +1026,15 @@ fn clear_view(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, colo }); } +/// A full-screen pipeline of `BLIT`'s `entry`; `depth`: it writes the +/// geometry's depth buffer. fn blit_pipeline( device: &wgpu::Device, common: &Common, layout: &wgpu::BindGroupLayout, entry: &str, formats: &[wgpu::TextureFormat], + depth: bool, ) -> wgpu::RenderPipeline { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Java shader pack blit"), @@ -756,7 +1053,13 @@ fn blit_pipeline( buffers: &[], }, primitive: Default::default(), - depth_stencil: None, + depth_stencil: depth.then_some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &common.blit, @@ -830,6 +1133,13 @@ impl Common { let unfilterable = wgpu::TextureSampleType::Float { filterable: false }; Self { linear: sampler(Linear, ClampToEdge, None), + atlas: device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Java shader pack block atlas"), + mag_filter: Nearest, + min_filter: Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }), nearest: sampler(Nearest, ClampToEdge, None), repeat: sampler(Linear, Repeat, None), compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)), @@ -848,6 +1158,10 @@ impl Common { label: Some("Java shader pack picture"), entries: &[texture_entry(0, unfilterable)], }), + depth_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack geometry depth"), + entries: &[texture_entry(1, wgpu::TextureSampleType::Depth)], + }), blit: device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Java shader pack blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()), @@ -890,8 +1204,12 @@ impl PassGpu { device: &wgpu::Device, program: &Program, formats: &[wgpu::TextureFormat], - screen: Option, + output: Output, ) -> Result { + let (screen, setup) = match output { + Output::Screen(screen) => (screen, None), + Output::Geometry(setup) => (None, Some(setup)), + }; let name = program.pass.program.clone(); let link = &program.link; let mut samplers = Vec::new(); @@ -924,7 +1242,7 @@ impl PassGpu { .unwrap_or_else(|| format!("{sampler}_s")); samplers.push(SamplerBinding { name: sampler.clone(), - source: source(sampler), + source: source(sampler, setup.is_some()), dimension, signed, texture: binding(&format!("{sampler}_t"))?, @@ -968,7 +1286,7 @@ impl PassGpu { )), ) } - (false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => ( + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => ( wgpu::TextureSampleType::Float { filterable: false }, Some(false), ), @@ -1017,6 +1335,9 @@ impl PassGpu { label: Some(&name), entries: &entries, }); + if let Some(setup) = setup { + return Self::geometry(device, program, formats, setup, layout, samplers, block); + } let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(&name), bind_group_layouts: &[Some(&layout)], @@ -1062,11 +1383,11 @@ impl PassGpu { // Output location `l` writes target `draw_buffers[l]` (or the screen). let outputs = &program.fragment.interface.outputs; - let pass_blend = program.pass.blend.as_ref().and_then(blend_state); + let blends = pass_blends(&program.pass, &program.draw_buffers, None); let target_states: Vec> = match screen { Some(format) => vec![Some(wgpu::ColorTargetState { format, - blend: pass_blend, + blend: program.pass.blend.as_ref().and_then(blend_state), write_mask: if outputs.contains_key(&0) { wgpu::ColorWrites::ALL } else { @@ -1087,16 +1408,9 @@ impl PassGpu { sample_type(format), wgpu::TextureSampleType::Float { filterable: true } ); - let buf_blend = program - .pass - .buffer_blends - .iter() - .find(|(idx, _)| *idx == i) - .map(|(_, b)| blend_state(b)) - .unwrap_or(pass_blend); Some(wgpu::ColorTargetState { format, - blend: if can_blend { buf_blend } else { None }, + blend: blends[l].filter(|_| can_blend), write_mask: if outputs.contains_key(&(l as u32)) { wgpu::ColorWrites::ALL } else { @@ -1161,21 +1475,164 @@ impl PassGpu { }, reads_alt: program.pass.reads_alt.clone(), scale: program.pass.scale.clamp(0.0, 1.0), + flat_pipeline: None, + geometry: None, }) } - /// The pass's bind group over `targets`. + /// A geometry program's pipelines over Horizon's terrain vertices + /// (instanced and flat draws), into its draw buffers on the side the + /// next passes read, tested against the world's depth. #[allow(clippy::too_many_arguments)] + fn geometry( + device: &wgpu::Device, + program: &Program, + formats: &[wgpu::TextureFormat], + setup: GeometrySetup, + layout: wgpu::BindGroupLayout, + samplers: Vec, + block: Option<(u32, Vec<(String, Vec)>)>, + ) -> Result { + let name = program.pass.program.clone(); + let outputs = &program.fragment.interface.outputs; + let targets: Vec> = program + .draw_buffers + .iter() + .enumerate() + .map(|(l, &i)| { + let format = formats + .get(i as usize) + .copied() + .unwrap_or(wgpu::TextureFormat::Rgba8Unorm); + let blendable = matches!( + sample_type(format), + wgpu::TextureSampleType::Float { filterable: true } + ); + Some(wgpu::ColorTargetState { + format, + blend: setup.blends.get(l).copied().flatten().filter(|_| blendable), + write_mask: if outputs.contains_key(&(l as u32)) { + wgpu::ColorWrites::ALL + } else { + wgpu::ColorWrites::empty() + }, + }) + }) + .collect(); + let vertex = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &super::TERRAIN_ATTRIBUTES, + }; + let instance_attributes = wgpu::vertex_attr_array![5 => Float32x4]; + let instance = wgpu::VertexBufferLayout { + array_stride: 16, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &instance_attributes, + }; + let fragment_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.fsh")), + source: wgpu::ShaderSource::Wgsl(program.fragment.wgsl.as_str().into()), + }); + let pipeline = |vertex_program: &horizon_shaderpack::translate::Translated, + flat: Option<&wgpu::BindGroupLayout>| { + let vertex_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&format!("{name}.vsh")), + source: wgpu::ShaderSource::Wgsl(vertex_program.wgsl.as_str().into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some(&name), + bind_group_layouts: &[None, flat, Some(&layout), Some(setup.layouts.page)], + ..Default::default() + }); + let buffers = if flat.is_some() { + vec![Some(vertex.clone())] + } else { + vec![Some(vertex.clone()), Some(instance.clone())] + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&name), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &vertex_module, + entry_point: Some("main"), + compilation_options: Default::default(), + buffers: &buffers, + }, + // The y flip into GL's layout turns the faces around. + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + front_face: wgpu::FrontFace::Cw, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &fragment_module, + entry_point: Some("main"), + compilation_options: Default::default(), + targets: &targets, + }), + multiview_mask: None, + cache: None, + }) + }; + let instanced = pipeline(&program.vertex, None); + let flat_pipeline = setup + .layouts + .flat + .map(|flat| pipeline(setup.flat_vertex, Some(flat))); + let uniform = block.as_ref().map(|(size, _)| { + ( + *size, + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack uniforms"), + size: u64::from(*size).max(16), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + ) + }); + // It reads the side the next passes read, but the other side of the + // targets it writes: wgpu can't read and write a texture at once. + let flipped = program.pass.reads_alt.clone(); + let written: BTreeSet = program.draw_buffers.iter().copied().collect(); + let reads_alt = (0..horizon_shaderpack::pipeline::MAX_COLOR_BUFFERS) + .filter(|i| flipped.contains(i) != written.contains(i)) + .collect(); + Ok(Self { + program: name, + pipeline: instanced, + layout, + samplers, + uniforms: block.map(|(_, members)| members).unwrap_or_default(), + uniform, + attributes: Vec::new(), + draw_buffers: program.draw_buffers.clone(), + reads_alt, + scale: 1.0, + flat_pipeline, + geometry: Some(flipped), + }) + } + + /// The pass's bind group over `targets` and `views`. fn bind( &self, device: &wgpu::Device, queue: &wgpu::Queue, targets: &BTreeMap, - depth: &wgpu::TextureView, - opaque_depth: &wgpu::TextureView, + textures: &Views, common: &Common, blank: &mut Vec, ) -> wgpu::BindGroup { + let depth = textures.depth; let mut views = Vec::new(); for s in &self.samplers { let custom = (!s.compare && s.dimension == wgpu::TextureViewDimension::D2) @@ -1200,10 +1657,25 @@ impl PassGpu { (false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => { depth.clone() } - (false, Source::OpaqueDepth) + (false, Source::DepthSolid) if s.dimension == wgpu::TextureViewDimension::D2 => { - opaque_depth.clone() + textures.depth_solid.clone() + } + (false, Source::Atlas) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.atlas { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::Lightmap) if s.dimension == wgpu::TextureViewDimension::D2 => { + match textures.lightmap { + Some(v) => v.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(true)), + } + } + (false, Source::FlatNormal) => { + blank_view(device, queue, blank, s, BlankKind::FlatNormal) } (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { @@ -1225,7 +1697,8 @@ impl PassGpu { (true, _) => &common.compare, _ if s.signed.is_some() => &common.nearest, (false, Source::Noise) => &common.repeat, - (false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => &common.nearest, + (false, Source::Depth | Source::DepthSolid | Source::Shadow) => &common.nearest, + (false, Source::Atlas) => &common.atlas, (false, Source::Target(i)) => { match targets.get(&i).map(|t| sample_type(t.format)) { Some(wgpu::TextureSampleType::Float { filterable: true }) | None => { @@ -1266,6 +1739,88 @@ impl PassGpu { }) } + /// This frame's values of its uniforms. + fn write_uniforms(&self, queue: &wgpu::Queue, inputs: &Inputs) { + let Some((block_size, buffer)) = &self.uniform else { + return; + }; + let mut bytes = vec![0u8; *block_size as usize]; + for (name, slots) in &self.uniforms { + if let Some(values) = inputs.value(name, self.geometry.is_some()) { + for (&(offset, int), value) in slots.iter().zip(values) { + let at = offset as usize..offset as usize + 4; + bytes[at].copy_from_slice(&if int { + (value as i32).to_ne_bytes() + } else { + value.to_ne_bytes() + }); + } + } + } + queue.write_buffer(buffer, 0, &bytes); + } + + /// A geometry program: Horizon's terrain (solid or `translucent`) into + /// its draw buffers on the side the next passes read, against `depth`. + #[allow(clippy::too_many_arguments)] + fn draw_geometry( + &self, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + bound: &Bound, + group: &wgpu::BindGroup, + depth: &wgpu::TextureView, + inputs: &Inputs, + world: &JavaWorld, + translucent: bool, + ) { + let Some(flipped) = &self.geometry else { + return; + }; + self.write_uniforms(queue, inputs); + // Targets of another size than the world's can't be drawn with it. + let size = wgpu::Extent3d { + width: bound.size[0].max(1), + height: bound.size[1].max(1), + depth_or_array_layers: 1, + }; + let attachments: Vec> = self + .draw_buffers + .iter() + .map(|i| { + let t = bound.targets.get(i).filter(|t| t.main.size() == size)?; + let side = if flipped.contains(i) { + &t.alt_view + } else { + &t.main_view + }; + Some(color_attachment(side, None)) + }) + .collect(); + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&self.program), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + (world.draw)( + &mut render, + translucent, + &TerrainPipelines { + instanced: &self.pipeline, + flat: self.flat_pipeline.as_ref(), + group, + }, + ); + } + /// Draw into the targets of `draw_buffers`, on the side it doesn't read. fn draw( &self, @@ -1311,22 +1866,7 @@ impl PassGpu { common: &Common, inputs: &Inputs, ) { - if let Some((block_size, buffer)) = &self.uniform { - let mut bytes = vec![0u8; *block_size as usize]; - for (name, slots) in &self.uniforms { - if let Some(values) = inputs.value(name) { - for (&(offset, int), value) in slots.iter().zip(values) { - let at = offset as usize..offset as usize + 4; - bytes[at].copy_from_slice(&if int { - (value as i32).to_ne_bytes() - } else { - value.to_ne_bytes() - }); - } - } - } - queue.write_buffer(buffer, 0, &bytes); - } + self.write_uniforms(queue, inputs); let attachments: Vec> = views .iter() .map(|v| v.map(|v| color_attachment(v, None))) @@ -1349,6 +1889,8 @@ impl PassGpu { enum BlankKind { Color(bool), + /// A normal map's flat normal, (0.5, 0.5, 1). + FlatNormal, /// An `R32Float` 1.0: the far plane. Far, /// A depth texture at the far plane, for comparison samplers. @@ -1371,6 +1913,7 @@ fn blank_view( wgpu::TextureFormat::Rgba8Unorm, vec![if white { 255 } else { 0 }; 4], ), + (BlankKind::FlatNormal, _) => (wgpu::TextureFormat::Rgba8Unorm, vec![128, 128, 255, 255]), (BlankKind::Far, _) => (wgpu::TextureFormat::R32Float, 1.0f32.to_ne_bytes().to_vec()), (BlankKind::FarDepth, _) => (wgpu::TextureFormat::Depth32Float, Vec::new()), }; @@ -1569,6 +2112,8 @@ struct Inputs { is_day: bool, /// The pack's custom uniforms this frame. custom: HashMap>, + /// `atlasSize`, in geometry programs. + atlas_size: [f32; 2], } /// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 @@ -1624,6 +2169,7 @@ impl Inputs { shadow_angle: 0.0, is_day: true, custom: HashMap::new(), + atlas_size: [0.0; 2], }; out.set_world(&JavaFrame::default(), 0.0); out @@ -1659,16 +2205,55 @@ impl Inputs { /// The value of uniform `name`, as its scalars in order: Iris's own, /// else the pack's custom uniform; `None` for one Horizon doesn't /// provide (it stays zero). - fn value(&self, name: &str) -> Option> { - self.builtin(name) + fn value(&self, name: &str, geometry: bool) -> Option> { + geometry + .then(|| self.geometry(name)) + .flatten() + .or_else(|| self.builtin(name)) .or_else(|| self.custom.get(name).cloned()) } + /// The uniforms whose value differs in geometry programs: the + /// camera's matrices (camera-relative positions, as Iris's terrain), + /// the lightmap's texture matrix, the atlas's size. + fn geometry(&self, name: &str) -> Option> { + let mat = |m: Mat4| m.to_cols_array().to_vec(); + Some(match name { + "iris_ModelViewMatrix" | "modelViewMatrix" => mat(self.view), + "iris_ModelViewMatrixInverse" | "modelViewMatrixInverse" => mat(self.view.inverse()), + "iris_ProjectionMatrix" | "projectionMatrix" => mat(self.projection), + "iris_ProjectionMatrixInverse" | "projectionMatrixInverse" => { + mat(self.projection.inverse()) + } + "iris_ModelViewProjectionMatrix" => mat(self.projection * self.view), + "iris_NormalMatrix" | "normalMatrix" => Mat3::from_mat4(self.view) + .inverse() + .transpose() + .to_cols_array() + .to_vec(), + // Unit 1, the lightmap: 0..240 to texel centres (Iris's + // `LIGHTMAP_TEXTURE_MATRIX`). + "iris_TextureMatrix" => { + let lightmap = Mat4::from_scale(Vec3::splat(1.0 / 256.0)) + * Mat4::from_translation(Vec3::splat(8.0)); + (0..8) + .flat_map(|i| mat(if i == 1 { lightmap } else { Mat4::IDENTITY })) + .collect() + } + "textureMatrix" => mat(Mat4::IDENTITY), + "chunkOffset" => vec![0.0; 3], + "alphaTestRef" => vec![0.1], + "atlasSize" => self.atlas_size.to_vec(), + "entityId" | "blockEntityId" | "currentRenderedItemId" => vec![-1.0], + _ => return None, + }) + } + /// The value of Iris uniform `name`; `None` for one Horizon doesn't /// provide. fn builtin(&self, name: &str) -> Option> { if let Some(flag) = name.strip_prefix("iris_bool_") { - return self.value(flag); + return self.value(flag, false); } let f = &self.frame; let mat = |m: Mat4| m.to_cols_array().to_vec(); @@ -1757,8 +2342,11 @@ mod tests { ("R32UI", F::R32Uint), ("RGBA16I", F::Rgba32Sint), ] { - assert_eq!(target_format(iris), wgpu, "{iris}"); + assert_eq!(target_format(iris, false), wgpu, "{iris}"); } + assert_eq!(target_format("RGBA16", true), F::Rgba16Unorm); + assert_eq!(target_format("RG16_SNORM", true), F::Rg16Snorm); + assert_eq!(target_format("RGBA16F", true), F::Rgba16Float); assert_eq!( sample_type(F::R32Float), wgpu::TextureSampleType::Float { filterable: false } @@ -1767,14 +2355,20 @@ mod tests { #[test] fn samplers_read_what_iris_binds() { - assert_eq!(source("colortex4"), Source::Target(4)); - assert_eq!(source("gaux1"), Source::Target(4)); - assert_eq!(source("gdepthtex"), Source::Depth); - assert_eq!(source("depthtex1"), Source::OpaqueDepth); - assert_eq!(source("shadowtex1"), Source::Shadow); - assert_eq!(source("dhDepthTex0"), Source::Shadow); - assert_eq!(source("shadowcolor0"), Source::Blank(true)); - assert_eq!(source("cloudTexture"), Source::Blank(false)); + assert_eq!(source("colortex4", false), Source::Target(4)); + assert_eq!(source("gaux1", false), Source::Target(4)); + assert_eq!(source("gdepthtex", false), Source::Depth); + assert_eq!(source("shadowtex1", false), Source::Shadow); + assert_eq!(source("dhDepthTex0", false), Source::Shadow); + assert_eq!(source("shadowcolor0", false), Source::Blank(true)); + assert_eq!(source("cloudTexture", false), Source::Blank(false)); + // Before translucent terrain; geometry programs' own textures. + assert_eq!(source("depthtex1", false), Source::DepthSolid); + assert_eq!(source("gtexture", true), Source::Atlas); + assert_eq!(source("texture", true), Source::Atlas); + assert_eq!(source("lightmap", true), Source::Lightmap); + assert_eq!(source("normals", true), Source::FlatNormal); + assert_eq!(source("colortex1", true), Source::Target(1)); let (d, signed, shadow) = sampler_kind("usampler2D").unwrap(); assert_eq!( (d, signed, shadow), @@ -1808,21 +2402,24 @@ mod tests { moon_angle: sun_angle + 180.0, }; inputs.set_world(&world(-90.0), 0.0); - close(inputs.value("sunPosition"), [100.0, 0.0, 0.0]); - close(inputs.value("moonPosition"), [-100.0, 0.0, 0.0]); - close(inputs.value("upPosition"), [0.0, 100.0, 0.0]); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.0])); - assert_eq!(inputs.value("eyeBrightness"), Some(vec![48.0, 240.0])); + close(inputs.value("sunPosition", false), [100.0, 0.0, 0.0]); + close(inputs.value("moonPosition", false), [-100.0, 0.0, 0.0]); + close(inputs.value("upPosition", false), [0.0, 100.0, 0.0]); + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.0])); + assert_eq!( + inputs.value("eyeBrightness", false), + Some(vec![48.0, 240.0]) + ); // Complementary Unbound's sunPathRotation of -40 at noon: the sun // where its GetSunVector puts it, (0, cos 40, sin 40). let tilt = (-40f32).to_radians(); inputs.set_world(&world(0.0), -40.0); close( - inputs.value("sunPosition"), + inputs.value("sunPosition", false), [0.0, 100.0 * tilt.cos(), -100.0 * tilt.sin()], ); - assert_eq!(inputs.value("sunAngle"), Some(vec![0.25])); - close(inputs.value("shadowLightPosition"), { + assert_eq!(inputs.value("sunAngle", false), Some(vec![0.25])); + close(inputs.value("shadowLightPosition", false), { let s = inputs.sun_position; [s.x, s.y, s.z] }); @@ -1830,15 +2427,15 @@ mod tests { inputs.set_world(&world(150.0), 0.0); assert!(!inputs.is_day); assert_eq!( - inputs.value("shadowLightPosition"), - inputs.value("moonPosition") + inputs.value("shadowLightPosition", false), + inputs.value("moonPosition", false) ); - assert!((inputs.value("shadowAngle").unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); + assert!((inputs.value("shadowAngle", false).unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); // Custom uniforms come after Iris's own. inputs.custom.insert("eyeBrightnessM".into(), vec![0.5]); inputs.custom.insert("sunAngle".into(), vec![9.0]); - assert_eq!(inputs.value("eyeBrightnessM"), Some(vec![0.5])); - assert_ne!(inputs.value("sunAngle"), Some(vec![9.0])); + assert_eq!(inputs.value("eyeBrightnessM", false), Some(vec![0.5])); + assert_ne!(inputs.value("sunAngle", false), Some(vec![9.0])); } #[test] @@ -1857,10 +2454,10 @@ mod tests { }; assert!((depth(near) + 1.0).abs() < 1e-4, "{}", depth(near)); assert!((depth(far) - 1.0).abs() < 1e-3, "{}", depth(far)); - assert_eq!(inputs.value("viewWidth"), Some(vec![300.0])); + assert_eq!(inputs.value("viewWidth", false), Some(vec![300.0])); assert_eq!( - inputs.value("iris_bool_hasSkylight"), - inputs.value("hasSkylight") + inputs.value("iris_bool_hasSkylight", false), + inputs.value("hasSkylight", false) ); } } diff --git a/crates/horizon-client/src/gfx/java_terrain.rs b/crates/horizon-client/src/gfx/java_terrain.rs new file mode 100644 index 000000000..6411efda1 --- /dev/null +++ b/crates/horizon-client/src/gfx/java_terrain.rs @@ -0,0 +1,645 @@ +//! Horizon's terrain drawn with a Java pack's `gbuffers_terrain` and +//! `gbuffers_water` (docs/shader-packs.md). The pack's vertex program runs +//! after a glue that rebuilds what Iris would feed it from Horizon's +//! `TerrainVertex`: the camera-relative position, the quad's normal and +//! tangent (from its four corners, read from the arena page as storage), +//! the colour without vanilla's directional shade, the lightmap +//! coordinates, the sprite's place in a block atlas laid out from Horizon's +//! sprite arrays, and `mc_Entity` from the pack's `block.properties`, by +//! sprite name. +use horizon_shaderpack::translate::Geometry; +use std::collections::BTreeMap; + +/// `TerrainVertex` in 32-bit words. +const VERTEX_WORDS: u32 = 6; + +/// The glue's declarations and `hz_vertex`; `HZ_ORIGIN_DECL` and +/// `HZ_ORIGIN` are the variant's (instanced or flat draws). +const GLUE: &str = r#" +layout(location = 0) in vec3 hz_position; +layout(location = 1) in uvec2 hz_uv; +layout(location = 2) in uint hz_layer; +layout(location = 3) in vec4 hz_color; +layout(location = 4) in uvec2 hz_light; +HZ_ORIGIN_DECL +layout(std430, set = 3, binding = 0) readonly buffer HzVertices { uint hz_vertices[]; }; +// [0]: atlas columns, [1]: 1 in the Nether, then each sprite layer's block id. +layout(std430, set = 3, binding = 1) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +vec3 hz_normal; +vec4 hz_tangent; +vec4 hz_tint; +vec2 hz_atlas; +vec2 hz_mid; +vec2 hz_lightmap; +float hz_block; +vec3 hz_mid_block; +vec3 hz_corner(uint v) { + uint b = v * HZ_WORDSu; + return vec3(uintBitsToFloat(hz_vertices[b]), uintBitsToFloat(hz_vertices[b + 1u]), + uintBitsToFloat(hz_vertices[b + 2u])); +} +vec2 hz_corner_uv(uint v) { + uint w = hz_vertices[v * HZ_WORDSu + 3u]; + return vec2(float(w & 65535u), float(w >> 16u)); +} +void hz_vertex() { + vec4 origin = HZ_ORIGIN; + hz_pos = vec4(hz_position + origin.xyz, 1.0); + // The quad's corners: quads are four vertices from a multiple of four. + uint q = uint(gl_VertexIndex) & 4294967292u; + vec3 p0 = hz_corner(q); + vec3 e1 = hz_corner(q + 1u) - p0; + vec3 e2 = hz_corner(q + 2u) - p0; + vec3 n = cross(e1, e2); + if (dot(n, n) < 1e-12) { + n = cross(e2, hz_corner(q + 3u) - p0); + } + hz_normal = dot(n, n) > 0.0 ? normalize(n) : vec3(0.0, 1.0, 0.0); + vec2 t0 = hz_corner_uv(q); + vec2 d1 = hz_corner_uv(q + 1u) - t0; + vec2 d2 = hz_corner_uv(q + 2u) - t0; + float s = d1.x * d2.y - d2.x * d1.y < 0.0 ? -1.0 : 1.0; + vec3 t = (e1 * d2.y - e2 * d1.y) * s; + vec3 b = (e2 * d1.x - e1 * d2.x) * s; + t = t - hz_normal * dot(hz_normal, t); + t = dot(t, t) > 0.0 ? normalize(t) : vec3(1.0, 0.0, 0.0); + hz_tangent = vec4(t, dot(cross(hz_normal, t), b) < 0.0 ? -1.0 : 1.0); + // Iris turns vanilla's directional shade off: undo it on axis faces. + vec3 a = abs(hz_normal); + bool nether = hz_table[1] != 0; + float shade = 1.0; + if (a.y > 0.999) { + shade = nether ? 0.9 : (hz_normal.y > 0.0 ? 1.0 : 0.5); + } else if (a.z > 0.999) { + shade = 0.8; + } else if (a.x > 0.999) { + shade = 0.6; + } + hz_tint = vec4(min(hz_color.rgb / shade, vec3(1.0)), hz_color.a); + // The sprite's cell in the atlas, columns of square cells. + int layer = int(hz_layer & 16383u); + int cols = max(hz_table[0], 1); + vec2 cell = vec2(float(layer % cols), float(layer / cols)); + vec2 uv = clamp(vec2(hz_uv) * origin.w, 0.0, 1.0); + hz_atlas = (cell + uv) / float(cols); + hz_mid = (cell + 0.5) / float(cols); + // Vanilla's UV2: block light, then sky light, 0..240. + hz_lightmap = vec2(float(hz_light.y), float(hz_light.x)); + hz_block = float(hz_table[2 + layer]); + hz_mid_block = (floor(hz_position - hz_normal * 0.01) + 0.5 - hz_position) * 64.0; +} +"#; + +/// The glue of one draw path: instanced section draws (the origin is an +/// instance attribute) or flat ones (`gfx/flat.rs`: from the block's slot). +pub fn glue(flat: bool, alpha_test: Option) -> Geometry { + let (decl, origin) = if flat { + ( + "layout(std430, set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\ + layout(std430, set = 1, binding = 1) readonly buffer HzSlotOrigins { vec4 hz_slot_origins[]; };", + "hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]", + ) + } else { + ("layout(location = 5) in vec4 hz_origin;", "hz_origin") + }; + let vertex_glue = GLUE + .replace("HZ_ORIGIN_DECL", decl) + .replace("HZ_ORIGIN", origin) + .replace("HZ_WORDS", &VERTEX_WORDS.to_string()); + let lightmap = "vec4(hz_lightmap, 0.0, 1.0)"; + let attributes: BTreeMap = [ + ("iris_Vertex", "hz_pos"), + ("vaPosition", "hz_pos"), + ("iris_Normal", "vec4(hz_normal, 0.0)"), + ("vaNormal", "vec4(hz_normal, 0.0)"), + ("iris_Color", "hz_tint"), + ("vaColor", "hz_tint"), + ("iris_MultiTexCoord0", "vec4(hz_atlas, 0.0, 1.0)"), + ("vaUV0", "vec4(hz_atlas, 0.0, 1.0)"), + ("iris_MultiTexCoord1", lightmap), + ("iris_MultiTexCoord2", lightmap), + ("vaUV2", lightmap), + // OverlayTexture.NO_OVERLAY. + ("vaUV1", "vec4(0.0, 10.0, 0.0, 0.0)"), + ("mc_Entity", "vec4(hz_block, -1.0, 0.0, 0.0)"), + ("mc_midTexCoord", "vec4(hz_mid, 0.0, 1.0)"), + ("at_tangent", "hz_tangent"), + ("at_midBlock", "vec4(hz_mid_block, 0.0)"), + ] + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + Geometry { + vertex_glue, + attributes, + alpha_test, + } +} + +/// The glue's table: atlas columns, the Nether flag, then each sprite +/// layer's block id from `block.properties` (-1 for blocks it doesn't +/// list, as Iris). +pub fn table(sprite_layers: &BTreeMap, block_ids: &BTreeMap) -> Vec { + let layers = sprite_layers.values().max().map_or(0, |&m| m as usize + 1); + let mut out = vec![-1; layers + 2]; + out[0] = atlas_columns(layers as u32) as i32; + out[1] = 0; + for (name, &layer) in sprite_layers { + if let Some(id) = horizon_shaderpack::properties::sprite_block_id(name, block_ids) { + out[layer as usize + 2] = id; + } + } + out +} + +/// The atlas's columns (and rows) of sprite cells for `layers` sprites. +pub fn atlas_columns(layers: u32) -> u32 { + (f64::from(layers.max(1)).sqrt().ceil() as u32).max(1) +} + +/// Whether `device` renders to and filters the 16-bit normalized formats +/// a Java pack's `RGBA16` targets become (`java_stages::target_format`). +pub fn norm16_targets(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + use wgpu::TextureFormat as F; + let wanted = wgpu::Features::TEXTURE_FORMAT_16BIT_NORM + | wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES; + device.features().contains(wanted) + && [ + F::R16Unorm, + F::Rg16Unorm, + F::Rgba16Unorm, + F::R16Snorm, + F::Rg16Snorm, + F::Rgba16Snorm, + ] + .into_iter() + .all(|f| { + let features = adapter.get_texture_format_features(f); + features + .allowed_usages + .contains(wgpu::TextureUsages::RENDER_ATTACHMENT) + && features + .flags + .contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) + }) +} + +/// The bind group layout of a page group: the page's vertices and the glue's +/// table, read by the vertex stage. +pub fn page_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout { + let storage = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack terrain page"), + entries: &[storage(0), storage(1)], + }) +} + +/// Draws Horizon's terrain with a pack's pipelines: the solid layer or the +/// translucent one. Set by the renderer, which owns the sections. +pub type DrawTerrain<'a> = dyn Fn(&mut wgpu::RenderPass<'_>, bool, &TerrainPipelines<'_>) + 'a; + +/// What the renderer binds to draw with a pack's geometry program: the +/// pipeline of its draw path and the pack's group (group 2). Group 1 is the +/// flat path's, group 3 the page's ([`page_layout`]). `flat` is `None` when +/// the renderer has no flat draws. +pub struct TerrainPipelines<'a> { + pub instanced: &'a wgpu::RenderPipeline, + pub flat: Option<&'a wgpu::RenderPipeline>, + pub group: &'a wgpu::BindGroup, +} + +/// What a Java pack's geometry reads from the renderer each frame. +pub struct JavaWorld<'a> { + /// The block sprite arrays, [`super::SPRITE_SPLIT`]-layer each. + pub sprites: &'a [wgpu::Texture], + pub split: u32, + /// Mipmap levels the terrain samples. + pub levels: u32, + /// The sprite layers and mip levels animation rewrote this frame. + pub animated: &'a [(u32, u32)], + pub lightmap: &'a wgpu::TextureView, + pub draw: &'a DrawTerrain<'a>, +} + +const ATLAS: &str = r#" +struct Atlas { cols: u32, layers: u32, split: u32, pad: u32 } +@group(0) @binding(0) var atlas: Atlas; +@group(0) @binding(1) var s0: texture_2d_array; +@group(0) @binding(2) var s1: texture_2d_array; +@group(0) @binding(3) var s2: texture_2d_array; +@group(0) @binding(4) var s3: texture_2d_array; +@group(0) @binding(5) var s4: texture_2d_array; +@group(0) @binding(6) var s5: texture_2d_array; +@group(0) @binding(7) var s6: texture_2d_array; +@group(0) @binding(8) var s7: texture_2d_array; + +struct Out { + @builtin(position) p: vec4f, + @location(0) @interpolate(flat) mip: u32, +} + +@vertex +fn vs(@builtin(vertex_index) i: u32, @builtin(instance_index) mip: u32) -> Out { + let uv = vec2f(f32((i << 1u) & 2u), f32(i & 2u)); + return Out(vec4f(uv * 2.0 - 1.0, 0.0, 1.0), mip); +} + +// Each sprite layer into its cell, at mip level `mip`. +@fragment +fn fs(in: Out) -> @location(0) vec4f { + let cell = max(textureDimensions(s0, in.mip).x, 1u); + let px = vec2u(in.p.xy); + let c = px / cell; + let layer = c.y * atlas.cols + c.x; + if c.x >= atlas.cols || layer >= atlas.layers { + return vec4f(0.0); + } + let at = px % cell; + let l = i32(layer % atlas.split); + let m = i32(in.mip); + switch layer / atlas.split { + case 0u: { return textureLoad(s0, at, l, m); } + case 1u: { return textureLoad(s1, at, l, m); } + case 2u: { return textureLoad(s2, at, l, m); } + case 3u: { return textureLoad(s3, at, l, m); } + case 4u: { return textureLoad(s4, at, l, m); } + case 5u: { return textureLoad(s5, at, l, m); } + case 6u: { return textureLoad(s6, at, l, m); } + default: { return textureLoad(s7, at, l, m); } + } +} +"#; + +/// Horizon's block sprites as one 2D atlas, as Iris binds `gtexture`: +/// square cells, [`atlas_columns`] to a row. Drawn from the sprite arrays +/// once, then animated sprites are copied in as they change. +pub struct Atlas { + texture: wgpu::Texture, + pub view: wgpu::TextureView, + mips: Vec, + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + uniform: wgpu::Buffer, + /// Layers, sprite size, mip levels it was made for. + key: (u32, u32, u32), + /// The first sprite array it was drawn from (resource reloads make + /// new ones). + source: wgpu::Texture, + drawn: bool, +} + +impl Atlas { + /// The atlas for `world`'s sprites; `None` without any. + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, world: &JavaWorld) -> Option { + let key = Self::key(world)?; + let (layers, size, levels) = key; + let cols = atlas_columns(layers); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Java shader pack block atlas"), + size: wgpu::Extent3d { + width: cols * size, + height: cols * size, + depth_or_array_layers: 1, + }, + mip_level_count: levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let mips = (0..levels) + .map(|level| { + texture.create_view(&wgpu::TextureViewDescriptor { + base_mip_level: level, + mip_level_count: Some(1), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }]; + entries.extend((1..=8).map(|binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2Array, + multisampled: false, + }, + count: None, + })); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Java shader pack block atlas"), + entries: &entries, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Java shader pack block atlas"), + source: wgpu::ShaderSource::Wgsl(ATLAS.into()), + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Java shader pack block atlas"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Java shader pack block atlas"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }), + ), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], + }), + multiview_mask: None, + cache: None, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Java shader pack block atlas"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer( + &uniform, + 0, + bytemuck::cast_slice(&[cols, layers, world.split.max(1), 0]), + ); + Some(Self { + view: texture.create_view(&Default::default()), + texture, + mips, + pipeline, + layout, + uniform, + key, + source: world.sprites[0].clone(), + drawn: false, + }) + } + + fn key(world: &JavaWorld) -> Option<(u32, u32, u32)> { + let first = world.sprites.first()?; + let layers = world + .sprites + .iter() + .map(|t| t.depth_or_array_layers()) + .sum(); + let levels = (world.levels + 1).min(first.mip_level_count()).max(1); + Some((layers, first.width(), levels)) + } + + /// Whether it was made for `world`'s sprites. + pub fn fits(&self, world: &JavaWorld) -> bool { + Self::key(world) == Some(self.key) && world.sprites.first() == Some(&self.source) + } + + /// Bring it up to date: drawn the first time, then the sprites + /// animation rewrote copied into their cells. + pub fn update( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + world: &JavaWorld, + ) { + if !self.drawn { + self.draw(device, encoder, world); + self.drawn = true; + return; + } + let (layers, size, levels) = self.key; + let cols = atlas_columns(layers); + let split = world.split.max(1); + for &(layer, level) in world.animated { + let Some(array) = world.sprites.get((layer / split) as usize) else { + continue; + }; + if level >= levels || layer >= layers { + continue; + } + let edge = (size >> level).max(1); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: array, + mip_level: level, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: layer % split, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &self.texture, + mip_level: level, + origin: wgpu::Origin3d { + x: (layer % cols) * edge, + y: (layer / cols) * edge, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { + width: edge, + height: edge, + depth_or_array_layers: 1, + }, + ); + } + } + + /// The atlas's size in pixels (`atlasSize`). + pub fn size(&self) -> [u32; 2] { + [self.texture.width(), self.texture.height()] + } + + /// Draw the sprites into the atlas, every mip level. + fn draw(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, world: &JavaWorld) { + let views: Vec = (0..8) + .map(|i| { + let t = world.sprites.get(i).unwrap_or(&world.sprites[0]); + t.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::D2Array), + mip_level_count: Some(self.key.2), + ..Default::default() + }) + }) + .collect(); + let mut entries = vec![wgpu::BindGroupEntry { + binding: 0, + resource: self.uniform.as_entire_binding(), + }]; + entries.extend(views.iter().enumerate().map(|(i, v)| wgpu::BindGroupEntry { + binding: i as u32 + 1, + resource: wgpu::BindingResource::TextureView(v), + })); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Java shader pack block atlas"), + layout: &self.layout, + entries: &entries, + }); + for (mip, view) in self.mips.iter().enumerate() { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Java shader pack block atlas"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..3, mip as u32..mip as u32 + 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `module` validates and translates for Metal, Vulkan and DirectX 12. + fn backends(module: &naga::Module, label: &str) { + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(module) + .unwrap_or_else(|e| panic!("{label}: {e:?}")); + naga::back::msl::write_string( + module, + &info, + // wgpu's Metal backend asks for MSL 2.x. + &naga::back::msl::Options { + lang_version: (2, 4), + ..Default::default() + }, + &naga::back::msl::PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{label} (MSL): {e}")); + naga::back::spv::write_vec(module, &info, &Default::default(), None) + .unwrap_or_else(|e| panic!("{label} (SPIR-V): {e}")); + for entry in &module.entry_points { + let mut hlsl = String::new(); + naga::back::hlsl::Writer::new( + &mut hlsl, + &naga::back::hlsl::Options::default(), + &naga::back::hlsl::PipelineOptions { + entry_point: Some((entry.stage, entry.name.clone())), + }, + ) + .write(module, &info, None) + .unwrap_or_else(|e| panic!("{label} {} (HLSL): {e}", entry.name)); + } + } + + /// A terrain program reading every attribute the glue fills, run after + /// each draw path's glue, and the atlas shader, on every backend. + #[test] + fn the_glue_feeds_a_terrain_program_on_every_backend() { + let program = "#version 120 +attribute vec4 mc_Entity; +attribute vec4 mc_midTexCoord; +attribute vec4 at_tangent; +attribute vec3 at_midBlock; +varying vec4 color; +varying vec2 uv; +varying vec2 lm; +varying vec3 normal; +varying float id; +void main() { + vec4 p = gl_ModelViewMatrix * gl_Vertex; + p.xyz += at_midBlock / 64.0 * 0.0 + at_tangent.xyz * 0.0; + gl_Position = gl_ProjectionMatrix * p; + color = gl_Color; + uv = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy + mc_midTexCoord.xy * 0.0; + lm = (gl_TextureMatrix[1] * gl_MultiTexCoord1).xy; + normal = gl_NormalMatrix * gl_Normal; + id = mc_Entity.x; +} +"; + for flat in [false, true] { + let mut link = horizon_shaderpack::translate::Link { + set: 2, + geometry: Some(glue(flat, Some(0.1))), + ..Default::default() + }; + let t = horizon_shaderpack::translate::translate( + horizon_shaderpack::Stage::Vertex, + program, + &mut link, + &|l| format!("line {l}"), + ) + .unwrap_or_else(|e| panic!("flat {flat}: {e}")); + for wanted in ["hz_vertex();", "mc_Entity = vec4(vec4(hz_block"] { + assert!(t.glsl.contains(wanted), "{wanted}\n{}", t.glsl); + } + // The glue's inputs are Horizon's vertex layout. + let inputs = t.module.entry_points[0].function.arguments.len(); + assert_eq!(inputs, if flat { 6 } else { 7 }, "{}", t.wgsl); + let reparsed = naga::front::wgsl::parse_str(&t.wgsl).unwrap(); + backends(&reparsed, &format!("terrain glue (flat {flat})")); + } + backends(&naga::front::wgsl::parse_str(ATLAS).unwrap(), "atlas"); + backends( + &naga::front::wgsl::parse_str(super::super::java_stages::BLIT).unwrap(), + "Java shader pack blits", + ); + } + + #[test] + fn sprites_take_their_blocks_ids() { + let layers: BTreeMap = [ + ("minecraft:block/oak_leaves", 0), + ("minecraft:block/water_still", 1), + ("minecraft:block/stone", 2), + ("minecraft:block/oak_log_top", 3), + ] + .into_iter() + .map(|(n, l)| (n.to_owned(), l)) + .collect(); + let ids: BTreeMap = [("oak_leaves", 10003), ("water", 8), ("oak_log", 7)] + .into_iter() + .map(|(n, i)| (n.to_owned(), i)) + .collect(); + assert_eq!(table(&layers, &ids), [2, 0, 10003, 8, -1, 7]); + assert_eq!(atlas_columns(5), 3); + assert_eq!(atlas_columns(0), 1); + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index ab9c98804..abbc1241f 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -120,6 +120,8 @@ pub struct ItemInfo { pub dye: Option, /// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks. pub block_transformer: Option, + /// Has a default `bundle_contents` (the bundles, `BundleItem`). + pub bundle: bool, } /// `Item.Properties.craftRemainder` (not a data component, so not in the /// default-component report): what an item leaves in the grid when crafted with. @@ -593,6 +595,7 @@ impl Items { jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned), dye: c["minecraft:dye"].as_str().map(str::to_owned), block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned), + bundle: c.get("minecraft:bundle_contents").is_some(), crafting_remainder: CRAFT_REMAINDERS .iter() .find(|(item, _)| *item == name) diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index d8873e25c..349aa188e 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -2,13 +2,14 @@ //! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates //! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`, //! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world -//! as Iris runs them over its own. Geometry programs (`gbuffers_*`, -//! `shadow`) don't run yet: the world is drawn by Horizon. +//! as Iris runs them over its own. Of the geometry programs, the terrain's +//! (`gbuffers_terrain`, `gbuffers_water` and their fallbacks) draw Horizon's +//! terrain (`gfx/java_terrain.rs`); the rest of the world is Horizon's. use horizon_shaderpack::{ JavaPack, - pipeline::{Directives, Program, TargetSettings}, + pipeline::{Directives, GeometryProgram, Pass, Program, TargetSettings}, preprocess::Environment, - properties::SkyDirectives, + properties::{Blend, SkyDirectives}, uniforms::CustomUniforms, }; use std::{ @@ -36,6 +37,17 @@ pub struct JavaFolder { /// `sunPathRotation`, `eyeBrightnessHalflife`, `wetnessHalflife` and /// `drynessHalflife`. pub directives: Directives, + /// The programs Horizon's solid and translucent terrain are drawn with, + /// each translated for instanced and flat draws (`variants[0]`). + pub terrain: Option, + pub water: Option, + /// How many of `passes` run before translucent terrain (`begin*`, + /// `prepare*`, `deferred*`). + pub translucent_at: usize, + pub flipped_after_translucent: BTreeSet, + /// Each draw buffer's blending in `terrain` and `water`. + pub terrain_blends: Vec>, + pub water_blends: Vec>, } /// The key of `texture.noise` (`noisetex`) in [`JavaPasses::custom_textures`]. @@ -60,6 +72,8 @@ pub struct JavaPasses { pub uniforms: CustomUniforms, /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). pub sky: SkyDirectives, + /// `block.properties`: block name → `mc_Entity` id. + pub block_ids: BTreeMap, /// `texture..` and `texture.noise` images, by /// `"."` and [`NOISE_KEY`]. pub custom_textures: BTreeMap, @@ -144,6 +158,45 @@ pub fn load( if passes.is_empty() && final_pass.is_none() { continue; } + // A geometry program that doesn't translate leaves that terrain to + // Horizon, with a warning. + let geometry = |pass: &Option, alpha_test| { + let pass = pass.as_ref()?; + let glues = [false, true].map(|flat| crate::gfx::java_terrain::glue(flat, alpha_test)); + match pack.compile_geometry(pass, &plan.targets, &values, &env, &properties, &glues) { + Ok(program) => Some(program), + Err(e) => { + log::warn!("Horizon: shader pack {}: {e}", pass.program); + None + } + } + }; + // Iris's alpha test of cutout terrain (`AlphaTests.ONE_TENTH_ALPHA`). + let terrain = geometry(&plan.terrain, Some(0.1)); + let water = terrain.as_ref().and_then(|_| geometry(&plan.water, None)); + let translucent_at = early.clone().count() + plan.deferred.len(); + let blends = |g: &Option, default| { + g.as_ref().map_or_else(Vec::new, |g| { + pass_blends(&g.program.pass, &g.program.draw_buffers, default) + }) + }; + let terrain_blends = blends(&terrain, None); + // Vanilla's translucent blending (`BlendFunction.TRANSLUCENT`). + let water_blends = blends( + &water, + Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + ); folders.push(JavaFolder { folder: name.to_owned(), targets: plan.targets, @@ -154,6 +207,12 @@ pub fn load( final_pass, flipped_at_end: plan.flipped_at_end, directives: plan.directives, + terrain, + water, + translucent_at, + flipped_after_translucent: plan.flipped_after_translucent, + terrain_blends, + water_blends, }); } if folders.is_empty() { @@ -184,11 +243,69 @@ pub fn load( for problem in &uniforms.problems { log::warn!("Horizon: shader pack custom uniform {problem}"); } + let block_ids = pack.block_ids(&values, &env).unwrap_or_else(|e| { + log::warn!("Horizon: shader pack {e}"); + BTreeMap::new() + }); Ok(JavaPasses { folders, uniforms, sky: properties.sky(), custom_textures, + block_ids, + }) +} + +/// Each draw buffer's blending, as Iris's `BlendModeOverride`: +/// `blend..`, else `blend.`, else `default` +/// (none for full-screen passes, vanilla's for the geometry programs). +pub(crate) fn pass_blends( + pass: &Pass, + draw_buffers: &[u32], + default: Option, +) -> Vec> { + let all = pass.blend.as_ref().map_or(default, blend_state); + draw_buffers + .iter() + .map(|i| { + pass.buffer_blends + .iter() + .find(|(b, _)| b == i) + .map_or(all, |(_, b)| blend_state(b)) + }) + .collect() +} + +/// A `blend.*` value as wgpu's blending (`off`: none). The factors are the +/// GL ones `ShaderProperties` accepts. +pub(crate) fn blend_state(blend: &Blend) -> Option { + let Blend::Factors(factors) = blend else { + return None; + }; + let factor = |name: &str| { + use wgpu::BlendFactor as F; + match name { + "ZERO" => F::Zero, + "SRC_COLOR" => F::Src, + "ONE_MINUS_SRC_COLOR" => F::OneMinusSrc, + "DST_COLOR" => F::Dst, + "ONE_MINUS_DST_COLOR" => F::OneMinusDst, + "SRC_ALPHA" => F::SrcAlpha, + "ONE_MINUS_SRC_ALPHA" => F::OneMinusSrcAlpha, + "DST_ALPHA" => F::DstAlpha, + "ONE_MINUS_DST_ALPHA" => F::OneMinusDstAlpha, + "SRC_ALPHA_SATURATE" => F::SrcAlphaSaturated, + _ => F::One, + } + }; + let component = |src: &str, dst: &str| wgpu::BlendComponent { + src_factor: factor(src), + dst_factor: factor(dst), + operation: wgpu::BlendOperation::Add, + }; + Some(wgpu::BlendState { + color: component(&factors[0], &factors[1]), + alpha: component(&factors[2], &factors[3]), }) } @@ -242,8 +359,18 @@ mod tests { .folders .iter() .flat_map(|f| f.passes.iter().chain(&f.final_pass)); + let geometry = pack + .folders + .iter() + .flat_map(|f| f.terrain.iter().chain(&f.water)); passes .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) + .chain(geometry.flat_map(|g| { + let p = &g.program; + [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")] + .into_iter() + .chain(g.variants.iter().map(move |v| (p, v, "vsh (flat)"))) + })) .find_map(|(p, t, ext)| { let e = naga::front::wgsl::parse_str(&t.wgsl).err()?; Some(format!( @@ -283,7 +410,13 @@ mod tests { .iter() .map(|f| { let n = f.passes.len() + usize::from(f.final_pass.is_some()); - format!("{} {n} passes", f.folder) + let geometry: Vec<&str> = f + .terrain + .iter() + .chain(&f.water) + .map(|g| g.program.pass.program.as_str()) + .collect(); + format!("{} {n} passes, terrain {geometry:?}", f.folder) }) .collect(); println!("{name}: loads ({})", folders.join(", ")); diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 676fd0adc..ae3089006 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -489,12 +489,16 @@ impl ServerEntity { // A value back at its default is left out of the state, but the // clients still hold the old one: Entity's shared flags and pose go // back to 0 (a player standing up again, a mob no longer on fire), - // a sleeper's bed to none. + // a sleeper's bed to none, an item frame's item to empty and its + // rotation to 0 (ItemFrame.DATA_ITEM and DATA_ROTATION). + let frame = e.kind.ends_with("item_frame"); for (index, kind, _) in &self.meta { let default = match (*index, *kind) { (0, serializer::BYTE) => Value::Byte(0), (6, serializer::POSE) => Value::Id(0), (14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None), + (9, serializer::ITEM_STACK) if frame => Value::Item(None), + (10, serializer::INT) if frame => Value::Int(0), _ => match e.defaults.iter().find(|d| (d.0, d.1) == (*index, *kind)) { Some(d) => d.2.clone(), None => continue, @@ -1106,6 +1110,39 @@ mod tests { assert!(changes(&mut s, &e).is_empty()); } + #[test] + fn an_emptied_item_frame_sends_its_empty_item_and_rotation() { + let mut e = state(0.0); + e.kind = "minecraft:item_frame".into(); + let mut s = added(&e); + changes(&mut s, &e); + e.meta = vec![ + ( + 9, + serializer::ITEM_STACK, + Value::Item(Some(Stack::new(5, 1))), + ), + (10, serializer::INT, Value::Int(3)), + ]; + changes(&mut s, &e); + // Punched out (ItemFrame.removeFramedMap, setItem(EMPTY)): both back to the default. + e.meta.clear(); + let data = changes(&mut s, &e) + .into_iter() + .find_map(|p| match p { + play::Clientbound::SetEntityData(d) => Some(d), + _ => None, + }) + .expect("the empty frame is sent"); + assert_eq!( + data.values, + vec![ + (9, serializer::ITEM_STACK, Value::Item(None)), + (10, serializer::INT, Value::Int(0)), + ] + ); + } + #[test] fn a_value_back_at_a_listed_default_is_sent() { let mut e = state(0.0); diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index d37874bc8..de9fb9608 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -4,10 +4,15 @@ //! clone, throw, quick craft (drag) and pickup all; items thrown out of a //! menu are returned for the game to drop. use super::guest::Guest; -use crate::{items::ItemStack, world::World}; +use crate::{ + bundle::{Contents, can_be_in_bundle}, + items::{ItemStack, Items}, + world::World, +}; /// What the menus need to know about items. pub trait Rules { + fn items(&self) -> &Items; fn max_stack(&self, item: &str) -> u32; /// The armor slot (0 head .. 3 feet) an item can be worn in. fn armor_index(&self, item: &str) -> Option; @@ -364,6 +369,9 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { return; } let right = button == 1; + if bundle_click(view, i, right, rules) { + return; + } let (slot_item, carried) = (view.get(i), view.guest.carried.clone()); match (slot_item, carried) { (None, None) => {} @@ -410,6 +418,84 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { } } +/// `tryItemClickBehaviourOverride`: the carried stack's +/// `BundleItem.overrideStackedOnOther`, then the clicked one's +/// `overrideOtherStackedOnMe`. True when a bundle took the click. +fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bool { + let items = rules.items(); + let other = view.get(i); + if let Some(mut carried) = view.guest.carried.clone() + && let Some(mut contents) = Contents::of(items, &carried) + && other.is_some() != right + { + match other { + // tryTransfer: as much as fits, through `safeTake`. + Some(mut other) => { + if can_be_in_bundle(&other) { + let amount = other.count.min(contents.room_for(items, &other)); + if amount > 0 { + let mut taken = other.clone(); + taken.count = amount; + other.count -= amount; + view.set(i, (other.count > 0).then_some(other)); + contents.try_insert(items, &mut taken); + } + } + } + // removeOne into the empty slot (`safeInsert`); the rest goes back. + None => { + if let Some(mut stack) = contents.remove_one(items) { + if view.may_place(i, &stack, rules) { + let amount = stack.count.min(view.slot_max(i, &stack, rules)); + view.set( + i, + Some(ItemStack { + count: amount, + ..stack.clone() + }), + ); + stack.count -= amount; + } + if stack.count > 0 { + contents.try_insert(items, &mut stack); + } + } + } + } + contents.store(&mut carried); + view.guest.carried = Some(carried); + return true; + } + let Some(mut bundle) = other else { + return false; + }; + let Some(mut contents) = Contents::of(items, &bundle) else { + return false; + }; + // Slot.allowModification: mayPickup and mayPlace of its item. + let allowed = view.may_place(i, &bundle, rules); + match (view.guest.carried.take(), right) { + (Some(mut carried), false) => { + if allowed { + contents.try_insert(items, &mut carried); + } + view.guest.carried = (carried.count > 0).then_some(carried); + } + (None, true) => { + if allowed { + view.guest.carried = contents.remove_one(items); + } + } + (carried, _) => { + view.guest.carried = carried; + return false; + } + } + contents.store(&mut bundle); + view.set(i, Some(bundle)); + true +} + fn swap(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) { let Ok(i) = usize::try_from(slot) else { return; @@ -538,3 +624,116 @@ fn quick_craft( } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::lan::{Joined, PlayerSender}; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{Arc, atomic::AtomicI32, mpsc}; + + struct ItemRules(Items); + impl Rules for ItemRules { + fn items(&self) -> &Items { + &self.0 + } + fn max_stack(&self, item: &str) -> u32 { + self.0.get(item).map_or(64, |i| i.max_stack) + } + fn armor_index(&self, _: &str) -> Option { + None + } + } + + fn guest() -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: 2, + uuid: 2, + name: "Alex".into(), + properties: Vec::new(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender::new(tx, Arc::default()), + latency: Arc::new(AtomicI32::new(0)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + 2, + [0.0, 64.0, 0.0], + 8, + ) + } + + fn contents(stack: &Option) -> Vec<(String, u32)> { + let inside = stack.as_ref().and_then(|s| s.data()); + inside.map_or(Vec::new(), |d| { + d.bundle_contents + .iter() + .map(|s| (s.item.to_string(), s.count)) + .collect() + }) + } + + /// A guest's chest clicks run `BundleItem`'s overrides: a carried + /// bundle takes a slot's stack and drops its first one into an empty + /// slot; a stack clicked onto a bundle goes in, as far as it fits. + #[test] + fn guest_chest_clicks_fill_and_empty_bundles() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION) + }); + if !root.join("items.json").exists() { + eprintln!("skipping resource-backed bundle check: {}", root.display()); + return; + } + let registry = horizon_world::level::data::load_registry(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap(); + let rules = ItemRules(Items::load(&root, ®istry, &facts).unwrap()); + let mut g = guest(); + let mut chest = vec![ + Some(ItemStack::new("minecraft:stone", 48)), + None, + Some(ItemStack::new("minecraft:bundle", 1)), + ]; + let mut drag = None; + let mut view = View { + guest: &mut g, + container: Some(&mut chest), + }; + view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1)); + // Left click with the bundle: the stone goes in. + click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules); + assert_eq!(view.get(0), None); + assert_eq!( + contents(&view.guest.carried), + [("minecraft:stone".into(), 48)] + ); + // Right click on an empty slot: the stone comes back out. + click(&mut view, &mut drag, 1, 1, input::PICKUP, &rules); + assert_eq!(view.get(1).map(|s| s.count), Some(48)); + assert_eq!(contents(&view.guest.carried), []); + // Ender pearls (1/16 each) onto the bundle in the chest: 16 fit. + view.guest.carried = Some(ItemStack::new("minecraft:ender_pearl", 16)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried, None); + let bundle = view.get(2); + assert_eq!(contents(&bundle), [("minecraft:ender_pearl".into(), 16)]); + // Full: more stone stays in hand. + view.guest.carried = Some(ItemStack::new("minecraft:stone", 5)); + click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules); + assert_eq!(view.guest.carried.as_ref().map(|s| s.count), Some(5)); + // Right click on it with an empty hand takes the pearls out. + view.guest.carried = None; + click(&mut view, &mut drag, 2, 1, input::PICKUP, &rules); + assert_eq!( + view.guest.carried.as_ref().map(|s| (&*s.item, s.count)), + Some(("minecraft:ender_pearl", 16)) + ); + assert_eq!(contents(&view.get(2)), []); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1f04a89f0..dddf87c0d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,7 @@ pub mod border_render; pub mod bossbar; pub mod breaking; pub mod brewing; +pub mod bundle; pub mod camera; pub mod cauldron; pub mod chat; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index cdaf73eed..07e4ba2b9 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -16,6 +16,7 @@ use crate::{ }; use std::sync::Arc; +mod bundle; pub mod place; /// What a menu needs to know about items and recipes. @@ -276,6 +277,9 @@ pub struct Menu { pub loom_patterns: Vec>, /// Sounds the menu plays (`ui.loom.take_result`), for the caller. pub sounds: Vec<&'static str>, + /// Sounds the player makes (a bundle's insert and remove), for the + /// caller to play at the player as `Entity.playSound`. + pub player_sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, /// `LivingEntity.onEquipItem` calls that change the item: the @@ -671,6 +675,7 @@ impl Menu { quick_slots: Vec::new(), loom_patterns: Vec::new(), sounds: Vec::new(), + player_sounds: Vec::new(), crafted: Vec::new(), equipped: Vec::new(), merchant: None, @@ -931,6 +936,23 @@ impl Menu { } } + /// `slotsChanged(player.getInventory())`, which a bundle click calls + /// (`BundleItem.broadcastChangesOnContainerMenu`): the menus that don't + /// check which container changed recompute from their inputs. + fn inventory_slots_changed(&mut self, env: &Env) { + match self.kind { + Kind::Inventory | Kind::Crafting => self.recompute(env), + Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), + Kind::Cartography => self.carto_changed(env), + Kind::Merchant => self.merchant_update(env), + // ItemCombinerMenu.slotsChanged only for its inputs; the + // smithing table's hasRecipeError always. + Kind::Smithing => self.smith_error(), + _ => {} + } + } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and /// the levels (creative pays nothing). The enchanting itself needs a /// level and is the caller's (`enchant_button`). @@ -2536,10 +2558,12 @@ impl Menu { Ok(()) } - /// The PICKUP branch of `doClick` (without the bundle overrides), ending - /// with `slot.setChanged()`. + /// The PICKUP branch of `doClick`: a bundle's override, else the + /// plain click, ending with `slot.setChanged()`. fn pickup(&mut self, env: &Env, s: usize, primary: bool) { - self.pickup_inner(env, s, primary); + if !self.bundle_click(env, s, primary) { + self.pickup_inner(env, s, primary); + } self.slot_changed(env, s); } diff --git a/crates/horizon-client/src/menu/bundle.rs b/crates/horizon-client/src/menu/bundle.rs new file mode 100644 index 000000000..fba4a488e --- /dev/null +++ b/crates/horizon-client/src/menu/bundle.rs @@ -0,0 +1,102 @@ +//! `BundleItem`'s click overrides in a PICKUP click +//! (`tryItemClickBehaviourOverride`). +use super::{Env, Menu, tidy}; +use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle}; + +impl Menu { + /// The carried stack's `overrideStackedOnOther`, then the clicked + /// one's `overrideOtherStackedOnMe`. True when a bundle took the click. + pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let took = self.carried_bundle_click(env, s, primary) + || self.clicked_bundle_click(env, s, primary); + if took { + // broadcastChangesOnContainerMenu: the open menu's + // slotsChanged for the player's inventory. + self.inventory_slots_changed(env); + } + took + } + + /// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot. + fn carried_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut contents) = self + .carried + .as_ref() + .and_then(|c| Contents::of(env.items, c)) + else { + return false; + }; + match (self.slot(s).cloned(), primary) { + (Some(other), true) => { + // tryTransfer: what fits, taken by the slot's rules. + let mut moved = 0; + if can_be_in_bundle(&other) { + let room = contents.room_for(env.items, &other); + if let Some(mut taken) = self.safe_take(env, s, other.count, room) { + moved = contents.try_insert(env.items, &mut taken); + } + } + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + } + (None, false) => { + if let Some(stack) = contents.remove_one(env.items) { + let count = stack.count; + let mut remainder = Some(stack); + self.safe_insert(env, s, &mut remainder, count); + match remainder { + Some(mut rest) => { + contents.try_insert(env.items, &mut rest); + } + None => self.player_sounds.push(REMOVE_ONE), + } + } + } + _ => return false, + } + if let Some(carried) = self.carried.as_mut() { + contents.store(carried); + } + true + } + + /// `BundleItem.overrideOtherStackedOnMe`: a click on a bundle in a slot. + fn clicked_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool { + let Some(mut bundle) = self.slot(s).cloned() else { + return false; + }; + let Some(mut contents) = Contents::of(env.items, &bundle) else { + return false; + }; + let allowed = self.allow_modification(env, s); + match (self.carried.take(), primary) { + (Some(mut other), true) => { + let moved = if allowed { + contents.try_insert(env.items, &mut other) + } else { + 0 + }; + self.player_sounds + .push(if moved > 0 { INSERT } else { INSERT_FAIL }); + self.carried = Some(other); + tidy(&mut self.carried); + } + (None, false) => { + if allowed && let Some(removed) = contents.remove_one(env.items) { + self.player_sounds.push(REMOVE_ONE); + self.carried = Some(removed); + } + } + (carried, _) => { + // toggleSelectedItem(-1): Horizon keeps no selected item. + self.carried = carried; + return false; + } + } + // `self.set(BUNDLE_CONTENTS, ...)` changes the slot's stack in place. + contents.store(&mut bundle); + let slot = self.slots[s]; + self.containers[slot.container][slot.index] = Some(bundle); + true + } +} diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 97acc91c9..5fc09e35b 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -589,6 +589,7 @@ impl Settings { height_focused: f64::from(self.chat_height_focused), height_unfocused: f64::from(self.chat_height_unfocused), line_spacing: f64::from(self.chat_line_spacing), + colors: self.chat_colors, } } } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 11abb3328..1254d32f6 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -428,6 +428,34 @@ impl Text { } out } + /// The text without its legacy `§` codes (ChatFormatting.stripFormatting: + /// a `§` and a code character, `0`-`9`, `a`-`f`, `k`-`o` or `r`). + pub fn strip_legacy(&self) -> Text { + if !self.spans.iter().any(|s| s.text.contains('§')) { + return self.clone(); + } + let code = + |c: char| matches!(c.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'); + let mut out = Text::default(); + for span in &self.spans { + let mut text = String::with_capacity(span.text.len()); + let mut chars = span.text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '§' && chars.peek().is_some_and(|&n| code(n)) { + chars.next(); + } else { + text.push(c); + } + } + if !text.is_empty() { + out.spans.push(Span { + text, + style: span.style.clone(), + }); + } + } + out + } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { self.spans diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml index 8db24ac35..013d38a99 100644 --- a/crates/horizon-mods/Cargo.toml +++ b/crates/horizon-mods/Cargo.toml @@ -19,13 +19,16 @@ wit-component = { version = "0.239", optional = true } wit-parser = { version = "0.239", optional = true } [features] -default = ["runtime"] -# Loads and runs mods; without it only manifests and packaging (cargo horizon-mod). +# Loads and runs mods (the game's `mods` feature); without it only manifests, +# content and packaging. Off by default so builds that don't run mods (the +# game's tests and probes) skip wasmtime and cranelift. runtime = ["dep:wasmtime"] pack = ["dep:wit-component", "dep:wit-parser"] -[dev-dependencies] -horizon-mods = { path = ".", features = ["pack"] } +# Runs real mods: `cargo test -p horizon-mods --features runtime,pack`. +[[test]] +name = "sandbox" +required-features = ["runtime", "pack"] [lints] workspace = true diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index ec9ebe67d..5060bf747 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -11,6 +11,6 @@ pub mod manifest; mod runtime; pub use content::Content; -pub use manifest::{Capability, Manifest, Package, Side}; +pub use manifest::{Capability, Manifest, Package, Side, find}; #[cfg(feature = "runtime")] pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 44cdbd418..a71210883 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -1,6 +1,10 @@ //! `horizon-mod.toml`, a mod's manifest, and the `.hmod` file around it. use serde::Deserialize; -use std::{fmt, io::Read, path::Path}; +use std::{ + fmt, + io::Read, + path::{Path, PathBuf}, +}; /// The manifest's file name, beside `mod.wasm`. pub const MANIFEST: &str = "horizon-mod.toml"; @@ -282,6 +286,20 @@ impl Package { } } +/// The `.hmod` files and mod folders in `dir`, by name. +pub fn find(dir: &Path) -> Vec { + let Ok(read) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec = read + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "hmod") || p.join(MANIFEST).is_file()) + .collect(); + found.sort(); + found +} + /// Turns a `wasm32-unknown-unknown` cdylib built with the SDK into the /// component the game loads. #[cfg(feature = "pack")] diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 975cd1461..9dd2eb54e 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -131,23 +131,6 @@ pub struct Mods { out: Vec, } -/// The `.hmod` files and mod folders in `dir`, by name. -pub fn find(dir: &Path) -> Vec { - let Ok(read) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut found: Vec = read - .flatten() - .map(|e| e.path()) - .filter(|p| { - p.extension().is_some_and(|e| e == "hmod") - || p.join(crate::manifest::MANIFEST).is_file() - }) - .collect(); - found.sort(); - found -} - impl Mods { /// Reads every mod at `paths` and starts those `enabled` says are on. /// A command that `reserved` (vanilla's commands) or an earlier mod diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index b29bffb28..805dd80d4 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -372,6 +372,19 @@ fn client_library_artifacts(manifest: &Value) -> Result, Str Ok(artifacts) } +/// Netty's native transports (`io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64`, +/// the epoll ones on Linux): the game uses one when it loads and Netty NIO otherwise +/// (`EventLoopGroupHolder.remote` asks `KQueue.isAvailable()`, then `Epoll.isAvailable()`), and +/// Prism Launcher never downloads them (#1487). Preparing imports one when the launcher has it. +fn runs_without(name: &str) -> bool { + let mut parts = name.split(':'); + parts.next() == Some("io.netty") + && parts + .next() + .is_some_and(|artifact| artifact.starts_with("netty-transport-native-")) + && parts.nth(1).is_some() +} + /// A relative path with only normal components and forward slashes, from a manifest or bundle. pub(crate) fn safe_relative(path: &str) -> Option { if path.contains('\\') || path.starts_with('/') { @@ -547,9 +560,18 @@ pub fn import( for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; + let source = launcher_library(&minecraft, name, &relative); + let destination = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !source.is_file() && !destination.exists() { + log(&format!( + "No {name} in {}: the game runs without it", + minecraft.display() + )); + continue; + } client_libraries.push(import_copy( - &launcher_library(&minecraft, name, &relative), - &lock.directory.join("libraries/client").join(&relative), + &source, + &destination, sha1, "sha1", &hint(LAUNCHER_HINT, version), @@ -783,13 +805,17 @@ pub fn verify(lock: &Lock) -> Result { } /// The client libraries, checked against the version JSON (tools/test_model_baking_parity.py's -/// `client_libraries`); the client-side exporters compile against them. +/// `client_libraries`); the client-side exporters compile against them. A native transport the +/// player's launcher did not have is left out. pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, String> { let mut libraries = Vec::new(); - for (_, artifact) in client_library_artifacts(manifest)? { + for (name, artifact) in client_library_artifacts(manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe client library path")?; let library = lock.directory.join("libraries/client").join(&relative); + if runs_without(name) && !library.exists() { + continue; + } if !library.exists() || digest(&library, "sha1")? != sha1 { return Err(format!("Client dependency checksum changed: {path}")); } @@ -1071,6 +1097,135 @@ mod tests { } } + /// scanfee's Prism Launcher 26.3 install on a Mac (#1487): Prism keeps natives under its own + /// names and never downloads Netty's native transport, which the game runs without. Preparing + /// still checks every other library, and the transport whenever the launcher has it. + #[test] + fn a_prism_install_without_netty_natives_prepares() { + let fixture = Imports::new(); + let old = fixture.imported(&fixture.source); + let prism = fixture.directory.join("PrismLauncher"); + let put = |path: &str, data: &[u8]| { + let path = prism.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + put( + "versions/9.9/9.9.jar", + &fs::read(old.join("jars/client.jar")).unwrap(), + ); + put("libraries/org/lib/lib/1/lib-1.jar", b"lib"); + put( + "libraries/com/mojang/jtracy-natives-test/1/jtracy-natives-test-1.jar", + b"jtracy natives", + ); + let sha1 = |data: &[u8]| { + let file = fixture.directory.join("sha1"); + fs::write(&file, data).unwrap(); + digest(&file, "sha1").unwrap() + }; + let library = |name: &str, path: &str, sha1: &str, rules: &str| { + format!( + r#"{{"name":"{name}","downloads":{{"artifact":{{"path":"{path}","sha1":"{sha1}"}}}}{rules}}}"# + ) + }; + let netty = |arch: &str| { + library( + &format!("io.netty:netty-transport-native-kqueue:1:osx-{arch}"), + &format!("io/netty/netty-transport-native-kqueue/1/netty-transport-native-kqueue-1-osx-{arch}.jar"), + &sha1(b"kqueue"), + &format!(r#","rules":[{{"action":"allow","os":{{"name":"{}"}}}}]"#, rule_system()), + ) + }; + let client_sha1 = digest(&old.join("jars/client.jar"), "sha1").unwrap(); + let server_sha1 = digest(&old.join("jars/server.jar"), "sha1").unwrap(); + let libraries = [ + library( + "org.lib:lib:1", + "org/lib/lib/1/lib-1.jar", + &sha1(b"lib"), + "", + ), + library( + "com.mojang:jtracy:1:natives-test", + "com/mojang/jtracy/1/jtracy-1-natives-test.jar", + &sha1(b"jtracy natives"), + "", + ), + netty("aarch_64"), + netty("x86_64"), + ]; + put( + "versions/9.9/9.9.json", + format!( + r#"{{"id":"9.9","javaVersion":{{"majorVersion":25}},"downloads":{{"client":{{"sha1":"{client_sha1}"}},"server":{{"sha1":"{server_sha1}"}}}},"libraries":[{}]}}"#, + libraries.join(",") + ) + .as_bytes(), + ); + let manifest_sha1 = digest(&prism.join("versions/9.9/9.9.json"), "sha1").unwrap(); + fs::write( + fixture.target.join("research-lock.json"), + format!( + r#"{{"minecraft":{{"version":"9.9","java_major":25,"manifest_sha1":"{manifest_sha1}","client_sha1":"{client_sha1}","server_sha1":"{server_sha1}"}}}}"# + ), + ) + .unwrap(); + let lock = Lock::read(&fixture.target).unwrap(); + let server = old.join("jars/server.jar"); + let prepare = || import(&fixture.target, &lock, Some(&prism), Some(&server), &|_| {}); + let imported = || { + let manifest = verify(&lock).unwrap().manifest; + client_libraries(&lock, &manifest).unwrap().len() + }; + + prepare().unwrap(); + assert_eq!(imported(), 2); + let prepared = read_json(&lock.directory.join("prepared.json")).unwrap(); + let listed = prepared.get("libraries").and_then(|l| l.get("client")); + assert_eq!( + listed.and_then(Value::as_array).map(<[Value]>::len), + Some(2) + ); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + + // The launcher's copy is used, and checked, when it has one. + let manifest = read_json(&prism.join("versions/9.9/9.9.json")).unwrap(); + let (_, transport) = client_library_artifacts(&manifest) + .unwrap() + .into_iter() + .find(|(name, _)| runs_without(name)) + .unwrap(); + let path = transport.get("path").and_then(Value::as_str).unwrap(); + put(&format!("libraries/{path}"), b"not kqueue"); + assert!(prepare().unwrap_err().contains("is not the pinned file")); + put(&format!("libraries/{path}"), b"kqueue"); + prepare().unwrap(); + assert_eq!(imported(), 3); + // Other libraries stay required. + fs::remove_dir_all(lock.directory.join("libraries/client/org")).unwrap(); + fs::remove_file(prism.join("libraries/org/lib/lib/1/lib-1.jar")).unwrap(); + assert!(prepare().unwrap_err().starts_with("Missing ")); + } + + #[test] + fn runs_without_only_netty_native_transports() { + assert!(runs_without( + "io.netty:netty-transport-native-kqueue:4.2.16.Final:osx-aarch_64" + )); + assert!(runs_without( + "io.netty:netty-transport-native-epoll:4.2.16.Final:linux-x86_64" + )); + for required in [ + "io.netty:netty-transport-native-unix-common:4.2.16.Final", + "io.netty:netty-transport-classes-kqueue:4.2.16.Final", + "org.lwjgl:lwjgl:3.3.3:natives-macos-arm64", + "com.mojang:jtracy:1.14.38:natives-windows", + ] { + assert!(!runs_without(required), "{required}"); + } + } + #[test] fn natives_follow_the_architecture() { let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index fa454a134..552105d9e 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -182,6 +182,22 @@ impl JavaPack { } } +impl JavaPack { + /// The block ids of the pack's `block.properties` (empty without one), + /// [`properties::block_ids`]. + pub fn block_ids( + &self, + values: &OptionValues, + env: &Environment, + ) -> Result, String> { + match self.files.read("block.properties") { + Some(text) => properties::block_ids(&text, env, &self.options, values) + .map_err(|e| format!("block.properties: {e}")), + None => Ok(BTreeMap::new()), + } + } +} + /// A program's name in `shaders.properties` (`world-1/composite1.fsh` is /// `world-1/composite1`). pub fn program_name(program: &str) -> &str { diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index d851fc23a..0fe455231 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -12,7 +12,7 @@ use crate::{ options::OptionValues, preprocess::Environment, properties::{Blend, LEGACY_TARGETS, ShaderProperties}, - translate::{Link, Translated}, + translate::{Geometry, Link, Translated}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -327,8 +327,33 @@ pub struct Passes { /// next frame starts unflipped. pub flipped_at_end: BTreeSet, pub directives: Directives, + /// The program Horizon's solid terrain is drawn with + /// ([`TERRAIN_PROGRAMS`]), before `deferred`. + pub terrain: Option, + /// The program its translucent terrain is drawn with + /// ([`WATER_PROGRAMS`]), after `deferred`. + pub water: Option, } +/// The programs Iris draws solid terrain with, the first the pack has +/// (`ProgramId.Terrain`'s fallbacks). +pub const TERRAIN_PROGRAMS: &[&str] = &[ + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + +/// The programs Iris draws translucent terrain with (`ProgramId.Water`'s +/// fallbacks). +pub const WATER_PROGRAMS: &[&str] = &[ + "gbuffers_water", + "gbuffers_terrain", + "gbuffers_textured_lit", + "gbuffers_textured", + "gbuffers_basic", +]; + /// The `const` directives of a program folder that aren't about targets /// (`PackDirectives`), read from the same programs in the same order. #[derive(Clone, Copy, Debug, PartialEq)] @@ -554,6 +579,25 @@ impl JavaPack { out.flipped_after_translucent = flipped.clone(); out.composite = run(&groups[3], "composite_pre", &mut flipped)?; out.flipped_at_end = flipped; + // Geometry writes the side the next passes read. + let geometry = |chain: &[&str], flipped: &BTreeSet| { + let Some(name) = chain.iter().find(|n| exists(n)) else { + return Ok::<_, String>(None); + }; + let text = fragment(name)?; + let (blend, buffer_blends) = resolve_blends(&path(name)); + Ok(Some(Pass { + program: path(name), + draw_buffers: draw_buffers(&text).map_err(|e| format!("{}: {e}", path(name)))?, + reads_alt: flipped.clone(), + mipmapped: BTreeSet::new(), + scale: 1.0, + blend, + buffer_blends, + })) + }; + out.terrain = geometry(TERRAIN_PROGRAMS, &out.flipped_after_prepare)?; + out.water = geometry(WATER_PROGRAMS, &out.flipped_after_translucent)?; if exists("final") { let prog = path("final"); let (blend, buffer_blends) = resolve_blends(&prog); @@ -614,6 +658,70 @@ impl JavaPack { } } +/// A geometry program translated: the program (its vertex with the first +/// glue), and its vertex with each other glue. +pub struct GeometryProgram { + pub program: Program, + pub variants: Vec, +} + +impl JavaPack { + /// Translate geometry program `pass` (`gbuffers_*`) to run over + /// Horizon's geometry: its bindings in group 2, its attributes from + /// each of `glues` (the vertex program is translated once per glue). + #[allow(clippy::too_many_arguments)] + pub fn compile_geometry( + &self, + pass: &Pass, + targets: &[TargetSettings], + values: &OptionValues, + env: &Environment, + properties: &ShaderProperties, + glues: &[Geometry], + ) -> Result { + let (first, rest) = glues + .split_first() + .ok_or("a geometry program needs a glue")?; + let mut link = Link { + image_formats: properties.image_formats(), + shared_samplers: shared_samplers(targets), + set: 2, + geometry: Some(first.clone()), + ..Link::default() + }; + let vertex = self.translate(&format!("{}.vsh", pass.program), values, env, &mut link)?; + let fragment = self.translate(&format!("{}.fsh", pass.program), values, env, &mut link)?; + let mut variants = Vec::new(); + for glue in rest { + let mut other = link.clone(); + other.geometry = Some(glue.clone()); + variants.push(self.translate( + &format!("{}.vsh", pass.program), + values, + env, + &mut other, + )?); + if other.uniforms != link.uniforms || other.bindings != link.bindings { + return Err(format!("{}: its variants bind differently", pass.program)); + } + } + let draw_buffers = match &pass.draw_buffers { + Some(buffers) => buffers.clone(), + None => (0..fragment.interface.outputs.keys().max().map_or(1, |m| m + 1)).collect(), + }; + Ok(GeometryProgram { + program: Program { + pass: pass.clone(), + vertex, + fragment, + draw_buffers, + link, + }, + variants, + }) + } +} + /// Iris's sampler states for the textures it binds: colour targets /// linear (nearest for integer formats, and for 32-bit floats, which wgpu /// can't filter everywhere), depth nearest, noise repeating. For diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 885351b97..d0c69bbf0 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -639,6 +639,58 @@ impl ShaderProperties { } } +/// `block.properties` (`block.=`), preprocessed as +/// `shaders.properties` is: each block's id by its name without namespace +/// (`oak_leaves`). A block listed with a state (`grass_block:snowy=true`) +/// takes that id only when no entry names it without one; numeric ids +/// (before 1.13) are skipped. +pub fn block_ids( + text: &str, + env: &Environment, + options: &OptionSet, + values: &OptionValues, +) -> Result, String> { + let properties = Properties::parse(&preprocess(text, env, options, values)?); + let mut plain = BTreeMap::new(); + let mut with_state = BTreeMap::new(); + for (key, value) in properties.iter() { + let Some(Ok(id)) = key.strip_prefix("block.").map(str::parse::) else { + continue; + }; + for entry in value.split_whitespace() { + let entry = entry.strip_prefix("minecraft:").unwrap_or(entry); + if entry.contains(':') && entry.split(':').nth(1).is_some_and(|s| s.contains('=')) { + let name = entry.split(':').next().unwrap_or(entry); + with_state.entry(name.to_owned()).or_insert(id); + } else if !entry.chars().all(|c| c.is_ascii_digit()) && !entry.contains('=') { + plain.insert(entry.to_owned(), id); + } + } + } + for (name, id) in with_state { + plain.entry(name).or_insert(id); + } + Ok(plain) +} + +/// The block a block sprite (`minecraft:block/oak_log_top`) belongs to in +/// `ids` ([`block_ids`]): the block named like it, else the longest one its +/// name starts with followed by `_` (`oak_log`, `water` for `water_still`). +pub fn sprite_block_id(sprite: &str, ids: &BTreeMap) -> Option { + let name = sprite.rsplit(['/', ':']).next()?; + if let Some(&id) = ids.get(name) { + return Some(id); + } + let mut end = name.len(); + while let Some(cut) = name[..end].rfind('_') { + if let Some(&id) = ids.get(&name[..cut]) { + return Some(id); + } + end = cut; + } + None +} + /// Iris's `BooleanParser`: options joined by `!`, `&&`, `||` and brackets, /// `&&` binding tighter. `true`/`1` and `false`/`0` are literals; a name that /// isn't a boolean option is true; a malformed expression is true. @@ -757,6 +809,42 @@ mod tests { set } + /// `block.properties` as Chocapic13' writes it, and sprites matched to + /// its blocks. + #[test] + fn block_ids_and_the_sprites_of_their_blocks() { + let text = "\ +#if MC_VERSION >= 11300 +block.10001= minecraft:wheat minecraft:short_grass +block.10003 = minecraft:oak_leaves \\ + minecraft:vine +block.10006 = minecraft:grass_block:snowy=true minecraft:snow +block.8 = minecraft:water +block.2 = minecraft:grass_block +#else +block.10001= 6 31 +#endif +layer.translucent=minecraft:glass +"; + let env = Environment { + defines: vec![("MC_VERSION".into(), "260300".into())], + }; + let ids = block_ids(text, &env, &OptionSet::default(), &OptionValues::default()).unwrap(); + assert_eq!(ids.get("vine"), Some(&10003)); + // The stateless entry wins over the snowy one. + assert_eq!(ids.get("grass_block"), Some(&2)); + assert!(!ids.contains_key("6") && !ids.contains_key("glass")); + for (sprite, id) in [ + ("minecraft:block/oak_leaves", Some(10003)), + ("minecraft:block/water_still", Some(8)), + ("minecraft:block/grass_block_top", Some(2)), + ("minecraft:block/wheat_stage7", Some(10001)), + ("minecraft:block/stone", None), + ] { + assert_eq!(sprite_block_id(sprite, &ids), id, "{sprite}"); + } + } + #[test] fn java_properties_syntax() { let p = Properties::parse( diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 2e5d46db3..1fa3a6c14 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -45,7 +45,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; /// Locations, bindings and uniforms shared by the programs of one pass: a /// pass's vertex program is translated first, its fragment program second. -#[derive(Default, Debug)] +#[derive(Clone, Default, Debug)] pub struct Link { /// Varying name → location (split matrices and arrays as `name#i`). pub varyings: BTreeMap, @@ -64,6 +64,27 @@ pub struct Link { /// 16). Once any is named, comparison samplers share `iris_compare` and /// integer ones `iris_nearest`; textures not named keep `{name}_s`. pub shared_samplers: BTreeMap, + /// The bind group of the pack's bindings (0; 2 for geometry programs, + /// whose first groups are Horizon's). + pub set: u32, + /// Set for `gbuffers_*` programs drawn over Horizon's own geometry. + pub geometry: Option, +} + +/// How a `gbuffers_*` program runs over Horizon's geometry: its vertex +/// attributes aren't inputs but globals the glue fills from Horizon's +/// vertices before the program's `main`. +#[derive(Clone, Debug, Default)] +pub struct Geometry { + /// GLSL put before the vertex program: Horizon's vertex inputs and + /// buffers, and a `void hz_vertex()` run first in `main`. + pub vertex_glue: String, + /// Each attribute's value as a `vec4` expression of the glue + /// (`iris_Vertex`, `mc_Entity`, `vaUV0`...). Others are zero. + pub attributes: BTreeMap, + /// Iris's alpha test: the fragment is discarded unless output 0's + /// alpha is above it. + pub alpha_test: Option, } impl Link { @@ -385,6 +406,7 @@ pub fn translate( .parse(&options, &glsl) .map_err(|e| first_lines(&e.emit_to_string(&glsl)))?; unpad_private_arrays(&mut module); + end_returning_cases(&mut module); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all(), @@ -403,6 +425,49 @@ pub fn translate( }) } +/// A `case` that ends with `return` or `discard` rather than `break` +/// (Photon's displacement) is a fall-through one to naga's GLSL front end, +/// which its WGSL writer refuses: nothing falls through it. +fn end_returning_cases(module: &mut naga::Module) { + fn block(b: &mut naga::Block) { + for s in b.iter_mut() { + match s { + naga::Statement::Block(inner) => block(inner), + naga::Statement::If { accept, reject, .. } => { + block(accept); + block(reject); + } + naga::Statement::Loop { + body, continuing, .. + } => { + block(body); + block(continuing); + } + naga::Statement::Switch { cases, .. } => { + for case in cases { + block(&mut case.body); + if case.fall_through + && matches!( + case.body.last(), + Some(naga::Statement::Return { .. } | naga::Statement::Kill) + ) + { + case.fall_through = false; + } + } + } + _ => {} + } + } + } + for (_, f) in module.functions.iter_mut() { + block(&mut f.body); + } + for e in &mut module.entry_points { + block(&mut e.function.body); + } +} + /// Built-in functions naga folds in `const` initialisers. const FOLDABLE: &[&str] = &[ "radians", @@ -634,6 +699,8 @@ struct Legaliser<'a> { mat2_ctor: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, + /// Geometry programs: each attribute's type, for the glue. + attribute_types: BTreeMap, } fn var(name: &str) -> ast::Expr { @@ -952,6 +1019,7 @@ impl<'a> Legaliser<'a> { gather: false, mat2_ctor: false, runtime_constants: HashSet::new(), + attribute_types: BTreeMap::new(), } } @@ -1043,7 +1111,8 @@ impl<'a> Legaliser<'a> { show_declaration(&mut text, d, &mut FormattingState::default()) .map_err(|e| e.to_string())?; self.header.push(format!( - "layout({kind}, set = 0, binding = {binding}) {}", + "layout({kind}, set = {}, binding = {binding}) {}", + self.link.set, text.trim() )); Ok(false) @@ -1099,7 +1168,8 @@ impl<'a> Legaliser<'a> { for (name, _) in &names { let t = self.link.binding(&format!("{name}_t")); self.header.push(format!( - "layout(set = 0, binding = {t}) uniform {texture} {name}_t;" + "layout(set = {}, binding = {t}) uniform {texture} {name}_t;", + self.link.set )); let shared = &self.link.shared_samplers; let var = if shared.is_empty() { @@ -1117,7 +1187,8 @@ impl<'a> Legaliser<'a> { if self.sampler_vars.insert(var.clone()) { let s = self.link.binding(&var); self.header.push(format!( - "layout(set = 0, binding = {s}) uniform {sampler} {var};" + "layout(set = {}, binding = {s}) uniform {sampler} {var};", + self.link.set )); } self.interface @@ -1156,7 +1227,8 @@ impl<'a> Legaliser<'a> { .unwrap_or_else(|| "rgba8".to_owned()); let binding = self.link.binding(name); layout.push(format!( - "layout({f}, set = 0, binding = {binding}) {memory}uniform {ty} {name};" + "layout({f}, set = {}, binding = {binding}) {memory}uniform {ty} {name};", + self.link.set )); self.interface.images.push((name.clone(), f)); } @@ -1199,10 +1271,8 @@ impl<'a> Legaliser<'a> { for (i, (name, array)) in names.iter().enumerate() { let full_array = format!("{ty_array}{array}"); if input { - let at = Link::location(&mut self.link.attributes, name); - self.header.push(format!( - "layout(location = {at}) in {ty} {name}{full_array};" - )); + let decl = self.attribute(&ty, name, &full_array); + self.header.push(decl); self.interface.attributes.insert(name.clone()); } else if !varying { let at = explicit @@ -1670,9 +1740,8 @@ impl<'a> Legaliser<'a> { let ty = LEGACY_ATTRIBUTES.iter().find(|(a, _)| *a == n).unwrap().1; let renamed = n.replacen("gl_", "iris_", 1); if self.interface.attributes.insert(renamed.clone()) { - let at = Link::location(&mut self.link.attributes, &renamed); - self.header - .push(format!("layout(location = {at}) in {ty} {renamed};")); + let decl = self.attribute(ty, &renamed, ""); + self.header.push(decl); } renamed } @@ -1694,6 +1763,21 @@ impl<'a> Legaliser<'a> { } } + /// A vertex attribute's declaration: an input, or for geometry programs + /// a global the glue fills ([`Geometry`]). + fn attribute(&mut self, ty: &str, name: &str, array: &str) -> String { + match &self.link.geometry { + Some(_) => { + self.attribute_types.insert(name.to_owned(), ty.to_owned()); + format!("{ty} {name}{array};") + } + None => { + let at = Link::location(&mut self.link.attributes, name); + format!("layout(location = {at}) in {ty} {name}{array};") + } + } + } + fn frag_data(&mut self, n: u32) -> ast::Expr { let name = format!("iris_FragData{n}"); if self.interface.outputs.insert(n, name.clone()).is_none() { @@ -1959,9 +2043,8 @@ impl<'a> Legaliser<'a> { continue; } if attribute && self.stage == Stage::Vertex { - let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {ty} {name};")); + let decl = self.attribute(ty, name, ""); + self.header.push(decl); self.interface.attributes.insert(name.to_owned()); } else if !attribute { self.link.uniform(name, format!("{ty} {name}"))?; @@ -1971,6 +2054,42 @@ impl<'a> Legaliser<'a> { if !self.errors.is_empty() { return Err(self.errors.join("\n")); } + if let Some(geometry) = &self.link.geometry { + match self.stage { + Stage::Vertex => { + // The glue first, then the attributes from it, before + // the global initialisers (which may read them). + let mut first = vec!["hz_vertex();".to_owned()]; + for (name, ty) in &self.attribute_types { + first.push(match geometry.attributes.get(name) { + Some(value) => format!("{name} = {ty}({value});"), + None => format!("{name} = {ty}(0);"), + }); + } + self.prologue.splice(0..0, first); + } + Stage::Fragment => { + if let (Some(reference), Some(name)) = + (geometry.alpha_test, self.interface.outputs.get(&0)) + { + let written = format!("iris_out_{name}"); + let name = if self.declared.contains(&written) + || self + .header + .iter() + .any(|h| h.ends_with(&format!(" {written};"))) + { + written + } else { + name.clone() + }; + self.epilogue + .push(format!("if (!({name}.a > {reference:?})) discard;")); + } + } + _ => {} + } + } if self.stage == Stage::Vertex { // GL's clip space to wgpu's: y flipped, so texture row 0 stays // the bottom of the picture as in GL (texture coordinates and @@ -1982,6 +2101,10 @@ impl<'a> Legaliser<'a> { } let mut out = String::from("#version 450 core\n"); out.push_str(HELPERS); + if let (Some(geometry), Stage::Vertex) = (&self.link.geometry, self.stage) { + out.push_str(&geometry.vertex_glue); + out.push('\n'); + } if self.modulo { out.push_str(&modulo_helpers()); } @@ -1995,7 +2118,10 @@ impl<'a> Legaliser<'a> { out.push_str(MAT2_HELPERS); } if !self.link.uniforms.is_empty() { - out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); + out.push_str(&format!( + "layout(std140, set = {}, binding = 0) uniform IrisUniforms {{\n", + self.link.set + )); for (_, decl) in &self.link.uniforms { out.push_str(&format!(" {decl};\n")); } diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index 4c932d199..251bb7fb5 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -7,7 +7,7 @@ use horizon_shaderpack::{ include::Inlined, preprocess::{Environment, preprocess}, program_name, - translate::{Link, Translated, translate}, + translate::{Geometry, Link, Translated, translate}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -440,6 +440,95 @@ void main() {{ ); } +/// A `gbuffers_*` program over Horizon's geometry: its attributes are +/// globals the glue fills before `main`, its bindings in group 2, and its +/// fragment discards below Iris's alpha test. A `case` ending in `return` +/// (Photon's displacement) isn't a fall-through for naga. +#[test] +fn geometry_programs_take_their_attributes_from_the_glue() { + let glue = Geometry { + vertex_glue: "layout(location = 0) in vec3 hz_position; +layout(std430, set = 3, binding = 0) readonly buffer HzTable { int hz_table[]; }; +vec4 hz_pos; +void hz_vertex() { hz_pos = vec4(hz_position, 1.0) + float(hz_table[0]); }" + .into(), + attributes: [ + ("iris_Vertex".to_owned(), "hz_pos".to_owned()), + ( + "mc_Entity".to_owned(), + "vec4(8.0, -1.0, 0.0, 0.0)".to_owned(), + ), + ] + .into(), + alpha_test: Some(0.1), + }; + let mut link = Link { + set: 2, + geometry: Some(glue), + ..Link::default() + }; + let vs = run( + Stage::Vertex, + "uniform sampler2D noisetex; +attribute vec4 mc_Entity; +attribute vec2 mc_midTexCoord; +varying vec2 uv; +vec3 sway(vec3 p, int id) { + switch (id) { + case 8: + return p + 1.0; + case 9: + case 10: + return p - 1.0; + default: + return p; + } +} +void main() { + uv = gl_MultiTexCoord0.xy + mc_midTexCoord; + gl_Position = gl_ModelViewProjectionMatrix * vec4(sway(gl_Vertex.xyz, int(mc_Entity.x)), 1.0); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "hz_vertex();", + "mc_Entity = vec4(vec4(8.0, -1.0, 0.0, 0.0));", + "iris_Vertex = vec4(hz_pos);", + "mc_midTexCoord = vec2(0);", + "set = 2, binding = 0) uniform IrisUniforms", + ] { + assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl); + } + // Horizon's vertex input is the only one. + assert_eq!( + io(&vs, false).into_keys().collect::>(), + ["hz_position"] + ); + reparse(&vs.wgsl).unwrap(); + let fs = run( + Stage::Fragment, + "uniform sampler2D gtexture; +varying vec2 uv; +void main() { + /* DRAWBUFFERS:02 */ + gl_FragData[0] = texture2D(gtexture, uv); + gl_FragData[1] = vec4(1.0); +} +", + &mut link, + ) + .unwrap(); + assert!( + fs.glsl.contains("if (!(iris_FragData0.a > 0.1)) discard;"), + "{}", + fs.glsl + ); + assert!(fs.glsl.contains("set = 2, binding = "), "{}", fs.glsl); + reparse(&fs.wgsl).unwrap(); +} + /// A fragment output narrower than its four-channel target (Steadfast's /// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: /// GL fills the missing channels, wgpu refuses the pipeline. diff --git a/crates/horizon-world/examples/active_effect_tick_fixture.rs b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs similarity index 99% rename from crates/horizon-world/examples/active_effect_tick_fixture.rs rename to crates/horizon-world/examples/probe/active_effect_tick_fixture.rs index 7a4ed3c29..1e366bf44 100644 --- a/crates/horizon-world/examples/active_effect_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effect_tick_fixture.rs @@ -512,9 +512,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/active_effects_fixture.rs b/crates/horizon-world/examples/probe/active_effects_fixture.rs similarity index 98% rename from crates/horizon-world/examples/active_effects_fixture.rs rename to crates/horizon-world/examples/probe/active_effects_fixture.rs index dba99cccd..70395e813 100644 --- a/crates/horizon-world/examples/active_effects_fixture.rs +++ b/crates/horizon-world/examples/probe/active_effects_fixture.rs @@ -304,9 +304,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/anchor_fixture.rs b/crates/horizon-world/examples/probe/anchor_fixture.rs similarity index 94% rename from crates/horizon-world/examples/anchor_fixture.rs rename to crates/horizon-world/examples/probe/anchor_fixture.rs index c6c15e65e..230b05699 100644 --- a/crates/horizon-world/examples/anchor_fixture.rs +++ b/crates/horizon-world/examples/probe/anchor_fixture.rs @@ -18,8 +18,8 @@ fn anchor( a.to_json().unwrap_or_else(|_| "error".to_owned()) ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/attribute_fixture.rs b/crates/horizon-world/examples/probe/attribute_fixture.rs similarity index 92% rename from crates/horizon-world/examples/attribute_fixture.rs rename to crates/horizon-world/examples/probe/attribute_fixture.rs index 450400c21..79cf4e236 100644 --- a/crates/horizon-world/examples/attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Definition, Instance, Modifier, Observer, Operation, Packed, }; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn refs<'a>(mods: impl IntoIterator, pool: &[Modifier]) -> String { let s = mods .into_iter() @@ -43,9 +37,9 @@ impl Observer for Callback<'_> { self.out, "dirty {} {:016x} {} {:016x} {} {}", self.target, - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), a.modifiers().len(), a.permanent_modifiers().len() )?; @@ -55,7 +49,7 @@ impl Observer for Callback<'_> { return Err(io::Error::other("injected attribute observer failure")); } if self.op["read"].as_bool().unwrap() { - writeln!(self.out, "observed {:016x}", bits(a.value()))?; + writeln!(self.out, "observed {:016x}", f64_bits(a.value()))?; } Ok(()) } @@ -64,9 +58,9 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: writeln!( out, "state {id} {:016x} {} {:016x}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_bits(a.cached_value()) )?; writeln!(out, "all {}", refs(a.modifiers(), pool))?; writeln!(out, "permanent {}", refs(a.permanent_modifiers(), pool))?; @@ -80,8 +74,8 @@ fn state(out: &mut dyn Write, id: usize, a: &Instance, pool: &[Modifier]) -> io: } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -165,7 +159,7 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "packed {:016x} {}", - bits(p.base), + f64_bits(p.base), refs(&p.modifiers, &pool) )?; packed = Some(p); @@ -181,7 +175,7 @@ fn main() -> Result<(), Box> { ), "many" => instances[target].add_permanent_many(mods(), &mut cb), "value" => { - writeln!(cb.out, "value {:016x}", bits(instances[target].value()))?; + writeln!(cb.out, "value {:016x}", f64_bits(instances[target].value()))?; Ok(()) } _ => panic!("fixture mode"), diff --git a/crates/horizon-world/examples/attribute_health_fixture.rs b/crates/horizon-world/examples/probe/attribute_health_fixture.rs similarity index 94% rename from crates/horizon-world/examples/attribute_health_fixture.rs rename to crates/horizon-world/examples/probe/attribute_health_fixture.rs index 3bf0d8d75..05e779aac 100644 --- a/crates/horizon-world/examples/attribute_health_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attribute_health::{AttributeHealth, HealthAttributes, HealthError, HealthObserver}, attributes::{ @@ -21,13 +22,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn double_bits(v: f64) -> u64 { if v.is_nan() { f64::NAN.to_bits() @@ -55,7 +49,7 @@ impl Observer<'_> { impl HealthObserver for Observer<'_> { type Error = io::Error; fn updated(&mut self, h: &mut SyncedFloat) -> io::Result<()> { - self.effect(&format!("updated {:08x}", bits(h.value()))) + self.effect(&format!("updated {:08x}", f32_bits(h.value()))) } } // This fixture observes health/food values, not cross-attribute hash order. @@ -168,7 +162,7 @@ impl FoodWorld for World<'_, A> { } fn hurt_starvation(&mut self, _: (), _: &mut FoodData, v: f32) -> Result<(), Self::Error> { self.observer - .effect(&format!("starve {:08x}", bits(v))) + .effect(&format!("starve {:08x}", f32_bits(v))) .map_err(HealthError::Observer) } } @@ -261,7 +255,7 @@ fn run(dir: &Path, output: &str) -> Result<(), Box(dir: &Path, output: &str) -> Result<(), Box(dir: &Path, output: &str) -> Result<(), Box Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("live") { + if crate::args().nth(2).as_deref() == Some("live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") diff --git a/crates/horizon-world/examples/attribute_map_queries_fixture.rs b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs similarity index 98% rename from crates/horizon-world/examples/attribute_map_queries_fixture.rs rename to crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs index 28ee0c73a..8b7bf110a 100644 --- a/crates/horizon-world/examples/attribute_map_queries_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs @@ -244,9 +244,9 @@ mod integration { }; let prefix = format!( "prototype {id} {} {} {}", - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_hex(a.cached_value()) ); let all = a.modifiers().to_vec(); let permanent = a.permanent_modifiers().to_vec(); @@ -271,7 +271,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -377,14 +377,14 @@ mod integration { } else { ValueKind::Base }; - map.value(world.key(op), kind, &mut world).map(bits) + map.value(world.key(op), kind, &mut world).map(f64_hex) } "modifier-value" => { let id = world.templates[op["template"].as_u64().unwrap() as usize] .id() .to_owned(); map.modifier_value(world.key(op), &id, &mut world) - .map(bits) + .map(f64_hex) .map_err(|e| match e { ModifierValueError::World(e) => e, ModifierValueError::MissingInstanceModifier => Stop::Null, @@ -475,7 +475,7 @@ mod integration { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( @@ -499,6 +499,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs similarity index 99% rename from crates/horizon-world/examples/attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/attribute_updates_fixture.rs index 461a552b8..6bf9d815e 100644 --- a/crates/horizon-world/examples/attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/attribute_updates_fixture.rs @@ -625,9 +625,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/basic_feature_fixture.rs b/crates/horizon-world/examples/probe/basic_feature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/basic_feature_fixture.rs rename to crates/horizon-world/examples/probe/basic_feature_fixture.rs index f8ec7f53c..2e6bf9d73 100644 --- a/crates/horizon-world/examples/basic_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/basic_feature_fixture.rs @@ -156,8 +156,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/biome_chunk_fixture.rs b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs similarity index 96% rename from crates/horizon-world/examples/biome_chunk_fixture.rs rename to crates/horizon-world/examples/probe/biome_chunk_fixture.rs index 69f7c897d..e0c7f1686 100644 --- a/crates/horizon-world/examples/biome_chunk_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_chunk_fixture.rs @@ -20,8 +20,8 @@ fn biome_key(id: &i32) -> Option<&str> { _ => Some("horizon:other"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_generation_fixture.rs b/crates/horizon-world/examples/probe/biome_generation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_generation_fixture.rs rename to crates/horizon-world/examples/probe/biome_generation_fixture.rs index 2377747f9..f5a609a5c 100644 --- a/crates/horizon-world/examples/biome_generation_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_generation_fixture.rs @@ -20,8 +20,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; let noises: BTreeMap = serde_json::from_value(bundle["noises"].clone())?; diff --git a/crates/horizon-world/examples/biome_placement_fixture.rs b/crates/horizon-world/examples/probe/biome_placement_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_placement_fixture.rs rename to crates/horizon-world/examples/probe/biome_placement_fixture.rs index a412b9924..36a8cb7e6 100644 --- a/crates/horizon-world/examples/biome_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_placement_fixture.rs @@ -150,8 +150,8 @@ fn fixture( writeln!(world.out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_source_codec_fixture.rs b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_codec_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_codec_fixture.rs index d45dcdd3a..70347bbc6 100644 --- a/crates/horizon-world/examples/biome_source_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_codec_fixture.rs @@ -26,8 +26,8 @@ fn normalized(value: Value) -> Value { value => value, } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/biome_source_fixture.rs b/crates/horizon-world/examples/probe/biome_source_fixture.rs similarity index 95% rename from crates/horizon-world/examples/biome_source_fixture.rs rename to crates/horizon-world/examples/probe/biome_source_fixture.rs index cbf262a7c..021e67a0f 100644 --- a/crates/horizon-world/examples/biome_source_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_source_fixture.rs @@ -29,8 +29,8 @@ impl DensitySampler for Erosion { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/biome_temperature_fixture.rs b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs similarity index 97% rename from crates/horizon-world/examples/biome_temperature_fixture.rs rename to crates/horizon-world/examples/probe/biome_temperature_fixture.rs index 86b1393ce..e5b367947 100644 --- a/crates/horizon-world/examples/biome_temperature_fixture.rs +++ b/crates/horizon-world/examples/probe/biome_temperature_fixture.rs @@ -68,8 +68,8 @@ fn operations(worker: &mut BiomeTemperature, ops: &Value, out: &mut impl Write) } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs similarity index 78% rename from crates/horizon-world/examples/block_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/block_collision_scan_fixture.rs index 4c4764c5f..e39fe2b8d 100644 --- a/crates/horizon-world/examples/block_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/block_collision_scan_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -20,70 +21,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn shape(index: u64) -> VoxelShape { let cuboid = |min, max| VoxelShape::from_box(Aabb::new(min, max)).unwrap(); @@ -174,8 +111,8 @@ impl BlockCollisionWorld for World { Ok(self.palette[block.state.0 as usize].shape.clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let out = Rc::new(RefCell::new(io::BufWriter::new(fs::File::create( dir.join("rust.txt"), diff --git a/crates/horizon-world/examples/block_entity_storage_fixture.rs b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_entity_storage_fixture.rs rename to crates/horizon-world/examples/probe/block_entity_storage_fixture.rs index e321f23fe..687eed790 100644 --- a/crates/horizon-world/examples/block_entity_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/block_entity_storage_fixture.rs @@ -72,8 +72,8 @@ fn pending(tag: Option<&Tag>) -> String { } } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); let mut position = ChunkPos::default(); let mut chunk = ProtoBlockEntities::::new(position); diff --git a/crates/horizon-world/examples/block_landing_fixture.rs b/crates/horizon-world/examples/probe/block_landing_fixture.rs similarity index 93% rename from crates/horizon-world/examples/block_landing_fixture.rs rename to crates/horizon-world/examples/probe/block_landing_fixture.rs index 9e20d5a1b..a6ab6ac33 100644 --- a/crates/horizon-world/examples/block_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/block_landing_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -24,13 +26,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -43,17 +38,6 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} struct World<'a, 'r> { f: &'a Value, out: &'a mut dyn Write, @@ -100,9 +84,9 @@ impl BlockPushWorld for World<'_, '_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let i = e.0 as usize; self.entities[i] = self.entities[i].move_by(v); @@ -169,7 +153,7 @@ impl BlockLandingWorld for World<'_, '_> { Ok(k) } fn cause_fall_damage(&mut self, d: f64, m: f32, s: Self::DamageSource) -> io::Result { - self.query(format!("damage {:016x} {:08x} {s}", bits(d), fbits(m)))?; + self.query(format!("damage {:016x} {:08x} {s}", f64_bits(d), fbits(m)))?; Ok(self.flag("damage")) } fn known_sound(&self, s: LandingSound) -> Self::Sound { @@ -237,8 +221,8 @@ impl BlockLandingWorld for World<'_, '_> { self.query(format!("level-event {e} {} {d}", pos(p))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/block_properties_fixture.rs b/crates/horizon-world/examples/probe/block_properties_fixture.rs similarity index 97% rename from crates/horizon-world/examples/block_properties_fixture.rs rename to crates/horizon-world/examples/probe/block_properties_fixture.rs index 3404b1fa1..6169041a2 100644 --- a/crates/horizon-world/examples/block_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/block_properties_fixture.rs @@ -20,8 +20,8 @@ fn bbox(v: &Value) -> Aabb { .collect::>(); Aabb::new(Vec3::new(v[0], v[1], v[2]), Vec3::new(v[3], v[4], v[5])) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_push_fixture.rs b/crates/horizon-world/examples/probe/block_push_fixture.rs similarity index 83% rename from crates/horizon-world/examples/block_push_fixture.rs rename to crates/horizon-world/examples/probe/block_push_fixture.rs index 8871b1070..678e0fa24 100644 --- a/crates/horizon-world/examples/block_push_fixture.rs +++ b/crates/horizon-world/examples/probe/block_push_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -16,30 +18,12 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn bbox(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), Vec3::new(number(&v[3]), number(&v[4]), number(&v[5])), ) } -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) - ) -} fn shape(v: &Value) -> Result> { let mut s = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -85,9 +69,9 @@ impl BlockPushWorld for World<'_> { self.query(format!( "teleport {} {:016x} {:016x} {:016x}", e.0, - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ))?; let index = e.0 as usize; self.entities[index] = self.entities[index].move_by(v); @@ -97,8 +81,8 @@ impl BlockPushWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/block_state_codec_fixture.rs b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs similarity index 76% rename from crates/horizon-world/examples/block_state_codec_fixture.rs rename to crates/horizon-world/examples/probe/block_state_codec_fixture.rs index d0632ae86..40d51d4c2 100644 --- a/crates/horizon-world/examples/block_state_codec_fixture.rs +++ b/crates/horizon-world/examples/probe/block_state_codec_fixture.rs @@ -1,4 +1,5 @@ //! Original JSON block-state codec comparison transport. +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -11,19 +12,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/block_support_fixture.rs b/crates/horizon-world/examples/probe/block_support_fixture.rs similarity index 94% rename from crates/horizon-world/examples/block_support_fixture.rs rename to crates/horizon-world/examples/probe/block_support_fixture.rs index 9c43d5798..5d58fe159 100644 --- a/crates/horizon-world/examples/block_support_fixture.rs +++ b/crates/horizon-world/examples/probe/block_support_fixture.rs @@ -9,8 +9,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_survival_fixture.rs b/crates/horizon-world/examples/probe/block_survival_fixture.rs similarity index 98% rename from crates/horizon-world/examples/block_survival_fixture.rs rename to crates/horizon-world/examples/probe/block_survival_fixture.rs index e062eb8da..b357d1577 100644 --- a/crates/horizon-world/examples/block_survival_fixture.rs +++ b/crates/horizon-world/examples/probe/block_survival_fixture.rs @@ -103,8 +103,8 @@ impl SurvivalWorld for World<'_, W> { Ok(self.neighbors[old as usize % self.neighbors.len()]) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/probe/block_update_fixture.rs similarity index 99% rename from crates/horizon-world/examples/block_update_fixture.rs rename to crates/horizon-world/examples/probe/block_update_fixture.rs index bc90232cb..5be9be731 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/probe/block_update_fixture.rs @@ -191,8 +191,8 @@ fn summary(level: &Cells, before: &HashMap, out: &mut St } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/blocking_item_damage_fixture.rs b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs similarity index 97% rename from crates/horizon-world/examples/blocking_item_damage_fixture.rs rename to crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs index 2fd39bea0..eb2a6de60 100644 --- a/crates/horizon-world/examples/blocking_item_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs @@ -117,8 +117,8 @@ impl BlockingItemDamageWorld for World<'_> { Ok(self.flag("server")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/blocking_rules_fixture.rs b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs similarity index 93% rename from crates/horizon-world/examples/blocking_rules_fixture.rs rename to crates/horizon-world/examples/probe/blocking_rules_fixture.rs index c0e19d541..19d3bb8d5 100644 --- a/crates/horizon-world/examples/blocking_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/blocking_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::blocking_rules::{ BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld, }; @@ -13,13 +14,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -51,8 +45,8 @@ impl TypeMatchWorld for World<'_> { }) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -96,7 +90,7 @@ fn main() -> Result<(), Box> { )?; writeln!(w.out, "item {}", rules.item_damage.apply(damage))?; match rules.resolve(&mut w, damage, number(&f["angle"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/bulk_section_fixture.rs b/crates/horizon-world/examples/probe/bulk_section_fixture.rs similarity index 92% rename from crates/horizon-world/examples/bulk_section_fixture.rs rename to crates/horizon-world/examples/probe/bulk_section_fixture.rs index b9be692a7..a7bcc834a 100644 --- a/crates/horizon-world/examples/bulk_section_fixture.rs +++ b/crates/horizon-world/examples/probe/bulk_section_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::worldgen::{ anchor::WorldGenerationContext, bulk_section::TerrainBulkAccess, feature_region::TerrainRegion, }; @@ -55,17 +56,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -151,8 +141,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/bundle_weight_fixture.rs b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs similarity index 98% rename from crates/horizon-world/examples/bundle_weight_fixture.rs rename to crates/horizon-world/examples/probe/bundle_weight_fixture.rs index 2a47cdc37..8e077b807 100644 --- a/crates/horizon-world/examples/bundle_weight_fixture.rs +++ b/crates/horizon-world/examples/probe/bundle_weight_fixture.rs @@ -69,8 +69,8 @@ fn maximum(v: &Value) -> Option { fn fraction(f: Fraction) -> String { format!("{}/{}", f.numerator(), f.denominator()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/canyon_carver_fixture.rs b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/canyon_carver_fixture.rs rename to crates/horizon-world/examples/probe/canyon_carver_fixture.rs index 023ffa356..76eaad452 100644 --- a/crates/horizon-world/examples/canyon_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/canyon_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/carving_geometry_fixture.rs b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs similarity index 91% rename from crates/horizon-world/examples/carving_geometry_fixture.rs rename to crates/horizon-world/examples/probe/carving_geometry_fixture.rs index 1f0ce0ea2..52582b45b 100644 --- a/crates/horizon-world/examples/carving_geometry_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_geometry_fixture.rs @@ -1,4 +1,5 @@ //! Transport for shared cave/canyon geometry and ordered output failures. +use crate::support::common::f64_bits; use horizon_core::{ carving::{CarverOutput, CarvingMask, can_reach, carve_ellipsoid}, position::ChunkPos, @@ -15,13 +16,6 @@ fn n(v: &Value) -> i32 { fn d(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct Output<'a> { mask: &'a mut CarvingMask, trace: &'a std::cell::RefCell>, @@ -47,8 +41,8 @@ impl CarverOutput for Output<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -78,9 +72,9 @@ fn main() -> Result<(), Box> { }; trace.borrow_mut().push(format!( "skip {:x} {:x} {:x} {by} {skip}", - bits(x), - bits(y), - bits(z) + f64_bits(x), + f64_bits(y), + f64_bits(z) )); skip }, diff --git a/crates/horizon-world/examples/carving_mask_fixture.rs b/crates/horizon-world/examples/probe/carving_mask_fixture.rs similarity index 95% rename from crates/horizon-world/examples/carving_mask_fixture.rs rename to crates/horizon-world/examples/probe/carving_mask_fixture.rs index c7675ce47..17c82fd3c 100644 --- a/crates/horizon-world/examples/carving_mask_fixture.rs +++ b/crates/horizon-world/examples/probe/carving_mask_fixture.rs @@ -9,8 +9,8 @@ use std::{ fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/cave_carver_fixture.rs b/crates/horizon-world/examples/probe/cave_carver_fixture.rs similarity index 96% rename from crates/horizon-world/examples/cave_carver_fixture.rs rename to crates/horizon-world/examples/probe/cave_carver_fixture.rs index ad0d37612..79917c336 100644 --- a/crates/horizon-world/examples/cave_carver_fixture.rs +++ b/crates/horizon-world/examples/probe/cave_carver_fixture.rs @@ -82,8 +82,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/chunk_dump.rs b/crates/horizon-world/examples/probe/chunk_dump.rs similarity index 96% rename from crates/horizon-world/examples/chunk_dump.rs rename to crates/horizon-world/examples/probe/chunk_dump.rs index 125509d99..d36944989 100644 --- a/crates/horizon-world/examples/chunk_dump.rs +++ b/crates/horizon-world/examples/probe/chunk_dump.rs @@ -11,6 +11,7 @@ //! quart layer (16 columns, z-major), one `y Y ID...` line per block row and //! one `be X Y Z CANONICAL_NBT` line per block entity and one `t block|fluid //! NAME X Y Z PRIORITY` line per scheduled tick. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -23,17 +24,6 @@ use std::{collections::HashMap, fmt::Write as _, fs, io::Write as _, path::Path} type Error = Box; -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; @@ -106,8 +96,8 @@ fn canonical(tag: &Tag, out: &mut String) { } } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let seed: i64 = args.next().ok_or("seed")?.parse()?; let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?); diff --git a/crates/horizon-world/examples/chunk_stage_fixture.rs b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs similarity index 94% rename from crates/horizon-world/examples/chunk_stage_fixture.rs rename to crates/horizon-world/examples/probe/chunk_stage_fixture.rs index ee57f8930..2929de2f1 100644 --- a/crates/horizon-world/examples/chunk_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_stage_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for pre-light ProtoChunk writes and stage heightmap transitions. +use crate::support::common::tag; use horizon_core::position::ChunkPos; use horizon_world::{ DATA_VERSION, @@ -54,17 +55,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -223,8 +213,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/chunk_status_fixture.rs b/crates/horizon-world/examples/probe/chunk_status_fixture.rs similarity index 95% rename from crates/horizon-world/examples/chunk_status_fixture.rs rename to crates/horizon-world/examples/probe/chunk_status_fixture.rs index 92c5fe7bd..e124517fa 100644 --- a/crates/horizon-world/examples/chunk_status_fixture.rs +++ b/crates/horizon-world/examples/probe/chunk_status_fixture.rs @@ -4,8 +4,8 @@ use std::{ fs, io::{self, Write}, }; -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); writeln!( out, diff --git a/crates/horizon-world/examples/climbing_fixture.rs b/crates/horizon-world/examples/probe/climbing_fixture.rs similarity index 98% rename from crates/horizon-world/examples/climbing_fixture.rs rename to crates/horizon-world/examples/probe/climbing_fixture.rs index 19badd19b..48a28b8d3 100644 --- a/crates/horizon-world/examples/climbing_fixture.rs +++ b/crates/horizon-world/examples/probe/climbing_fixture.rs @@ -69,8 +69,8 @@ impl ClimbingWorld for World<'_> { self.last = Some(p); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/collision_context_fixture.rs b/crates/horizon-world/examples/probe/collision_context_fixture.rs similarity index 90% rename from crates/horizon-world/examples/collision_context_fixture.rs rename to crates/horizon-world/examples/probe/collision_context_fixture.rs index e99673e11..f26137fef 100644 --- a/crates/horizon-world/examples/collision_context_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_context_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::emit; use horizon_core::{ - geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, + geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, }; use horizon_world::{ @@ -31,70 +32,6 @@ const ITEMS: [&str; 5] = [ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct LiquidWorld<'a, W> { out: &'a mut W, calls: i32, @@ -244,8 +181,8 @@ impl PowderSnowWorld for RegistryWorld<'_, W> { Ok(self.feet.is_item("minecraft:leather_boots")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let registry = if dir.join("block-registry.nbt").exists() { Some(BlockRegistry::from_nbt( diff --git a/crates/horizon-world/examples/collision_fixture.rs b/crates/horizon-world/examples/probe/collision_fixture.rs similarity index 97% rename from crates/horizon-world/examples/collision_fixture.rs rename to crates/horizon-world/examples/probe/collision_fixture.rs index f8f2651c9..b2601f137 100644 --- a/crates/horizon-world/examples/collision_fixture.rs +++ b/crates/horizon-world/examples/probe/collision_fixture.rs @@ -56,12 +56,8 @@ impl Input<'_> { Vec3::new(self.number(), self.number(), self.number()) } } -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("fixture directory required")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("fixture directory required")?); let (registry_root, _) = nbt::read_named( &fs::read(base.join("block-registry.nbt"))?, Limits::default(), diff --git a/crates/horizon-world/examples/combat_rules_fixture.rs b/crates/horizon-world/examples/probe/combat_rules_fixture.rs similarity index 88% rename from crates/horizon-world/examples/combat_rules_fixture.rs rename to crates/horizon-world/examples/probe/combat_rules_fixture.rs index 42d01285d..9e523a30d 100644 --- a/crates/horizon-world/examples/combat_rules_fixture.rs +++ b/crates/horizon-world/examples/probe/combat_rules_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::combat_rules::{self, ArmorWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -56,8 +50,8 @@ impl ArmorWorld for World<'_> { Ok(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -77,7 +71,7 @@ fn main() -> Result<(), Box> { }; match result { Ok(v) => { - writeln!(w.out, "value {:08x}\nresult ok", bits(v))?; + writeln!(w.out, "value {:08x}\nresult ok", f32_bits(v))?; } Err(_) => writeln!(w.out, "result error")?, } diff --git a/crates/horizon-world/examples/component_durability_fixture.rs b/crates/horizon-world/examples/probe/component_durability_fixture.rs similarity index 98% rename from crates/horizon-world/examples/component_durability_fixture.rs rename to crates/horizon-world/examples/probe/component_durability_fixture.rs index 99f6c2389..7c5d89111 100644 --- a/crates/horizon-world/examples/component_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/component_durability_fixture.rs @@ -135,8 +135,8 @@ impl DurabilityWorld for World<'_> { writeln!(self.out, "copy-after {}", snapshot(©)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/component_patch_fixture.rs b/crates/horizon-world/examples/probe/component_patch_fixture.rs similarity index 97% rename from crates/horizon-world/examples/component_patch_fixture.rs rename to crates/horizon-world/examples/probe/component_patch_fixture.rs index 29b345c8d..9bd740061 100644 --- a/crates/horizon-world/examples/component_patch_fixture.rs +++ b/crates/horizon-world/examples/probe/component_patch_fixture.rs @@ -88,8 +88,8 @@ fn snapshot( maps[1] == maps[2] ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_emission_fixture.rs b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs similarity index 95% rename from crates/horizon-world/examples/consumable_emission_fixture.rs rename to crates/horizon-world/examples/probe/consumable_emission_fixture.rs index 966cec1d6..6bff122e1 100644 --- a/crates/horizon-world/examples/consumable_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -23,13 +24,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -142,12 +136,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -237,8 +231,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consumable_fixture.rs b/crates/horizon-world/examples/probe/consumable_fixture.rs similarity index 96% rename from crates/horizon-world/examples/consumable_fixture.rs rename to crates/horizon-world/examples/probe/consumable_fixture.rs index bfb1ad786..fccf46129 100644 --- a/crates/horizon-world/examples/consumable_fixture.rs +++ b/crates/horizon-world/examples/probe/consumable_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -33,13 +34,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&Component>) -> String { match v { None => "none".into(), @@ -189,12 +183,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -263,9 +257,9 @@ impl FoodConsumptionWorld for World<'_, R> { "food-sound {} {} {category} {} {} {} {} {}", s.level, s.sound, - bits(s.position.x), - bits(s.position.y), - bits(s.position.z), + f64_bits(s.position.x), + f64_bits(s.position.y), + f64_bits(s.position.z), fbits(s.volume), fbits(s.pitch) )) @@ -403,8 +397,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/consume_effect_fixture.rs b/crates/horizon-world/examples/probe/consume_effect_fixture.rs similarity index 98% rename from crates/horizon-world/examples/consume_effect_fixture.rs rename to crates/horizon-world/examples/probe/consume_effect_fixture.rs index 5e4b878b5..85c3b530b 100644 --- a/crates/horizon-world/examples/consume_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/consume_effect_fixture.rs @@ -206,8 +206,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/damage_immunity_fixture.rs b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs similarity index 97% rename from crates/horizon-world/examples/damage_immunity_fixture.rs rename to crates/horizon-world/examples/probe/damage_immunity_fixture.rs index b404b27b2..f477c08de 100644 --- a/crates/horizon-world/examples/damage_immunity_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_immunity_fixture.rs @@ -91,8 +91,8 @@ impl ImmunityWorld for Env<'_> { self.query("loaded", "loaded") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/damage_reduction_fixture.rs b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs similarity index 93% rename from crates/horizon-world/examples/damage_reduction_fixture.rs rename to crates/horizon-world/examples/probe/damage_reduction_fixture.rs index 16d37af2f..7310ca43e 100644 --- a/crates/horizon-world/examples/damage_reduction_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_reduction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ combat_rules::ArmorWorld, damage_reduction::{self, Bypass, DamageReductionWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -73,7 +67,7 @@ impl DamageReductionWorld for World<'_> { Ok(self.state()[format!("bypass_{n}")].as_bool().unwrap()) } fn hurt_armor(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("hurt-armor {:08x}", bits(v))) + self.query(&format!("hurt-armor {:08x}", f32_bits(v))) } fn armor_value(&mut self) -> io::Result { self.query("armor")?; @@ -115,8 +109,8 @@ impl DamageReductionWorld for World<'_> { Ok(0.0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let slots: Value = serde_json::from_str(&fs::read_to_string(dir.join("slots.json"))?)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); @@ -139,7 +133,7 @@ fn main() -> Result<(), Box> { } else { damage_reduction::after_magic(&mut w, d) }; - r.and_then(|v| writeln!(w.out, "float {:08x}", bits(v))) + r.and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))) }; writeln!( w.out, diff --git a/crates/horizon-world/examples/damage_source_fixture.rs b/crates/horizon-world/examples/probe/damage_source_fixture.rs similarity index 94% rename from crates/horizon-world/examples/damage_source_fixture.rs rename to crates/horizon-world/examples/probe/damage_source_fixture.rs index 7e8bfdaee..8599e3cac 100644 --- a/crates/horizon-world/examples/damage_source_fixture.rs +++ b/crates/horizon-world/examples/probe/damage_source_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::damage_source::{Catalog, EntityKind, SourceWorld}; use serde_json::Value; use std::{ @@ -11,21 +12,14 @@ fn number(v: &Value) -> f64 { fn position(v: &Value) -> [f64; 3] { std::array::from_fn(|i| number(&v[i])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn vec(v: Option<[f64; 3]>) -> String { match v { None => "none".into(), Some(v) => format!( "{:016x} {:016x} {:016x}", - bits(v[0]), - bits(v[1]), - bits(v[2]) + f64_bits(v[0]), + f64_bits(v[1]), + f64_bits(v[2]) ), } } @@ -85,8 +79,8 @@ impl SourceWorld for World<'_> { Ok(self.state()["creative"][id].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Catalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?, diff --git a/crates/horizon-world/examples/datafix_world.rs b/crates/horizon-world/examples/probe/datafix_world.rs similarity index 92% rename from crates/horizon-world/examples/datafix_world.rs rename to crates/horizon-world/examples/probe/datafix_world.rs index d3e189d85..f2e119d42 100644 --- a/crates/horizon-world/examples/datafix_world.rs +++ b/crates/horizon-world/examples/probe/datafix_world.rs @@ -4,7 +4,7 @@ //! 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}; +use std::{fs, io, path::Path, process::ExitCode}; fn copy(from: &Path, to: &Path) -> io::Result<()> { fs::create_dir_all(to)?; @@ -20,8 +20,8 @@ fn copy(from: &Path, to: &Path) -> io::Result<()> { Ok(()) } -fn main() -> ExitCode { - let args: Vec = env::args().skip(1).collect(); +pub fn main() -> ExitCode { + let args: Vec = crate::args().skip(1).collect(); let (input, output, target) = match args.as_slice() { [input, output] => (input, output, None), [input, output, target] => (input, output, target.parse::().ok()), diff --git a/crates/horizon-world/examples/decoration_fixture.rs b/crates/horizon-world/examples/probe/decoration_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_fixture.rs rename to crates/horizon-world/examples/probe/decoration_fixture.rs index 57c33d24b..1d8e53561 100644 --- a/crates/horizon-world/examples/decoration_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_fixture.rs @@ -102,8 +102,8 @@ impl PlacementContext for World<'_, W> { .is_some_and(|steps| steps.iter().flatten().any(|id| *id == feature))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/decoration_region_fixture.rs b/crates/horizon-world/examples/probe/decoration_region_fixture.rs similarity index 98% rename from crates/horizon-world/examples/decoration_region_fixture.rs rename to crates/horizon-world/examples/probe/decoration_region_fixture.rs index db1fb4206..bad115a50 100644 --- a/crates/horizon-world/examples/decoration_region_fixture.rs +++ b/crates/horizon-world/examples/probe/decoration_region_fixture.rs @@ -1,5 +1,4 @@ -#[path = "support/decoration_storage.rs"] -mod storage; +use crate::support::decoration_storage as storage; use horizon_core::{ biome::obfuscate_seed, position::{BlockPos, ChunkPos}, @@ -292,8 +291,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let (registry, states) = storage::load(dir)?; let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-world/examples/probe/dispatch.rs b/crates/horizon-world/examples/probe/dispatch.rs new file mode 100644 index 000000000..0b396edab --- /dev/null +++ b/crates/horizon-world/examples/probe/dispatch.rs @@ -0,0 +1,40 @@ +//! How the probe binary runs a probe. main.rs lists the probes and nothing else (tools/parity.py leaves it out of +//! the harnesses' dependencies); code every probe relies on goes here. +use std::process::ExitCode; + +/// `probes! { a, b, }` declares the binary's `main`, which runs the probe module named by its first argument. +macro_rules! probes { + ($($name:ident,)*) => { + fn run(name: &str) -> Option { + use std::process::Termination; + Some(match name { + $(stringify!($name) => $name::main().report(),)* + _ => return None, + }) + } + + fn main() -> std::process::ExitCode { + dispatch::main(&[$(stringify!($name)),*], run) + } + }; +} + +/// The probe's command line as its own example saw it: the program, then the arguments after the probe's name. +pub fn args() -> std::vec::IntoIter { + let mut args: Vec = std::env::args().collect(); + if args.len() > 1 { + args.remove(1); + } + args.into_iter() +} + +pub fn main(names: &[&str], run: fn(&str) -> Option) -> ExitCode { + let name = std::env::args().nth(1).unwrap_or_default(); + run(&name).unwrap_or_else(|| { + eprintln!( + "usage: probe [arguments...]\nprobes: {}", + names.join(" ") + ); + ExitCode::from(2) + }) +} diff --git a/crates/horizon-world/examples/dynamic_support_fixture.rs b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs similarity index 79% rename from crates/horizon-world/examples/dynamic_support_fixture.rs rename to crates/horizon-world/examples/probe/dynamic_support_fixture.rs index a321f97d0..84a176ea4 100644 --- a/crates/horizon-world/examples/dynamic_support_fixture.rs +++ b/crates/horizon-world/examples/probe/dynamic_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::{emit, values}; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, block_support::SupportType, @@ -15,70 +16,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, W> { collisions: &'a CachedCollisionRegistry<'a>, pistons: &'a PistonBlockBindings<'a>, @@ -152,8 +89,8 @@ impl PistonCollisionWorld for World<'_, W> { .map_err(io::Error::other) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts.json"))?)?; let states = facts["states"] diff --git a/crates/horizon-world/examples/edge_backoff_fixture.rs b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs similarity index 85% rename from crates/horizon-world/examples/edge_backoff_fixture.rs rename to crates/horizon-world/examples/probe/edge_backoff_fixture.rs index f12ce4431..a805cbb1e 100644 --- a/crates/horizon-world/examples/edge_backoff_fixture.rs +++ b/crates/horizon-world/examples/probe/edge_backoff_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::{Aabb, Axis, Vec3}; use horizon_world::edge_backoff::{EdgeBackoffInput, EdgeBackoffWorld, back_off_from_edge}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -56,12 +50,12 @@ impl EdgeBackoffWorld for World<'_> { fn no_collision(&mut self, b: Aabb) -> io::Result { self.query(format!( "clear {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) ))?; let p = self.probes; self.probes += 1; @@ -73,8 +67,8 @@ impl EdgeBackoffWorld for World<'_> { .unwrap_or(false)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -105,9 +99,9 @@ fn main() -> Result<(), Box> { Ok(v) => writeln!( world.out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(world.out, "error")?, }; diff --git a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs similarity index 93% rename from crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs rename to crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs index 8616303de..160dcdc28 100644 --- a/crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, effect_attribute_modifiers::{self as effects, Definitions, Error, ModifierWorld, Template}, @@ -24,21 +25,11 @@ enum Stop { Callback, Duplicate, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } fn desc(m: &Modifier) -> String { - format!("{}:{}:{}", m.id(), bits(m.amount()), m.operation() as u8) + format!("{}:{}:{}", m.id(), f64_hex(m.amount()), m.operation() as u8) } fn key_desc(k: Option<&Key>) -> String { k.map_or("null".into(), |k| k.id.to_string()) @@ -66,7 +57,7 @@ impl Shared { .iter() .map(|(k, v)| { let v = v.as_ref().map_or("null".into(), |t| { - format!("{}:{}:{}", t.id(), bits(t.amount()), t.operation() as u8) + format!("{}:{}:{}", t.id(), f64_hex(t.amount()), t.operation() as u8) }); format!("{}={v}", key_desc(k.as_ref())) }) @@ -126,9 +117,9 @@ impl Shared { fn state(&mut self, id: usize, a: &Instance) { self.logs.push(format!( "instance {id} {} {} {} | {} | {}", - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), self.refs(a.modifiers()), self.refs(a.permanent_modifiers()) )); @@ -153,7 +144,7 @@ impl Observer for Dirty<'_> { if self.shared.op["read"].as_bool().unwrap() { self.shared .logs - .push(format!("observed {}", bits(a.value()))); + .push(format!("observed {}", f64_hex(a.value()))); } Ok(()) } @@ -228,8 +219,8 @@ fn error(e: Error) -> &'static str { Error::World(Stop::Duplicate) => "duplicate", } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -316,10 +307,10 @@ fn main() -> Result<(), Box> { } "value" => { let id = op["target"].as_u64().unwrap() as usize; - world - .shared - .logs - .push(format!("value {id} {}", bits(world.instances[id].value()))); + world.shared.logs.push(format!( + "value {id} {}", + f64_hex(world.instances[id].value()) + )); Ok(()) } _ => { diff --git a/crates/horizon-world/examples/effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/effect_notifications_fixture.rs index 248c77a97..195fa9b4b 100644 --- a/crates/horizon-world/examples/effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_notifications_fixture.rs @@ -494,9 +494,9 @@ fn run(f: Value, out: &mut dyn Write) { w.all(&s); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/effect_sync_fixture.rs b/crates/horizon-world/examples/probe/effect_sync_fixture.rs similarity index 99% rename from crates/horizon-world/examples/effect_sync_fixture.rs rename to crates/horizon-world/examples/probe/effect_sync_fixture.rs index 6c7b5f3ae..9c8a2aa09 100644 --- a/crates/horizon-world/examples/effect_sync_fixture.rs +++ b/crates/horizon-world/examples/probe/effect_sync_fixture.rs @@ -330,8 +330,8 @@ impl EffectSyncWorld for World<'_> { sync::update_invisibility(s, self) } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let metadata: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let catalog = Catalog::from_json(&metadata)?; diff --git a/crates/horizon-world/examples/entity_attribute_fixture.rs b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs similarity index 92% rename from crates/horizon-world/examples/entity_attribute_fixture.rs rename to crates/horizon-world/examples/probe/entity_attribute_fixture.rs index eb1bc8358..e5fe13b98 100644 --- a/crates/horizon-world/examples/entity_attribute_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_attribute_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_world::attributes::{ AttributeError, Modifier, Operation, entity::{Catalog, LookupError}, @@ -12,17 +13,10 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn lookup(out: &mut dyn Write, label: &str, result: Result) -> io::Result<()> { match result { Ok(v) => { - writeln!(out, "{label} {:016x}", bits(v))?; + writeln!(out, "{label} {:016x}", f64_bits(v))?; writeln!(out, "ok") } Err(e) => writeln!( @@ -36,8 +30,8 @@ fn lookup(out: &mut dyn Write, label: &str, result: Result) -> ), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -114,9 +108,9 @@ fn main() -> Result<(), Box> { writeln!( out, "state {i} {:016x} {} {:016x} {} {} {} {}", - bits(a.base_value()), + f64_bits(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_bits(a.cached_value()), map.needs_update(id), map.needs_sync(id), a.modifiers().len(), diff --git a/crates/horizon-world/examples/entity_collision_fixture.rs b/crates/horizon-world/examples/probe/entity_collision_fixture.rs similarity index 69% rename from crates/horizon-world/examples/entity_collision_fixture.rs rename to crates/horizon-world/examples/probe/entity_collision_fixture.rs index edf258069..d801e7d34 100644 --- a/crates/horizon-world/examples/entity_collision_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_collision_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Vec3, VoxelShape}; +use crate::support::shapes::{box_values, emit}; +use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::{ entity_collision::{CollisionCandidate, EntityCollisionWorld, entity_collision_shapes}, entity_obstruction::EntityIdentity, @@ -12,70 +13,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} fn bounds(v: &Value) -> Aabb { Aabb::new( Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])), @@ -142,8 +79,8 @@ impl EntityCollisionWorld for World<'_, W> { && source.is_none_or(|id| self.entities[id.0 as usize - 1].root != entity.root)) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/entity_fluid_fixture.rs b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs similarity index 96% rename from crates/horizon-world/examples/entity_fluid_fixture.rs rename to crates/horizon-world/examples/probe/entity_fluid_fixture.rs index 1178c63bf..d897eea1c 100644 --- a/crates/horizon-world/examples/entity_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{ geometry::{Aabb, Vec3}, position::BlockPos, @@ -28,26 +29,17 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn show(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} #[derive(Clone, Copy, Default)] struct Tick { touch: bool, @@ -319,8 +311,8 @@ fn limit_checks(template: &Value, states: [FluidState; 5]) { assert!(!interaction.update(&mut world, false, 0).unwrap()); assert!(interaction.trackers().is_empty()); } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { @@ -446,7 +438,7 @@ fn main() -> Result<(), Box> { w.out, "tracker {} {:016x} {}", t.fluid as u8, - bits(t.height), + f64_bits(t.height), t.eyes_inside )?; } @@ -455,7 +447,7 @@ fn main() -> Result<(), Box> { w.out, "current {} {:016x} {} {}", tag.0, - bits(c.height), + f64_bits(c.height), show(c.accumulated), c.count )?; @@ -465,7 +457,7 @@ fn main() -> Result<(), Box> { let height = interaction.fluid_height(&w, tag); let inside = interaction.is_in_fluid(&w, tag); let eyes = interaction.is_eye_in_fluid(&w, tag); - writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", bits(height))?; + writeln!(w.out, "tag {t} {:016x} {inside} {eyes}", f64_bits(height))?; } writeln!(w.out, "final {}", show(w.velocity))?; writeln!(w.out, "queries {}", w.calls)?; @@ -476,7 +468,7 @@ fn main() -> Result<(), Box> { "tick {} {} {:016x}", tick.touch, tick.first, - bits(tick.fall) + f64_bits(tick.fall) )?; } } diff --git a/crates/horizon-world/examples/entity_move_fixture.rs b/crates/horizon-world/examples/probe/entity_move_fixture.rs similarity index 94% rename from crates/horizon-world/examples/entity_move_fixture.rs rename to crates/horizon-world/examples/probe/entity_move_fixture.rs index fbcbb8ed1..c31e485a9 100644 --- a/crates/horizon-world/examples/entity_move_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_move_fixture.rs @@ -1,5 +1,7 @@ +use crate::support::common::f64_bits; +use crate::support::shapes::bounds; use horizon_core::{ - geometry::{Aabb, Axis, Vec3, VoxelShape, resolve_shape_movement}, + geometry::{Aabb, Vec3, VoxelShape, resolve_shape_movement}, position::BlockPos, }; use horizon_world::{ @@ -23,30 +25,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vec(label: &str, v: Vec3) -> String { format!( "{label} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) - ) -} -fn bounds(label: &str, b: Aabb) -> String { - format!( - "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } fn pos(p: BlockPos) -> String { @@ -213,7 +197,7 @@ impl EntityMoveWorld for World<'_> { _: BlockStateId, p: BlockPos, ) -> io::Result<()> { - self.query(format!("fall {:016x} {ground} {}", bits(dy), pos(p)))?; + self.query(format!("fall {:016x} {ground} {}", f64_bits(dy), pos(p)))?; if self.flag("fall_mutates") { self.fall = 3.0; self.velocity = Vec3::new(17.0, 18.0, 19.0); @@ -327,8 +311,8 @@ impl RestitutionWorld for Bounce<'_, '_> { self.0.set_velocity(v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -399,7 +383,7 @@ fn main() -> Result<(), Box> { w.flags.minor, w.grounded, w.removed, - bits(w.fall) + f64_bits(w.fall) )?; writeln!(w.out, "history {}", w.history.records().len())?; for r in w.history.records() { diff --git a/crates/horizon-world/examples/entity_obstruction_fixture.rs b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs similarity index 96% rename from crates/horizon-world/examples/entity_obstruction_fixture.rs rename to crates/horizon-world/examples/probe/entity_obstruction_fixture.rs index ef8f0acc8..0d585170b 100644 --- a/crates/horizon-world/examples/entity_obstruction_fixture.rs +++ b/crates/horizon-world/examples/probe/entity_obstruction_fixture.rs @@ -69,8 +69,8 @@ fn bbox(v: &Value) -> Aabb { Vec3::new(values[3], values[4], values[5]), ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/extra_items_fixture.rs b/crates/horizon-world/examples/probe/extra_items_fixture.rs similarity index 99% rename from crates/horizon-world/examples/extra_items_fixture.rs rename to crates/horizon-world/examples/probe/extra_items_fixture.rs index 0cbdd98d0..f317e318c 100644 --- a/crates/horizon-world/examples/extra_items_fixture.rs +++ b/crates/horizon-world/examples/probe/extra_items_fixture.rs @@ -392,8 +392,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_support_fixture.rs b/crates/horizon-world/examples/probe/face_support_fixture.rs similarity index 60% rename from crates/horizon-world/examples/face_support_fixture.rs rename to crates/horizon-world/examples/probe/face_support_fixture.rs index e6bee0e7a..28e6fa81d 100644 --- a/crates/horizon-world/examples/face_support_fixture.rs +++ b/crates/horizon-world/examples/probe/face_support_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; use horizon_world::block_support::SupportType; use serde_json::Value; use std::{ @@ -13,72 +14,8 @@ fn numbers(v: &Value) -> Vec { .map(|v| f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())) .collect() } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/face_visibility_fixture.rs b/crates/horizon-world/examples/probe/face_visibility_fixture.rs similarity index 96% rename from crates/horizon-world/examples/face_visibility_fixture.rs rename to crates/horizon-world/examples/probe/face_visibility_fixture.rs index b2ef8716c..3c653f1e1 100644 --- a/crates/horizon-world/examples/face_visibility_fixture.rs +++ b/crates/horizon-world/examples/probe/face_visibility_fixture.rs @@ -12,8 +12,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let path = std::env::args().nth(1).ok_or("private fixture directory")?; +pub fn main() -> Result<(), Box> { + let path = crate::args().nth(1).ok_or("private fixture directory")?; let dir = Path::new(&path); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/fall_damage_fixture.rs b/crates/horizon-world/examples/probe/fall_damage_fixture.rs similarity index 89% rename from crates/horizon-world/examples/fall_damage_fixture.rs rename to crates/horizon-world/examples/probe/fall_damage_fixture.rs index 092208c95..573b9c1e9 100644 --- a/crates/horizon-world/examples/fall_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/fall_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::{FallDamageWorld, check_fall_damage}; use serde_json::Value; @@ -9,13 +10,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -66,7 +60,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -88,9 +82,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -100,8 +94,8 @@ impl FallDamageWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -130,10 +124,10 @@ fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/feature_catalog_fixture.rs b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs similarity index 94% rename from crates/horizon-world/examples/feature_catalog_fixture.rs rename to crates/horizon-world/examples/probe/feature_catalog_fixture.rs index c12b9c1a0..bbc69ffd3 100644 --- a/crates/horizon-world/examples/feature_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_catalog_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -178,19 +179,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let resources: Value = serde_json::from_str(&fs::read_to_string(dir.join("catalog.json"))?)?; let definitions = |name: &str| { diff --git a/crates/horizon-world/examples/feature_graph_fixture.rs b/crates/horizon-world/examples/probe/feature_graph_fixture.rs similarity index 97% rename from crates/horizon-world/examples/feature_graph_fixture.rs rename to crates/horizon-world/examples/probe/feature_graph_fixture.rs index fae5b6e2e..381972f44 100644 --- a/crates/horizon-world/examples/feature_graph_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_graph_fixture.rs @@ -161,8 +161,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let ids: [u32; 5] = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let blocks = ids.map(BlockStateId); diff --git a/crates/horizon-world/examples/feature_placement_fixture.rs b/crates/horizon-world/examples/probe/feature_placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/feature_placement_fixture.rs rename to crates/horizon-world/examples/probe/feature_placement_fixture.rs index c7500fa4f..5310b240f 100644 --- a/crates/horizon-world/examples/feature_placement_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for native modifier chains and a feature callback sharing the RNG. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -74,8 +73,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/feature_region_fixture.rs b/crates/horizon-world/examples/probe/feature_region_fixture.rs similarity index 97% rename from crates/horizon-world/examples/feature_region_fixture.rs rename to crates/horizon-world/examples/probe/feature_region_fixture.rs index a6cb08b10..6a244998d 100644 --- a/crates/horizon-world/examples/feature_region_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_region_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::worldgen::{ anchor::WorldGenerationContext, @@ -66,17 +67,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn fixture( f: &Value, registry: &BlockRegistry, @@ -496,8 +486,8 @@ fn query_state( } writeln!(out, "tags {bits}") } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/feature_sort_fixture.rs b/crates/horizon-world/examples/probe/feature_sort_fixture.rs similarity index 93% rename from crates/horizon-world/examples/feature_sort_fixture.rs rename to crates/horizon-world/examples/probe/feature_sort_fixture.rs index 6e645601c..370a16325 100644 --- a/crates/horizon-world/examples/feature_sort_fixture.rs +++ b/crates/horizon-world/examples/probe/feature_sort_fixture.rs @@ -7,8 +7,8 @@ use std::{ io::{self, Write}, path::Path, }; -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fill_layer_fixture.rs b/crates/horizon-world/examples/probe/fill_layer_fixture.rs similarity index 91% rename from crates/horizon-world/examples/fill_layer_fixture.rs rename to crates/horizon-world/examples/probe/fill_layer_fixture.rs index d10cd2b72..e107a6383 100644 --- a/crates/horizon-world/examples/fill_layer_fixture.rs +++ b/crates/horizon-world/examples/probe/fill_layer_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -134,19 +135,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_box_fixture.rs b/crates/horizon-world/examples/probe/fluid_box_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_box_fixture.rs rename to crates/horizon-world/examples/probe/fluid_box_fixture.rs index 50e5b7caf..0b348d7bb 100644 --- a/crates/horizon-world/examples/fluid_box_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_box_fixture.rs @@ -91,8 +91,8 @@ impl BoatFluidBoxWorld for World<'_> { self.boat } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_fixture.rs b/crates/horizon-world/examples/probe/fluid_fixture.rs similarity index 88% rename from crates/horizon-world/examples/fluid_fixture.rs rename to crates/horizon-world/examples/probe/fluid_fixture.rs index 466b85230..1c5ed4a85 100644 --- a/crates/horizon-world/examples/fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, fluid::{FluidBlockBindings, FluidHeightWorld, FluidKind, FluidState, FluidStateTable}, @@ -40,19 +41,8 @@ impl FluidHeightWorld for World<'_, W> { Ok(self.sturdy) } } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/fluid_flow_fixture.rs b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_flow_fixture.rs rename to crates/horizon-world/examples/probe/fluid_flow_fixture.rs index 4da9f6a07..ec7810509 100644 --- a/crates/horizon-world/examples/fluid_flow_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_flow_fixture.rs @@ -60,8 +60,8 @@ impl FluidFlowWorld for World<'_> { Ok(self.f["states"][s]["faces"].as_u64().unwrap() & (1 << (d as u8)) != 0) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/fluid_occupancy_fixture.rs b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs similarity index 98% rename from crates/horizon-world/examples/fluid_occupancy_fixture.rs rename to crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs index bb178e300..7fc884f49 100644 --- a/crates/horizon-world/examples/fluid_occupancy_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs @@ -67,8 +67,8 @@ impl FluidOccupancyWorld for World<'_, '_> { Ok(self.min + self.height - 1) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let registry = BlockRegistry::from_nbt( &nbt::read_named( diff --git a/crates/horizon-world/examples/fluid_shape_fixture.rs b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs similarity index 96% rename from crates/horizon-world/examples/fluid_shape_fixture.rs rename to crates/horizon-world/examples/probe/fluid_shape_fixture.rs index 7e42203ec..9c14d5849 100644 --- a/crates/horizon-world/examples/fluid_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/fluid_shape_fixture.rs @@ -34,8 +34,8 @@ impl FluidHeightWorld for World<'_> { panic!("ray shape does not use camera immersion support") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_fixture.rs b/crates/horizon-world/examples/probe/food_fixture.rs similarity index 90% rename from crates/horizon-world/examples/food_fixture.rs rename to crates/horizon-world/examples/probe/food_fixture.rs index d0645ea44..c12106dfb 100644 --- a/crates/horizon-world/examples/food_fixture.rs +++ b/crates/horizon-world/examples/probe/food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::food::{Difficulty, FoodData, FoodWorld}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(v: &Value) -> FoodData { FoodData { food: v["food"].as_i64().unwrap() as i32, @@ -72,7 +66,7 @@ impl FoodWorld for World<'_> { Ok(self.world()["hurt"].as_bool().unwrap()) } fn heal(&mut self, f: &mut FoodData, v: f32) -> io::Result<()> { - self.query(f, &format!("heal {:08x}", bits(v))) + self.query(f, &format!("heal {:08x}", f32_bits(v))) } fn health(&mut self, f: &mut FoodData) -> io::Result { self.query(f, "health")?; @@ -81,11 +75,11 @@ impl FoodWorld for World<'_> { fn hurt_starvation(&mut self, _: (), f: &mut FoodData, v: f32) -> io::Result<()> { self.query(f, "damage-sources")?; self.query(f, "starve-source")?; - self.query(f, &format!("hurt {:08x}", bits(v))) + self.query(f, &format!("hurt {:08x}", f32_bits(v))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -123,8 +117,8 @@ fn main() -> Result<(), Box> { w.out, "state {} {:08x} {:08x} {} {} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer, food.has_enough_food(), food.needs_food() @@ -135,8 +129,8 @@ fn main() -> Result<(), Box> { w.out, "final {} {:08x} {:08x} {}", food.food, - bits(food.saturation), - bits(food.exhaustion), + f32_bits(food.saturation), + f32_bits(food.exhaustion), food.timer )?; writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/food_properties_fixture.rs b/crates/horizon-world/examples/probe/food_properties_fixture.rs similarity index 98% rename from crates/horizon-world/examples/food_properties_fixture.rs rename to crates/horizon-world/examples/probe/food_properties_fixture.rs index 59524b0dc..50b88bccc 100644 --- a/crates/horizon-world/examples/food_properties_fixture.rs +++ b/crates/horizon-world/examples/probe/food_properties_fixture.rs @@ -160,8 +160,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/food_storage_fixture.rs b/crates/horizon-world/examples/probe/food_storage_fixture.rs similarity index 87% rename from crates/horizon-world/examples/food_storage_fixture.rs rename to crates/horizon-world/examples/probe/food_storage_fixture.rs index 4aafe920e..13e9a52dc 100644 --- a/crates/horizon-world/examples/food_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/food_storage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, nbt::{Compound, Tag}, @@ -17,13 +18,6 @@ const KEYS: [&str; 4] = [ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn tag(v: &Value) -> Option { let value = &v["value"]; Some(match v["type"].as_i64().unwrap() { @@ -49,8 +43,8 @@ fn tag(v: &Value) -> Option { _ => panic!("tag type"), }) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -82,8 +76,8 @@ fn main() -> Result<(), Box> { "state {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; let mut saved = Compound::new(); saved.insert("unrelated".into(), Tag::Int(42)); @@ -96,7 +90,7 @@ fn main() -> Result<(), Box> { for key in KEYS { match saved[&key.into()] { Tag::Int(v) => writeln!(out, "tag 3 {v}")?, - Tag::Float(v) => writeln!(out, "tag 5 {:08x}", bits(f32::from_bits(v)))?, + Tag::Float(v) => writeln!(out, "tag 5 {:08x}", f32_bits(f32::from_bits(v)))?, _ => panic!("saved type"), } } @@ -106,8 +100,8 @@ fn main() -> Result<(), Box> { "roundtrip {} {} {:08x} {:08x}", food.food, food.timer, - bits(food.saturation), - bits(food.exhaustion) + f32_bits(food.saturation), + f32_bits(food.exhaustion) )?; } Ok(()) diff --git a/crates/horizon-world/examples/ground_state_fixture.rs b/crates/horizon-world/examples/probe/ground_state_fixture.rs similarity index 87% rename from crates/horizon-world/examples/ground_state_fixture.rs rename to crates/horizon-world/examples/probe/ground_state_fixture.rs index 7b41515b3..47611587f 100644 --- a/crates/horizon-world/examples/ground_state_fixture.rs +++ b/crates/horizon-world/examples/probe/ground_state_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, Vec3}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn position(v: &Value) -> Option { if v.is_null() { None @@ -33,8 +27,8 @@ fn position(v: &Value) -> Option { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -62,12 +56,12 @@ fn main() -> Result<(), Box> { writeln!( out, "find {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; let call = calls; calls += 1; diff --git a/crates/horizon-world/examples/height_provider_fixture.rs b/crates/horizon-world/examples/probe/height_provider_fixture.rs similarity index 93% rename from crates/horizon-world/examples/height_provider_fixture.rs rename to crates/horizon-world/examples/probe/height_provider_fixture.rs index 7ada87a18..94b2524f7 100644 --- a/crates/horizon-world/examples/height_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/height_provider_fixture.rs @@ -33,8 +33,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/heightmap_fixture.rs b/crates/horizon-world/examples/probe/heightmap_fixture.rs similarity index 98% rename from crates/horizon-world/examples/heightmap_fixture.rs rename to crates/horizon-world/examples/probe/heightmap_fixture.rs index 35d7bc5c2..14cebbc59 100644 --- a/crates/horizon-world/examples/heightmap_fixture.rs +++ b/crates/horizon-world/examples/probe/heightmap_fixture.rs @@ -187,8 +187,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let directory = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let directory = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&directory); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let tags: Value = serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; diff --git a/crates/horizon-world/examples/interaction_shape_fixture.rs b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs similarity index 90% rename from crates/horizon-world/examples/interaction_shape_fixture.rs rename to crates/horizon-world/examples/probe/interaction_shape_fixture.rs index 60b9742b8..c1ca5700b 100644 --- a/crates/horizon-world/examples/interaction_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/interaction_shape_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, Axis, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -20,13 +21,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn shape(v: &Value) -> Result> { let mut result = VoxelShape::empty(); for b in v.as_array().unwrap() { @@ -77,8 +71,8 @@ impl RayWorld for World<'_, '_> { panic!("direct interaction clip") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { @@ -131,12 +125,12 @@ fn main() -> Result<(), Box> { writeln!( out, "box {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", - bits(b.min(Axis::X)), - bits(b.min(Axis::Y)), - bits(b.min(Axis::Z)), - bits(b.max(Axis::X)), - bits(b.max(Axis::Y)), - bits(b.max(Axis::Z)) + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) )?; } } @@ -160,9 +154,9 @@ fn main() -> Result<(), Box> { Some(h) => writeln!( out, "hit {:016x} {:016x} {:016x} {} {} {} {} {}", - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), h.block.x, h.block.y, diff --git a/crates/horizon-world/examples/inventory_pickup_fixture.rs b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_pickup_fixture.rs rename to crates/horizon-world/examples/probe/inventory_pickup_fixture.rs index b3f742aa0..58170e871 100644 --- a/crates/horizon-world/examples/inventory_pickup_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_pickup_fixture.rs @@ -218,8 +218,8 @@ impl horizon_world::inventory_pickup::PickupHooks for World { Ok(self.op["infinite"].as_bool().unwrap()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_tick_fixture.rs b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/inventory_tick_fixture.rs rename to crates/horizon-world/examples/probe/inventory_tick_fixture.rs index 974ed6760..1dfb9655e 100644 --- a/crates/horizon-world/examples/inventory_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_tick_fixture.rs @@ -149,8 +149,8 @@ impl InventoryTickWorld for World { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_fixture.rs index 2f5ed557b..f00d97c9f 100644 --- a/crates/horizon-world/examples/inventory_use_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_fixture.rs @@ -230,8 +230,8 @@ impl UseServices for Services { self.event(view, state, &format!("synced {id}")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/inventory_use_start_fixture.rs b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs similarity index 99% rename from crates/horizon-world/examples/inventory_use_start_fixture.rs rename to crates/horizon-world/examples/probe/inventory_use_start_fixture.rs index f887e5688..fc46a58b7 100644 --- a/crates/horizon-world/examples/inventory_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/inventory_use_start_fixture.rs @@ -295,8 +295,8 @@ impl StartServices for Services { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_after_use_fixture.rs b/crates/horizon-world/examples/probe/item_after_use_fixture.rs similarity index 99% rename from crates/horizon-world/examples/item_after_use_fixture.rs rename to crates/horizon-world/examples/probe/item_after_use_fixture.rs index 3daf5dfce..30c35b871 100644 --- a/crates/horizon-world/examples/item_after_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_after_use_fixture.rs @@ -277,8 +277,8 @@ impl AfterUseWorld for World { c.apply(self, original) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_blocking_fixture.rs b/crates/horizon-world/examples/probe/item_blocking_fixture.rs similarity index 95% rename from crates/horizon-world/examples/item_blocking_fixture.rs rename to crates/horizon-world/examples/probe/item_blocking_fixture.rs index c4889925a..e3f622a6d 100644 --- a/crates/horizon-world/examples/item_blocking_fixture.rs +++ b/crates/horizon-world/examples/probe/item_blocking_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_core::geometry::Vec3; use horizon_world::{ blocking_rules::{BlockingRules, DamageReduction, ItemDamageFunction, TypeMatchWorld}, @@ -19,13 +20,6 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Option { (!v.is_null()).then(|| Vec3::new(number(&v[0]), number(&v[1]), number(&v[2]))) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Component { present: bool, bypass: Option, @@ -154,11 +148,11 @@ impl ItemBlockingWorld for World<'_> { e == 1 } fn block_using_item(&mut self, _: u64, damage: f32, fully: bool) -> io::Result<()> { - self.event(&format!("block-using 0 {:08x} {fully}", bits(damage))) + self.event(&format!("block-using 0 {:08x} {fully}", f32_bits(damage))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -207,7 +201,7 @@ fn main() -> Result<(), Box> { changed: false, }; match item_blocking::apply(&mut w, single(&f["damage"])) { - Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", bits(v))?, + Ok(v) => writeln!(w.out, "blocked {:08x}\nresult ok", f32_bits(v))?, Err(_) => writeln!(w.out, "result error")?, }; writeln!(w.out, "queries {} {}", w.calls, w.changed)?; diff --git a/crates/horizon-world/examples/item_cooldowns_fixture.rs b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_cooldowns_fixture.rs rename to crates/horizon-world/examples/probe/item_cooldowns_fixture.rs index fb92d462f..e43f1c6bb 100644 --- a/crates/horizon-world/examples/item_cooldowns_fixture.rs +++ b/crates/horizon-world/examples/probe/item_cooldowns_fixture.rs @@ -130,8 +130,8 @@ impl CooldownUser for User<'_> { self.book.add(group(&stack), ticks, self.events) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_durability_fixture.rs b/crates/horizon-world/examples/probe/item_durability_fixture.rs similarity index 97% rename from crates/horizon-world/examples/item_durability_fixture.rs rename to crates/horizon-world/examples/probe/item_durability_fixture.rs index f051bb91c..de0af24c3 100644 --- a/crates/horizon-world/examples/item_durability_fixture.rs +++ b/crates/horizon-world/examples/probe/item_durability_fixture.rs @@ -82,8 +82,8 @@ impl DurabilityWorld for World<'_> { self.event(s, "break") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_particles_fixture.rs b/crates/horizon-world/examples/probe/item_particles_fixture.rs similarity index 93% rename from crates/horizon-world/examples/item_particles_fixture.rs rename to crates/horizon-world/examples/probe/item_particles_fixture.rs index 9eead88ca..3b7375e17 100644 --- a/crates/horizon-world/examples/item_particles_fixture.rs +++ b/crates/horizon-world/examples/probe/item_particles_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -22,13 +23,6 @@ fn n(v: &Value, k: &str) -> i32 { fn fl(v: &Value, k: &str) -> f32 { f32::from_bits(v[k].as_u64().unwrap() as u32) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn opt(v: Option<&i32>) -> String { v.map_or("none".into(), i32::to_string) } @@ -141,12 +135,12 @@ impl ItemParticleWorld for World<'_, R> { "particle {level} {} {} {damage} {same} {} {} {} {} {} {}", t.item(), t.count(), - bits(p.x), - bits(p.y), - bits(p.z), - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )) } } @@ -178,8 +172,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_stack_storage_fixture.rs b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_stack_storage_fixture.rs rename to crates/horizon-world/examples/probe/item_stack_storage_fixture.rs index bceb9f797..31c741b3e 100644 --- a/crates/horizon-world/examples/item_stack_storage_fixture.rs +++ b/crates/horizon-world/examples/probe/item_stack_storage_fixture.rs @@ -86,8 +86,8 @@ fn append(arena: &mut Vec, copy: CopyResult) -> usize { } } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_template_fixture.rs b/crates/horizon-world/examples/probe/item_template_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_template_fixture.rs rename to crates/horizon-world/examples/probe/item_template_fixture.rs index 6a8df6cc0..b6a538b04 100644 --- a/crates/horizon-world/examples/item_template_fixture.rs +++ b/crates/horizon-world/examples/probe/item_template_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_catalog_fixture.rs b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs similarity index 96% rename from crates/horizon-world/examples/item_use_catalog_fixture.rs rename to crates/horizon-world/examples/probe/item_use_catalog_fixture.rs index 406ba521d..7d7871720 100644 --- a/crates/horizon-world/examples/item_use_catalog_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_catalog_fixture.rs @@ -33,8 +33,8 @@ fn snapshot(out: &mut dyn Write, s: &ItemUseStack<'_>) -> io::Result<()> { s.use_on_release() ) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let catalog = ItemUseCatalog::from_json(&serde_json::from_str(&fs::read_to_string( dir.join("catalog.json"), diff --git a/crates/horizon-world/examples/item_use_fixture.rs b/crates/horizon-world/examples/probe/item_use_fixture.rs similarity index 93% rename from crates/horizon-world/examples/item_use_fixture.rs rename to crates/horizon-world/examples/probe/item_use_fixture.rs index 74436d1f3..8d88aae7a 100644 --- a/crates/horizon-world/examples/item_use_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ blocking_rules::{BlockingRules, ItemDamageFunction}, item_use::{self, ItemUseWorld}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -85,8 +79,8 @@ impl ItemUseWorld for World<'_> { Ok(self.state()["virtual_remaining"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -127,7 +121,7 @@ fn main() -> Result<(), Box> { item_use::ticks_using_item(&mut w).and_then(|v| writeln!(w.out, "ticks {v}")) } "partial" => item_use::ticks_using_item_partial(&mut w, single(&f["partial"])) - .and_then(|v| writeln!(w.out, "float {:08x}", bits(v))), + .and_then(|v| writeln!(w.out, "float {:08x}", f32_bits(v))), _ => panic!("mode"), }; writeln!( diff --git a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_lifecycle_fixture.rs rename to crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs index 404f6ba17..f7d3df48a 100644 --- a/crates/horizon-world/examples/item_use_lifecycle_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs @@ -166,8 +166,8 @@ impl UseLifecycleWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/item_use_start_fixture.rs b/crates/horizon-world/examples/probe/item_use_start_fixture.rs similarity index 98% rename from crates/horizon-world/examples/item_use_start_fixture.rs rename to crates/horizon-world/examples/probe/item_use_start_fixture.rs index 19cb859f8..be927e42e 100644 --- a/crates/horizon-world/examples/item_use_start_fixture.rs +++ b/crates/horizon-world/examples/probe/item_use_start_fixture.rs @@ -199,8 +199,8 @@ impl StartUseWorld for World<'_> { self.kinetic_count = 0; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_hash_map_fixture.rs b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_hash_map_fixture.rs rename to crates/horizon-world/examples/probe/java_hash_map_fixture.rs index cc2f6860d..de441a488 100644 --- a/crates/horizon-world/examples/java_hash_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_hash_map_fixture.rs @@ -35,8 +35,8 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/java_identity_map_fixture.rs b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs similarity index 97% rename from crates/horizon-world/examples/java_identity_map_fixture.rs rename to crates/horizon-world/examples/probe/java_identity_map_fixture.rs index c73d20f7d..700b5b329 100644 --- a/crates/horizon-world/examples/java_identity_map_fixture.rs +++ b/crates/horizon-world/examples/probe/java_identity_map_fixture.rs @@ -48,10 +48,10 @@ impl JavaKey for Key { fn opt(v: Option) -> String { v.map_or("none".into(), |v| v.to_string()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - let side = std::env::args().nth(2).unwrap(); + let side = crate::args().nth(2).unwrap(); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/level_place_fixture.rs b/crates/horizon-world/examples/probe/level_place_fixture.rs similarity index 97% rename from crates/horizon-world/examples/level_place_fixture.rs rename to crates/horizon-world/examples/probe/level_place_fixture.rs index 13595726d..0b9b4f883 100644 --- a/crates/horizon-world/examples/level_place_fixture.rs +++ b/crates/horizon-world/examples/probe/level_place_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/level_shape_fixture.rs b/crates/horizon-world/examples/probe/level_shape_fixture.rs similarity index 98% rename from crates/horizon-world/examples/level_shape_fixture.rs rename to crates/horizon-world/examples/probe/level_shape_fixture.rs index 1e4909928..696ac62ab 100644 --- a/crates/horizon-world/examples/level_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/level_shape_fixture.rs @@ -43,8 +43,8 @@ impl LevelAccess for Cells { } } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/live_attribute_updates_fixture.rs b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs similarity index 98% rename from crates/horizon-world/examples/live_attribute_updates_fixture.rs rename to crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs index 9f73a07e3..b053c2c82 100644 --- a/crates/horizon-world/examples/live_attribute_updates_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs @@ -252,9 +252,9 @@ mod integration { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut self.pools[i]), refs(a.permanent_modifiers(), &mut self.pools[i]) ) @@ -474,7 +474,7 @@ mod integration { } } pub fn run() -> std::result::Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -541,8 +541,8 @@ mod integration { None, ); let result = match op["mode"].as_str().unwrap() { - "value" => w.attribute_value(key).map(bits), - "base" => live_updates::value(&mut w, key, ValueKind::Base).map(bits), + "value" => w.attribute_value(key).map(f64_hex), + "base" => live_updates::value(&mut w, key, ValueKind::Base).map(f64_hex), "set-health" => w .dispatch_set_health(single(&op["value"])) .map(|()| "ok".into()), @@ -593,6 +593,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/live_attributes_fixture.rs b/crates/horizon-world/examples/probe/live_attributes_fixture.rs similarity index 94% rename from crates/horizon-world/examples/live_attributes_fixture.rs rename to crates/horizon-world/examples/probe/live_attributes_fixture.rs index e90d8cb4f..1c4a868f5 100644 --- a/crates/horizon-world/examples/live_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/live_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::ValueKind, attributes::{ @@ -17,16 +18,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn error(e: Error) -> &'static str { match e { Error::NullAttribute | Error::MissingInstanceModifier => "null", @@ -52,7 +43,7 @@ fn refs(mods: &[Modifier], pool: &mut Vec) -> String { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -65,8 +56,8 @@ fn effect_error(e: effects::Error) -> Error { _ => panic!("fixture definitions unexpectedly invalid"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let catalog = Arc::new(Catalog::from_json(&serde_json::from_str( &fs::read_to_string(dir.join("catalog.json"))?, @@ -104,11 +95,11 @@ fn main() -> Result<(), Box> { )?; let mode = op["mode"].as_str().unwrap(); let result: Result = match mode { - "value" => attrs.value(key, ValueKind::Computed).map(bits), - "base" => attrs.value(key, ValueKind::Base).map(bits), + "value" => attrs.value(key, ValueKind::Computed).map(f64_hex), + "base" => attrs.value(key, ValueKind::Base).map(f64_hex), "has" => attrs.has_attribute(key).map(|v| v.to_string()), "has_modifier" => attrs.has_modifier(key, m.id()).map(|v| v.to_string()), - "modifier" => attrs.modifier_value(key, m.id()).map(bits), + "modifier" => attrs.modifier_value(key, m.id()).map(f64_hex), "ensure" => attrs.get_instance(key).map(|h| handle(h.as_ref())), "reset" => attrs.reset_base(key).map(|v| v.to_string()), "ack_update" => { @@ -208,9 +199,9 @@ fn main() -> Result<(), Box> { "instance {} {} {} {} {} | {} | {}", h.index(), key.name(), - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()), + f64_hex(a.cached_value()), refs(a.modifiers(), &mut pool), refs(a.permanent_modifiers(), &mut pool) )?; diff --git a/crates/horizon-world/examples/living_air_fixture.rs b/crates/horizon-world/examples/probe/living_air_fixture.rs similarity index 94% rename from crates/horizon-world/examples/living_air_fixture.rs rename to crates/horizon-world/examples/probe/living_air_fixture.rs index fe581f54f..882c5a8f3 100644 --- a/crates/horizon-world/examples/living_air_fixture.rs +++ b/crates/horizon-world/examples/probe/living_air_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -193,8 +192,8 @@ impl LivingAirWorld for World<'_> { Ok(self.flag("omni")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -239,7 +238,12 @@ fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/living_damage_fixture.rs b/crates/horizon-world/examples/probe/living_damage_fixture.rs similarity index 88% rename from crates/horizon-world/examples/living_damage_fixture.rs rename to crates/horizon-world/examples/probe/living_damage_fixture.rs index b77048866..d8097bde9 100644 --- a/crates/horizon-world/examples/living_damage_fixture.rs +++ b/crates/horizon-world/examples/probe/living_damage_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ living_damage::{self, DamageStat, DamageWorld}, living_health::{self, HealthWorld}, @@ -14,13 +15,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn stat(s: DamageStat) -> &'static str { match s { DamageStat::Absorbed => "absorbed", @@ -69,11 +63,11 @@ impl DamageWorld for World<'_> { Ok(self.state()["invulnerable"].as_bool().unwrap()) } fn after_armor(&mut self, v: f32) -> io::Result { - self.query(&format!("armor {:08x}", bits(v)))?; + self.query(&format!("armor {:08x}", f32_bits(v)))?; Ok(single(&self.state()["armor"])) } fn after_magic(&mut self, v: f32) -> io::Result { - self.query(&format!("magic {:08x}", bits(v)))?; + self.query(&format!("magic {:08x}", f32_bits(v)))?; Ok(single(&self.state()["magic"])) } fn absorption(&mut self) -> io::Result { @@ -98,13 +92,13 @@ impl DamageWorld for World<'_> { Ok(single(&self.state()["food_exhaustion"])) } fn cause_food_exhaustion(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("exhaust {:08x}", bits(v)))?; + self.query(&format!("exhaust {:08x}", f32_bits(v)))?; self.exhaustion += v; Ok(()) } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.query("tracker")?; - self.query(&format!("record {:08x}", bits(v)))?; + self.query(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -113,7 +107,7 @@ impl DamageWorld for World<'_> { Ok(self.health) } fn set_health(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-health {:08x}", bits(v)))?; + self.query(&format!("set-health {:08x}", f32_bits(v)))?; self.health = v; Ok(()) } @@ -140,7 +134,7 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.query(&format!("set-absorption {:08x}", bits(v)))?; + self.query(&format!("set-absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -151,8 +145,8 @@ impl HealthWorld for World<'_> { DamageWorld::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -181,10 +175,10 @@ fn main() -> Result<(), Box> { writeln!( w.out, "final {:08x} {:08x} {:08x} {:08x}", - bits(w.health), - bits(w.absorption), - bits(w.exhaustion), - bits(w.recorded) + f32_bits(w.health), + f32_bits(w.absorption), + f32_bits(w.exhaustion), + f32_bits(w.recorded) )?; writeln!(w.out, "queries {}", w.calls)?; } diff --git a/crates/horizon-world/examples/living_fall_fixture.rs b/crates/horizon-world/examples/probe/living_fall_fixture.rs similarity index 94% rename from crates/horizon-world/examples/living_fall_fixture.rs rename to crates/horizon-world/examples/probe/living_fall_fixture.rs index 64dc1f2df..2d65929ff 100644 --- a/crates/horizon-world/examples/living_fall_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fall_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_fall::{ ImpulseContext, LivingFallWorld, calculate_fall_damage, cause_living_fall_damage, @@ -14,13 +15,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector(v: &Value) -> Option { if v.is_null() { None @@ -60,9 +54,9 @@ impl World<'_> { writeln!( self.out, "impact {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ) } else { writeln!(self.out, "impact none") @@ -100,7 +94,7 @@ impl LivingFallWorld for World<'_> { fn propagate_fall_to_passengers(&mut self, d: f64, m: f32) -> io::Result<()> { self.query(format!( "passengers {:016x} {:08x}", - bits(d), + f64_bits(d), if m.is_nan() { 0x7fc00000 } else { m.to_bits() } ))?; if self.f["mutate"].as_bool().unwrap() { @@ -169,8 +163,8 @@ fn run(world: &mut World<'_>) -> io::Result<()> { }; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/living_fluid_fixture.rs b/crates/horizon-world/examples/probe/living_fluid_fixture.rs similarity index 96% rename from crates/horizon-world/examples/living_fluid_fixture.rs rename to crates/horizon-world/examples/probe/living_fluid_fixture.rs index 55ccdd8f5..bd3704965 100644 --- a/crates/horizon-world/examples/living_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/living_fluid_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::living_air::*; use horizon_world::living_fluid::*; @@ -16,18 +17,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -248,8 +247,8 @@ impl LivingFluidWorld for World<'_> { Ok(self.flag("float_tag")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -320,7 +319,12 @@ fn main() -> Result<(), Box> { "result {}", if result.is_ok() { "ok" } else { "error" } )?; - writeln!(w.out, "final {} {:016x}", vector(w.velocity), bits(w.fall))?; + writeln!( + w.out, + "final {} {:016x}", + vector(w.velocity), + f64_bits(w.fall) + )?; writeln!(w.out, "queries {}", w.calls)?; } Ok(()) diff --git a/crates/horizon-world/examples/living_health_fixture.rs b/crates/horizon-world/examples/probe/living_health_fixture.rs similarity index 90% rename from crates/horizon-world/examples/living_health_fixture.rs rename to crates/horizon-world/examples/probe/living_health_fixture.rs index 958d43b7d..53d00b076 100644 --- a/crates/horizon-world/examples/living_health_fixture.rs +++ b/crates/horizon-world/examples/probe/living_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_health::{self, HealthWorld, SyncedFloat}; use serde_json::Value; use std::{ @@ -11,13 +12,6 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct Context<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -70,7 +64,7 @@ impl HealthWorld for World<'_> { self.stores[data].set(v, false, |_| self.ctx.query("updated")) } fn store_absorption(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("absorption {:08x}", bits(v)))?; + self.ctx.query(&format!("absorption {:08x}", f32_bits(v)))?; self.absorption = v; Ok(()) } @@ -78,12 +72,12 @@ impl HealthWorld for World<'_> { self.ctx.world()["dead"].as_bool().unwrap() } fn dispatch_set_health(&mut self, v: f32) -> io::Result<()> { - self.ctx.query(&format!("set {:08x}", bits(v)))?; + self.ctx.query(&format!("set {:08x}", f32_bits(v)))?; living_health::set_health(self, v) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -123,7 +117,7 @@ fn main() -> Result<(), Box> { "packed {}", w.stores[w.ctx.active] .take_dirty() - .map(|v| format!("{:08x}", bits(v))) + .map(|v| format!("{:08x}", f32_bits(v))) .unwrap_or_else(|| "none".into()) ) } @@ -138,7 +132,7 @@ fn main() -> Result<(), Box> { writeln!( w.ctx.out, "data {i} {:08x} {} {} {}", - bits(s.value()), + f32_bits(s.value()), s.is_dirty(), s.item_dirty(), s.is_default() @@ -149,7 +143,7 @@ fn main() -> Result<(), Box> { w.ctx.out, "state {} {:08x} {dead} {}", w.ctx.active, - bits(w.absorption), + f32_bits(w.absorption), w.ctx.calls )?; } diff --git a/crates/horizon-world/examples/living_hurt_fixture.rs b/crates/horizon-world/examples/probe/living_hurt_fixture.rs similarity index 92% rename from crates/horizon-world/examples/living_hurt_fixture.rs rename to crates/horizon-world/examples/probe/living_hurt_fixture.rs index e9addb406..b5ab3e890 100644 --- a/crates/horizon-world/examples/living_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/living_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld, hurt_server}; use serde_json::Value; use std::{ @@ -8,19 +9,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -126,7 +120,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -134,10 +128,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -155,7 +149,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -179,7 +173,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -205,8 +199,8 @@ impl HurtWorld for Env<'_> { self.event("attacker") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -239,7 +233,7 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/living_landing_fixture.rs b/crates/horizon-world/examples/probe/living_landing_fixture.rs similarity index 92% rename from crates/horizon-world/examples/living_landing_fixture.rs rename to crates/horizon-world/examples/probe/living_landing_fixture.rs index 156f8a2bd..3c3e333d7 100644 --- a/crates/horizon-world/examples/living_landing_fixture.rs +++ b/crates/horizon-world/examples/probe/living_landing_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::fall_damage::FallDamageWorld; use horizon_world::living_landing::{LivingLandingWorld, check_living_fall_damage}; @@ -10,13 +11,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn support(v: &Value) -> Option { if v.is_null() { None @@ -69,7 +63,7 @@ impl FallDamageWorld for World<'_> { p.x, p.y, p.z, - bits(distance) + f64_bits(distance) ))?; if self.input["mutate"].as_bool().unwrap() { self.fall = 17.25; @@ -91,9 +85,9 @@ impl FallDamageWorld for World<'_> { fn hit_ground(&mut self, p: Vec3, s: u8) -> io::Result<()> { self.query(format!( "hit-ground {:016x} {:016x} {:016x} {}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), if s == 1 { "queried" } else { "input" } )) } @@ -142,11 +136,11 @@ impl LivingLandingWorld for World<'_> { assert_eq!(s, 0); self.query(format!( "particles {:016x} {:016x} {:016x} {} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z), count, - bits(speed) + f64_bits(speed) ))?; if self.input["particle_mutate"].as_bool().unwrap() { self.fall = number(&self.input["after_fall"]); @@ -158,8 +152,8 @@ impl LivingLandingWorld for World<'_> { self.climbable = false; } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -194,10 +188,10 @@ fn main() -> Result<(), Box> { writeln!( world.out, "final {:016x} {:016x} {:016x} {:016x}", - bits(world.fall), - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(world.fall), + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )?; if let Some(p) = world.support { writeln!(world.out, "support {} {} {}", p.x, p.y, p.z)?; diff --git a/crates/horizon-world/examples/living_motion_fixture.rs b/crates/horizon-world/examples/probe/living_motion_fixture.rs similarity index 90% rename from crates/horizon-world/examples/living_motion_fixture.rs rename to crates/horizon-world/examples/probe/living_motion_fixture.rs index 92b4db938..96c0792ac 100644 --- a/crates/horizon-world/examples/living_motion_fixture.rs +++ b/crates/horizon-world/examples/probe/living_motion_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::living_motion::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -118,8 +117,8 @@ impl LivingMotionWorld for World<'_> { Ok(number(&self.f["drag_modifier"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -138,10 +137,11 @@ fn main() -> Result<(), Box> { "power" => jump_power(&mut w, single(&f["scale"])) .and_then(|v| writeln!(w.out, "float {:08x}", fbits(v))), "jump" => jump_from_ground(&mut w), - "gravity" => gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))), - "effective" => { - effective_gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", bits(v))) + "gravity" => { + gravity(&mut w).and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))) } + "effective" => effective_gravity(&mut w) + .and_then(|v| writeln!(w.out, "double {:016x}", f64_bits(v))), "apply" => apply_gravity(&mut w), "up" => swim_vertical(&mut w, true), "down" => swim_vertical(&mut w, false), diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs new file mode 100644 index 000000000..f3b9b6ef5 --- /dev/null +++ b/crates/horizon-world/examples/probe/main.rs @@ -0,0 +1,358 @@ +//! Every horizon-world parity probe in one binary: `probe [arguments]` runs `.rs` as its own +//! example did (tools/test_*_parity.py). Linking ~170 examples, each instantiating the crate's generics again, +//! was most of the parity job's probe build; one binary builds them once. +//! +//! This file only lists the probes, so that adding one reruns no harness: tools/parity.py leaves it out of +//! their dependencies. How a probe runs is in dispatch.rs. +#[macro_use] +mod dispatch; + +use dispatch::args; + +/// Code shared by several probes. +mod support { + pub mod common; + pub mod decoration_storage; + pub mod placement_queries; + pub mod shapes; +} + +mod active_effect_tick_fixture; +mod active_effects_fixture; +mod anchor_fixture; +mod attribute_fixture; +mod attribute_health_fixture; +mod attribute_map_queries_fixture; +mod attribute_updates_fixture; +mod basic_feature_fixture; +mod biome_chunk_fixture; +mod biome_generation_fixture; +mod biome_placement_fixture; +mod biome_source_codec_fixture; +mod biome_source_fixture; +mod biome_temperature_fixture; +mod block_collision_scan_fixture; +mod block_entity_storage_fixture; +mod block_landing_fixture; +mod block_properties_fixture; +mod block_push_fixture; +mod block_state_codec_fixture; +mod block_support_fixture; +mod block_survival_fixture; +mod block_update_fixture; +mod blocking_item_damage_fixture; +mod blocking_rules_fixture; +mod bulk_section_fixture; +mod bundle_weight_fixture; +mod canyon_carver_fixture; +mod carving_geometry_fixture; +mod carving_mask_fixture; +mod cave_carver_fixture; +mod chunk_dump; +mod chunk_stage_fixture; +mod chunk_status_fixture; +mod climbing_fixture; +mod collision_context_fixture; +mod collision_fixture; +mod combat_rules_fixture; +mod component_durability_fixture; +mod component_patch_fixture; +mod consumable_emission_fixture; +mod consumable_fixture; +mod consume_effect_fixture; +mod damage_immunity_fixture; +mod damage_reduction_fixture; +mod damage_source_fixture; +mod datafix_world; +mod decoration_fixture; +mod decoration_region_fixture; +mod dynamic_support_fixture; +mod edge_backoff_fixture; +mod effect_attribute_modifiers_fixture; +mod effect_notifications_fixture; +mod effect_sync_fixture; +mod entity_attribute_fixture; +mod entity_collision_fixture; +mod entity_fluid_fixture; +mod entity_move_fixture; +mod entity_obstruction_fixture; +mod extra_items_fixture; +mod face_support_fixture; +mod face_visibility_fixture; +mod fall_damage_fixture; +mod feature_catalog_fixture; +mod feature_graph_fixture; +mod feature_placement_fixture; +mod feature_region_fixture; +mod feature_sort_fixture; +mod fill_layer_fixture; +mod fluid_box_fixture; +mod fluid_fixture; +mod fluid_flow_fixture; +mod fluid_occupancy_fixture; +mod fluid_shape_fixture; +mod food_fixture; +mod food_properties_fixture; +mod food_storage_fixture; +mod ground_state_fixture; +mod height_provider_fixture; +mod heightmap_fixture; +mod interaction_shape_fixture; +mod inventory_pickup_fixture; +mod inventory_tick_fixture; +mod inventory_use_fixture; +mod inventory_use_start_fixture; +mod item_after_use_fixture; +mod item_blocking_fixture; +mod item_cooldowns_fixture; +mod item_durability_fixture; +mod item_particles_fixture; +mod item_stack_storage_fixture; +mod item_template_fixture; +mod item_use_catalog_fixture; +mod item_use_fixture; +mod item_use_lifecycle_fixture; +mod item_use_start_fixture; +mod java_hash_map_fixture; +mod java_identity_map_fixture; +mod level_place_fixture; +mod level_shape_fixture; +mod live_attribute_updates_fixture; +mod live_attributes_fixture; +mod living_air_fixture; +mod living_damage_fixture; +mod living_fall_fixture; +mod living_fluid_fixture; +mod living_health_fixture; +mod living_hurt_fixture; +mod living_landing_fixture; +mod living_motion_fixture; +mod material_condition_fixture; +mod material_extension_fixture; +mod material_stage_fixture; +mod material_surface_fixture; +mod movement_emission_fixture; +mod movement_registry_fixture; +mod movement_support_fixture; +mod object_open_map_fixture; +mod object_open_set_fixture; +mod piston_movement_fixture; +mod piston_shape_fixture; +mod placement_fixture; +mod player_equipment_fixture; +mod player_food_fixture; +mod player_health_fixture; +mod player_hurt_fixture; +mod player_inventory_fixture; +mod player_travel_fixture; +mod portal_travel_fixture; +mod registered_player_combat_fixture; +mod registry_collision_scan_fixture; +mod registry_fall_ray_fixture; +mod registry_fluid_fixture; +mod replace_block_fixture; +mod restitution_fixture; +mod retrogen_data_fixture; +mod rule_test_fixture; +mod scattered_ore_fixture; +mod server_player_combat_fixture; +mod server_player_damage_fixture; +mod simple_block_fixture; +mod simple_container_fixture; +mod spawn_origin; +mod state_provider_fixture; +mod status_effect_fixture; +mod status_tick_fixture; +mod stepped_interpolation_fixture; +mod stored_consume_fixture; +mod stored_effect_attributes_fixture; +mod stored_effect_notifications_fixture; +mod structure_density_fixture; +mod suffocation_fixture; +mod swimming_fixture; +mod synced_bytes_fixture; +mod synced_floats_fixture; +mod teleport_consume_fixture; +mod terrain_fixture; +mod tick_fixture; +mod tree_feature_fixture; +mod use_flag_reaction_fixture; +mod use_remainder_fixture; +mod value_provider_fixture; +mod view_direction_fixture; +mod water_splash_fixture; +mod world_border_fixture; +mod world_fixture; +mod world_ray_fixture; +mod worldgen_random_fixture; + +probes! { + active_effect_tick_fixture, + active_effects_fixture, + anchor_fixture, + attribute_fixture, + attribute_health_fixture, + attribute_map_queries_fixture, + attribute_updates_fixture, + basic_feature_fixture, + biome_chunk_fixture, + biome_generation_fixture, + biome_placement_fixture, + biome_source_codec_fixture, + biome_source_fixture, + biome_temperature_fixture, + block_collision_scan_fixture, + block_entity_storage_fixture, + block_landing_fixture, + block_properties_fixture, + block_push_fixture, + block_state_codec_fixture, + block_support_fixture, + block_survival_fixture, + block_update_fixture, + blocking_item_damage_fixture, + blocking_rules_fixture, + bulk_section_fixture, + bundle_weight_fixture, + canyon_carver_fixture, + carving_geometry_fixture, + carving_mask_fixture, + cave_carver_fixture, + chunk_dump, + chunk_stage_fixture, + chunk_status_fixture, + climbing_fixture, + collision_context_fixture, + collision_fixture, + combat_rules_fixture, + component_durability_fixture, + component_patch_fixture, + consumable_emission_fixture, + consumable_fixture, + consume_effect_fixture, + damage_immunity_fixture, + damage_reduction_fixture, + damage_source_fixture, + datafix_world, + decoration_fixture, + decoration_region_fixture, + dynamic_support_fixture, + edge_backoff_fixture, + effect_attribute_modifiers_fixture, + effect_notifications_fixture, + effect_sync_fixture, + entity_attribute_fixture, + entity_collision_fixture, + entity_fluid_fixture, + entity_move_fixture, + entity_obstruction_fixture, + extra_items_fixture, + face_support_fixture, + face_visibility_fixture, + fall_damage_fixture, + feature_catalog_fixture, + feature_graph_fixture, + feature_placement_fixture, + feature_region_fixture, + feature_sort_fixture, + fill_layer_fixture, + fluid_box_fixture, + fluid_fixture, + fluid_flow_fixture, + fluid_occupancy_fixture, + fluid_shape_fixture, + food_fixture, + food_properties_fixture, + food_storage_fixture, + ground_state_fixture, + height_provider_fixture, + heightmap_fixture, + interaction_shape_fixture, + inventory_pickup_fixture, + inventory_tick_fixture, + inventory_use_fixture, + inventory_use_start_fixture, + item_after_use_fixture, + item_blocking_fixture, + item_cooldowns_fixture, + item_durability_fixture, + item_particles_fixture, + item_stack_storage_fixture, + item_template_fixture, + item_use_catalog_fixture, + item_use_fixture, + item_use_lifecycle_fixture, + item_use_start_fixture, + java_hash_map_fixture, + java_identity_map_fixture, + level_place_fixture, + level_shape_fixture, + live_attribute_updates_fixture, + live_attributes_fixture, + living_air_fixture, + living_damage_fixture, + living_fall_fixture, + living_fluid_fixture, + living_health_fixture, + living_hurt_fixture, + living_landing_fixture, + living_motion_fixture, + material_condition_fixture, + material_extension_fixture, + material_stage_fixture, + material_surface_fixture, + movement_emission_fixture, + movement_registry_fixture, + movement_support_fixture, + object_open_map_fixture, + object_open_set_fixture, + piston_movement_fixture, + piston_shape_fixture, + placement_fixture, + player_equipment_fixture, + player_food_fixture, + player_health_fixture, + player_hurt_fixture, + player_inventory_fixture, + player_travel_fixture, + portal_travel_fixture, + registered_player_combat_fixture, + registry_collision_scan_fixture, + registry_fall_ray_fixture, + registry_fluid_fixture, + replace_block_fixture, + restitution_fixture, + retrogen_data_fixture, + rule_test_fixture, + scattered_ore_fixture, + server_player_combat_fixture, + server_player_damage_fixture, + simple_block_fixture, + simple_container_fixture, + spawn_origin, + state_provider_fixture, + status_effect_fixture, + status_tick_fixture, + stepped_interpolation_fixture, + stored_consume_fixture, + stored_effect_attributes_fixture, + stored_effect_notifications_fixture, + structure_density_fixture, + suffocation_fixture, + swimming_fixture, + synced_bytes_fixture, + synced_floats_fixture, + teleport_consume_fixture, + terrain_fixture, + tick_fixture, + tree_feature_fixture, + use_flag_reaction_fixture, + use_remainder_fixture, + value_provider_fixture, + view_direction_fixture, + water_splash_fixture, + world_border_fixture, + world_fixture, + world_ray_fixture, + worldgen_random_fixture, +} diff --git a/crates/horizon-world/examples/material_condition_fixture.rs b/crates/horizon-world/examples/probe/material_condition_fixture.rs similarity index 99% rename from crates/horizon-world/examples/material_condition_fixture.rs rename to crates/horizon-world/examples/probe/material_condition_fixture.rs index 0cbb03168..86017d1eb 100644 --- a/crates/horizon-world/examples/material_condition_fixture.rs +++ b/crates/horizon-world/examples/probe/material_condition_fixture.rs @@ -646,8 +646,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let definitions = serde_json::from_str(&fs::read_to_string(dir.join("conditions.json"))?)?; diff --git a/crates/horizon-world/examples/material_extension_fixture.rs b/crates/horizon-world/examples/probe/material_extension_fixture.rs similarity index 98% rename from crates/horizon-world/examples/material_extension_fixture.rs rename to crates/horizon-world/examples/probe/material_extension_fixture.rs index a48943723..1d7170b6d 100644 --- a/crates/horizon-world/examples/material_extension_fixture.rs +++ b/crates/horizon-world/examples/probe/material_extension_fixture.rs @@ -189,8 +189,8 @@ where } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let noises = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; let biomes = serde_json::from_str(&fs::read_to_string(dir.join("biomes.json"))?)?; diff --git a/crates/horizon-world/examples/material_stage_fixture.rs b/crates/horizon-world/examples/probe/material_stage_fixture.rs similarity index 98% rename from crates/horizon-world/examples/material_stage_fixture.rs rename to crates/horizon-world/examples/probe/material_stage_fixture.rs index 6682b04b7..31a563f7c 100644 --- a/crates/horizon-world/examples/material_stage_fixture.rs +++ b/crates/horizon-world/examples/probe/material_stage_fixture.rs @@ -1,4 +1,5 @@ //! Original transport for complete surface-stage chunk comparison. +use crate::support::common::tag; use horizon_core::{ biome::{BiomeZoom, obfuscate_seed}, carving::CarvingMask, @@ -78,17 +79,6 @@ impl TerrainBlockStates for Properties<'_> { self.0[id.0 as usize] } } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } @@ -705,8 +695,8 @@ fn dump( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result, Box> { Ok(serde_json::from_str(&fs::read_to_string( diff --git a/crates/horizon-world/examples/material_surface_fixture.rs b/crates/horizon-world/examples/probe/material_surface_fixture.rs similarity index 97% rename from crates/horizon-world/examples/material_surface_fixture.rs rename to crates/horizon-world/examples/probe/material_surface_fixture.rs index c7cb93bbd..3b3373f86 100644 --- a/crates/horizon-world/examples/material_surface_fixture.rs +++ b/crates/horizon-world/examples/probe/material_surface_fixture.rs @@ -105,8 +105,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private directory"); let dir = Path::new(&arg); let noises: BTreeMap = serde_json::from_str(&fs::read_to_string(dir.join("noises.json"))?)?; diff --git a/crates/horizon-world/examples/movement_emission_fixture.rs b/crates/horizon-world/examples/probe/movement_emission_fixture.rs similarity index 92% rename from crates/horizon-world/examples/movement_emission_fixture.rs rename to crates/horizon-world/examples/probe/movement_emission_fixture.rs index 36439e118..70ef1b32b 100644 --- a/crates/horizon-world/examples/movement_emission_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_emission_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::{f64_bits, position}; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_emission::*; use serde_json::Value; @@ -15,23 +16,9 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } @@ -137,9 +124,9 @@ impl MovementEmissionWorld for World<'_> { let p = vector(&self.f["position"]); self.query(format!( "step {s} {:016x} {:016x} {:016x}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; self.mutate(); Ok(()) @@ -178,8 +165,8 @@ impl MovementEmissionWorld for World<'_> { Ok(emission(&self.f["flap_emission"])) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/movement_registry_fixture.rs b/crates/horizon-world/examples/probe/movement_registry_fixture.rs similarity index 95% rename from crates/horizon-world/examples/movement_registry_fixture.rs rename to crates/horizon-world/examples/probe/movement_registry_fixture.rs index a04f5c124..28a934ee5 100644 --- a/crates/horizon-world/examples/movement_registry_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_registry_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementLocation}; use horizon_world::{ @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -48,8 +42,8 @@ impl MovementBlockProvider for World<'_> { )) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |name: &str| -> Result> { diff --git a/crates/horizon-world/examples/movement_support_fixture.rs b/crates/horizon-world/examples/probe/movement_support_fixture.rs similarity index 93% rename from crates/horizon-world/examples/movement_support_fixture.rs rename to crates/horizon-world/examples/probe/movement_support_fixture.rs index 096559250..1206aa0dc 100644 --- a/crates/horizon-world/examples/movement_support_fixture.rs +++ b/crates/horizon-world/examples/probe/movement_support_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::position; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::movement_support::{self as support, MovementBlockWorld, MovementLocation}; use serde_json::Value; @@ -12,13 +13,6 @@ fn number(v: &Value) -> f64 { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn position(v: &Value) -> BlockPos { - BlockPos::new( - v[0].as_i64().unwrap() as i32, - v[1].as_i64().unwrap() as i32, - v[2].as_i64().unwrap() as i32, - ) -} struct World<'a> { input: &'a Value, out: &'a mut dyn Write, @@ -84,8 +78,8 @@ impl MovementBlockWorld for World<'_> { self.factor(id, "speed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_map_fixture.rs b/crates/horizon-world/examples/probe/object_open_map_fixture.rs similarity index 98% rename from crates/horizon-world/examples/object_open_map_fixture.rs rename to crates/horizon-world/examples/probe/object_open_map_fixture.rs index 63073aa8d..ae03169dd 100644 --- a/crates/horizon-world/examples/object_open_map_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_map_fixture.rs @@ -74,8 +74,8 @@ fn mutation(map: &mut ObjectOpenMap, keys: &[Key], op: &Value) -> Stri _ => panic!("mutation"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/object_open_set_fixture.rs b/crates/horizon-world/examples/probe/object_open_set_fixture.rs similarity index 96% rename from crates/horizon-world/examples/object_open_set_fixture.rs rename to crates/horizon-world/examples/probe/object_open_set_fixture.rs index d4c06f39d..c624d336d 100644 --- a/crates/horizon-world/examples/object_open_set_fixture.rs +++ b/crates/horizon-world/examples/probe/object_open_set_fixture.rs @@ -25,8 +25,8 @@ impl ObjectKey for Key { fn desc(key: Option<&Key>) -> String { key.map_or("null".into(), |k| format!("{}:{}", k.id, k.object)) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/piston_movement_fixture.rs b/crates/horizon-world/examples/probe/piston_movement_fixture.rs similarity index 79% rename from crates/horizon-world/examples/piston_movement_fixture.rs rename to crates/horizon-world/examples/probe/piston_movement_fixture.rs index 3c324aa00..804ccec2e 100644 --- a/crates/horizon-world/examples/piston_movement_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_movement_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::piston_movement::PistonMovement; use serde_json::Value; @@ -12,15 +13,8 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -45,18 +39,18 @@ fn main() -> Result<(), Box> { Ok(v) => writeln!( out, "movement {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?, Err(_) => writeln!(out, "error")?, } writeln!( out, "deltas {:016x} {:016x} {:016x}", - bits(state.deltas[0]), - bits(state.deltas[1]), - bits(state.deltas[2]) + f64_bits(state.deltas[0]), + f64_bits(state.deltas[1]), + f64_bits(state.deltas[2]) )?; writeln!(out, "tick {}", state.game_time)?; writeln!(out, "queries {calls}")?; diff --git a/crates/horizon-world/examples/piston_shape_fixture.rs b/crates/horizon-world/examples/probe/piston_shape_fixture.rs similarity index 71% rename from crates/horizon-world/examples/piston_shape_fixture.rs rename to crates/horizon-world/examples/probe/piston_shape_fixture.rs index 06c62803b..ec75a9502 100644 --- a/crates/horizon-world/examples/piston_shape_fixture.rs +++ b/crates/horizon-world/examples/probe/piston_shape_fixture.rs @@ -1,4 +1,5 @@ -use horizon_core::geometry::{Aabb, Axis, Direction, VoxelShape}; +use crate::support::shapes::emit; +use horizon_core::geometry::{Direction, VoxelShape}; use horizon_world::{ collision::CachedCollisionRegistry, dynamic_support::{DynamicSupport, DynamicSupportWorld}, @@ -12,70 +13,6 @@ use std::{ io::{self, Write}, path::Path, }; -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct World<'a, 'r, W> { collisions: &'a CachedCollisionRegistry<'r>, dynamic: &'a [Option], @@ -125,8 +62,8 @@ fn number(v: &Value) -> f32 { fn float_bits(v: f32) -> u32 { if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/placement_fixture.rs b/crates/horizon-world/examples/probe/placement_fixture.rs similarity index 94% rename from crates/horizon-world/examples/placement_fixture.rs rename to crates/horizon-world/examples/probe/placement_fixture.rs index b3e6c4747..6214e630e 100644 --- a/crates/horizon-world/examples/placement_fixture.rs +++ b/crates/horizon-world/examples/probe/placement_fixture.rs @@ -1,6 +1,5 @@ //! Transport for placement decoding, emissions, failures and random state. -#[path = "support/placement_queries.rs"] -mod queries; +use crate::support::placement_queries as queries; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::worldgen::{anchor::WorldGenerationContext, placement::PlacementModifier}; use serde_json::Value; @@ -67,8 +66,8 @@ fn fixture( writeln!(out.borrow_mut(), "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_equipment_fixture.rs b/crates/horizon-world/examples/probe/player_equipment_fixture.rs similarity index 98% rename from crates/horizon-world/examples/player_equipment_fixture.rs rename to crates/horizon-world/examples/probe/player_equipment_fixture.rs index a7349b78c..0a356e31d 100644 --- a/crates/horizon-world/examples/player_equipment_fixture.rs +++ b/crates/horizon-world/examples/probe/player_equipment_fixture.rs @@ -131,8 +131,8 @@ impl EquipWorld for World { } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_food_fixture.rs b/crates/horizon-world/examples/probe/player_food_fixture.rs similarity index 93% rename from crates/horizon-world/examples/player_food_fixture.rs rename to crates/horizon-world/examples/probe/player_food_fixture.rs index 7478be35f..186ec6332 100644 --- a/crates/horizon-world/examples/player_food_fixture.rs +++ b/crates/horizon-world/examples/probe/player_food_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ food::FoodData, player_food::{self, PlayerFoodWorld, StoredPlayerFood}, @@ -11,13 +12,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} struct World<'a> { f: &'a Value, out: &'a mut dyn Write, @@ -68,7 +62,7 @@ impl PlayerFoodWorld for World<'_> { } fn add_exhaustion_direct(&mut self, v: f32) -> io::Result<()> { let i = self.index("direct"); - self.query(&format!("exhaust {i} {:08x}", bits(v)))?; + self.query(&format!("exhaust {i} {:08x}", f32_bits(v)))?; self.foods[i].add_exhaustion(v); Ok(()) } @@ -96,8 +90,8 @@ fn run(w: &mut W, f: &Value) -> Result, W::Erro _ => panic!("mode"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -136,7 +130,7 @@ fn main() -> Result<(), Box> { w.out, "food {i} {} {:08x}", food.food, - bits(food.exhaustion) + f32_bits(food.exhaustion) )?; } writeln!(w.out, "queries {}", w.calls)?; diff --git a/crates/horizon-world/examples/player_health_fixture.rs b/crates/horizon-world/examples/probe/player_health_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_health_fixture.rs rename to crates/horizon-world/examples/probe/player_health_fixture.rs index f7b687f65..24163bb75 100644 --- a/crates/horizon-world/examples/player_health_fixture.rs +++ b/crates/horizon-world/examples/probe/player_health_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::{ attributes::{ Modifier, Operation, @@ -19,20 +20,13 @@ fn single(v: &Value) -> f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.op["pack_callback"].as_bool().unwrap() { @@ -96,8 +90,8 @@ impl State { .unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { @@ -145,7 +139,7 @@ fn main() -> Result<(), Box> { .bind(&mut cb) .absorption() .map_err(|_| ()) - .and_then(|v| writeln!(cb.out, "float {:08x}", bits(v)).map_err(|_| ())), + .and_then(|v| writeln!(cb.out, "float {:08x}", f32_bits(v)).map_err(|_| ())), "hurt" => state .bind(&mut cb) .is_hurt() @@ -227,8 +221,8 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "state {:08x} {:08x} {} {} {} {} {} {}", - bits(state.data.get(ids.health).unwrap()), - bits(state.data.get(ids.absorption).unwrap()), + f32_bits(state.data.get(ids.health).unwrap()), + f32_bits(state.data.get(ids.absorption).unwrap()), state.data.is_dirty(), state.data.item_dirty(ids.health).unwrap(), state.data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/player_hurt_fixture.rs b/crates/horizon-world/examples/probe/player_hurt_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_hurt_fixture.rs rename to crates/horizon-world/examples/probe/player_hurt_fixture.rs index 54a5ed5e4..6e77abf71 100644 --- a/crates/horizon-world/examples/player_hurt_fixture.rs +++ b/crates/horizon-world/examples/probe/player_hurt_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ food::Difficulty, @@ -15,19 +16,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -134,7 +128,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -142,10 +136,10 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, s: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt {:08x} {}", bits(v), state(s)))?; + self.event(&format!("hurt {:08x} {}", f32_bits(v), state(s)))?; self.hit = true; self.recorded = v; if self.flag("mutate_hit") { @@ -163,7 +157,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -187,7 +181,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -263,8 +257,8 @@ impl ServerPlayerHurtWorld for Env<'_> { Ok(self.flag("can_harm")) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -303,7 +297,7 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; diff --git a/crates/horizon-world/examples/player_inventory_fixture.rs b/crates/horizon-world/examples/probe/player_inventory_fixture.rs similarity index 99% rename from crates/horizon-world/examples/player_inventory_fixture.rs rename to crates/horizon-world/examples/probe/player_inventory_fixture.rs index a3e2625e2..418fb9a3e 100644 --- a/crates/horizon-world/examples/player_inventory_fixture.rs +++ b/crates/horizon-world/examples/probe/player_inventory_fixture.rs @@ -142,8 +142,8 @@ impl Output { writeln!(self.out, "empty {e}").unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/player_travel_fixture.rs b/crates/horizon-world/examples/probe/player_travel_fixture.rs similarity index 94% rename from crates/horizon-world/examples/player_travel_fixture.rs rename to crates/horizon-world/examples/probe/player_travel_fixture.rs index 47adeaeb7..e4d493662 100644 --- a/crates/horizon-world/examples/player_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/player_travel_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::player_travel::*; use serde_json::Value; @@ -15,18 +16,16 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn fbits(v: f32) -> u32 { if v.is_nan() { 0x7fc00000 } else { v.to_bits() } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a> { f: &'a Value, @@ -115,8 +114,8 @@ impl PlayerTravelWorld for World<'_> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/portal_travel_fixture.rs b/crates/horizon-world/examples/probe/portal_travel_fixture.rs similarity index 98% rename from crates/horizon-world/examples/portal_travel_fixture.rs rename to crates/horizon-world/examples/probe/portal_travel_fixture.rs index b0843e411..cda3ae248 100644 --- a/crates/horizon-world/examples/portal_travel_fixture.rs +++ b/crates/horizon-world/examples/probe/portal_travel_fixture.rs @@ -246,8 +246,8 @@ fn run(case: &Value, b: &Behaviours, air: BlockStateId, out: &mut Vec) { )); } -fn main() -> Result<(), Box> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Box> { + let mut args = crate::args().skip(1); let resources = args.next().expect("resource directory"); let cases = args.next().expect("case file"); let output = args.next().expect("output file"); diff --git a/crates/horizon-world/examples/registered_player_combat_fixture.rs b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs similarity index 95% rename from crates/horizon-world/examples/registered_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/registered_player_combat_fixture.rs index 01afec289..c70881165 100644 --- a/crates/horizon-world/examples/registered_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/registered_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::damage_source::{ Catalog as DamageCatalog, DamageSource, EntityKind, SourceWorld, @@ -31,19 +32,12 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -151,7 +145,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -159,7 +153,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -171,7 +165,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { if !self @@ -197,7 +191,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -280,7 +274,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -290,7 +284,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -329,7 +323,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.source.bypasses(b)) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -387,7 +381,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -401,8 +395,8 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let damage_catalog = DamageCatalog::from_json( &serde_json::from_str(&fs::read_to_string(dir.join("damage/catalog.json"))?)?, @@ -513,16 +507,16 @@ fn main() -> Result<(), Box> { e.out, "state {} {:08x} {} {}", state(&s), - bits(recorded), + f32_bits(recorded), e.hit, e.calls )?; writeln!( e.out, "storage {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/registry_collision_scan_fixture.rs b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs similarity index 92% rename from crates/horizon-world/examples/registry_collision_scan_fixture.rs rename to crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs index 9e3a19914..b66812142 100644 --- a/crates/horizon-world/examples/registry_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs @@ -1,4 +1,5 @@ //! Integrated registry/cursor differential transport using resident TerrainChunk storage. +use crate::support::shapes::{emit, values}; use horizon_core::{ geometry::{Aabb, Axis, Vec3, VoxelShape}, position::{BlockPos, ChunkPos}, @@ -43,70 +44,6 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} struct Trace { out: io::BufWriter, calls: i32, @@ -382,8 +319,8 @@ impl CollisionChunks for World<'_> { &mut self.chunks.get_mut(&(p.x, p.z)).unwrap().1 } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/registry_fall_ray_fixture.rs b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs similarity index 94% rename from crates/horizon-world/examples/registry_fall_ray_fixture.rs rename to crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs index 3f2ebce75..c4f61644c 100644 --- a/crates/horizon-world/examples/registry_fall_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ entity_obstruction::EntityIdentity, @@ -21,13 +22,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -86,8 +80,8 @@ impl FallRayWorld for World<'_, '_, '_> { Ok(self.f["delay"].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let read = |n: &str| -> Result> { @@ -181,9 +175,9 @@ fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/crates/horizon-world/examples/registry_fluid_fixture.rs b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs similarity index 97% rename from crates/horizon-world/examples/registry_fluid_fixture.rs rename to crates/horizon-world/examples/probe/registry_fluid_fixture.rs index de6e111a6..45cd272b0 100644 --- a/crates/horizon-world/examples/registry_fluid_fixture.rs +++ b/crates/horizon-world/examples/probe/registry_fluid_fixture.rs @@ -67,8 +67,8 @@ impl DynamicSupportWorld for World<'_> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let load = |n: &str| -> Result<_, Box> { diff --git a/crates/horizon-world/examples/replace_block_fixture.rs b/crates/horizon-world/examples/probe/replace_block_fixture.rs similarity index 92% rename from crates/horizon-world/examples/replace_block_fixture.rs rename to crates/horizon-world/examples/probe/replace_block_fixture.rs index 7a8d00363..d0a742f99 100644 --- a/crates/horizon-world/examples/replace_block_fixture.rs +++ b/crates/horizon-world/examples/probe/replace_block_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -135,19 +136,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/restitution_fixture.rs b/crates/horizon-world/examples/probe/restitution_fixture.rs similarity index 93% rename from crates/horizon-world/examples/restitution_fixture.rs rename to crates/horizon-world/examples/probe/restitution_fixture.rs index d32532a82..0d630274e 100644 --- a/crates/horizon-world/examples/restitution_fixture.rs +++ b/crates/horizon-world/examples/probe/restitution_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_world::{ movement_restitution::{RestitutionInput, RestitutionWorld, restitute_movement}, @@ -18,19 +19,12 @@ fn single(v: &Value) -> f32 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn vector_text(prefix: &str, v: Vec3) -> String { format!( "{prefix} {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) ) } struct World<'a, W> { @@ -102,7 +96,7 @@ impl RestitutionWorld for World<'_, W> { p.x, p.y, p.z, - bits(fall) + f64_bits(fall) ))?; if self.f["mutate"].as_bool().unwrap() { self.velocity = Vec3::new(17.0, 18.0, 19.0); @@ -121,8 +115,8 @@ impl RestitutionWorld for World<'_, W> { Ok(()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/retrogen_data_fixture.rs b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs similarity index 97% rename from crates/horizon-world/examples/retrogen_data_fixture.rs rename to crates/horizon-world/examples/probe/retrogen_data_fixture.rs index 1f35cb363..3980d1234 100644 --- a/crates/horizon-world/examples/retrogen_data_fixture.rs +++ b/crates/horizon-world/examples/probe/retrogen_data_fixture.rs @@ -51,8 +51,8 @@ fn tag(row: &Value) -> Tag { _ => panic!("unknown tag"), } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for (index, line) in fs::read_to_string(&args[1])?.lines().enumerate() { writeln!(out, "case {index}")?; diff --git a/crates/horizon-world/examples/rule_test_fixture.rs b/crates/horizon-world/examples/probe/rule_test_fixture.rs similarity index 85% rename from crates/horizon-world/examples/rule_test_fixture.rs rename to crates/horizon-world/examples/probe/rule_test_fixture.rs index 31fa4c436..42a25532c 100644 --- a/crates/horizon-world/examples/rule_test_fixture.rs +++ b/crates/horizon-world/examples/probe/rule_test_fixture.rs @@ -1,4 +1,5 @@ //! Differential transport for replacement rules over pinned block identities. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -41,19 +42,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/scattered_ore_fixture.rs b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs similarity index 93% rename from crates/horizon-world/examples/scattered_ore_fixture.rs rename to crates/horizon-world/examples/probe/scattered_ore_fixture.rs index bc9dd9200..91b6821b7 100644 --- a/crates/horizon-world/examples/scattered_ore_fixture.rs +++ b/crates/horizon-world/examples/probe/scattered_ore_fixture.rs @@ -1,4 +1,5 @@ //! Feature world transport retaining ordered mutations and partial failures. +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -159,19 +160,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/server_player_combat_fixture.rs b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs similarity index 95% rename from crates/horizon-world/examples/server_player_combat_fixture.rs rename to crates/horizon-world/examples/probe/server_player_combat_fixture.rs index ac911a7c8..9607dcec2 100644 --- a/crates/horizon-world/examples/server_player_combat_fixture.rs +++ b/crates/horizon-world/examples/probe/server_player_combat_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::damage_immunity::{DamageRule, ImmunityTag, ImmunityWorld}; use horizon_world::living_hurt::{HurtState, HurtTag, HurtWorld}; use horizon_world::{ @@ -84,19 +85,12 @@ impl FixtureAttributes for Live { fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn state(s: &HurtState<()>) -> String { format!( "{} {} {:08x} {} {} {} {}", s.no_action_time, s.cooldown, - bits(s.last_hurt), + f32_bits(s.last_hurt), s.hurt_duration, s.hurt_time, s.last_source.is_some(), @@ -208,7 +202,7 @@ impl HurtWorld for Env<'_> { Ok(self.flag("component")) } fn apply_blocking(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result { - self.event(&format!("blocking {:08x}", bits(v)))?; + self.event(&format!("blocking {:08x}", f32_bits(v)))?; Ok(single(&self.op["blocked"])) } fn helmet_empty(&mut self, _: &mut HurtState<()>) -> io::Result { @@ -216,7 +210,7 @@ impl HurtWorld for Env<'_> { Ok(!self.flag("helmet")) } fn hurt_helmet(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { - self.event(&format!("hurt-helmet {:08x}", bits(v))) + self.event(&format!("hurt-helmet {:08x}", f32_bits(v))) } fn actually_hurt(&mut self, _s: &mut HurtState<()>, _v: f32) -> io::Result<()> { panic!("combat binding supplies actual inner damage") @@ -228,7 +222,7 @@ impl HurtWorld for Env<'_> { Ok(()) } fn knockback(&mut self, _: &mut HurtState<()>, v: f32, b: bool) -> io::Result<()> { - self.event(&format!("knockback {:08x} {b}", bits(v))) + self.event(&format!("knockback {:08x} {b}", f32_bits(v))) } fn death_protection(&mut self, _: &mut HurtState<()>) -> io::Result { self.event("tag bypasses_invulnerability")?; @@ -252,7 +246,7 @@ impl HurtWorld for Env<'_> { fn effects_on_hurt(&mut self, _: &mut HurtState<()>, v: f32) -> io::Result<()> { self.event("effects")?; for i in 0..self.op["effects"].as_u64().unwrap() { - self.event(&format!("effect {i} {:08x}", bits(v)))?; + self.event(&format!("effect {i} {:08x}", f32_bits(v)))?; } Ok(()) } @@ -337,7 +331,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -347,7 +341,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -393,7 +387,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut A, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { a.configure("minecraft:armor", number(&self.op["armor_after"]), None); } @@ -447,7 +441,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; self.hit = true; Ok(()) @@ -461,10 +455,10 @@ impl CombatEnvironment for Env<'_> { self.dead } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); - if std::env::args().nth(2).as_deref() == Some("--live") { + if crate::args().nth(2).as_deref() == Some("--live") { run::(dir, "rust-live.txt") } else { run::(dir, "rust.txt") @@ -554,16 +548,16 @@ fn run(dir: &Path, output: &str) -> Result<(), Box f32 { fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn values(v: Option<&[FloatValue]>) -> String { match v { None => "none".into(), Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -69,7 +63,7 @@ impl Observer for Env<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty() ))?; if self.flag("pack_callback") { @@ -115,7 +109,7 @@ impl ServerDamageEnvironment for Env<'_> { Ok(self.flag(&format!("bypass_{n}"))) } fn hurt_armor(&mut self, a: &mut EntityAttributes, v: f32) -> io::Result<()> { - self.event(&format!("hurt-armor {:08x}", bits(v)))?; + self.event(&format!("hurt-armor {:08x}", f32_bits(v)))?; if self.flag("break_armor") { let id = a.catalog().id("minecraft:armor").unwrap(); a.edit(id, |a, o| { @@ -174,7 +168,7 @@ impl ServerDamageEnvironment for Env<'_> { } fn record_damage(&mut self, v: f32) -> io::Result<()> { self.event("tracker")?; - self.event(&format!("record {:08x}", bits(v)))?; + self.event(&format!("record {:08x}", f32_bits(v)))?; self.recorded = v; Ok(()) } @@ -182,8 +176,8 @@ impl ServerDamageEnvironment for Env<'_> { self.event("damage-event") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let ids: Value = serde_json::from_str(&fs::read_to_string(dir.join("ids.json"))?)?; let ids = PlayerFloatIds { @@ -255,10 +249,10 @@ fn main() -> Result<(), Box> { writeln!( env.out, "state {:08x} {:08x} {:08x} {:08x} {} {} {} {}", - bits(data.get(ids.health).unwrap()), - bits(data.get(ids.absorption).unwrap()), - bits(food.exhaustion), - bits(recorded), + f32_bits(data.get(ids.health).unwrap()), + f32_bits(data.get(ids.absorption).unwrap()), + f32_bits(food.exhaustion), + f32_bits(recorded), data.is_dirty(), data.item_dirty(ids.health).unwrap(), data.item_dirty(ids.absorption).unwrap(), diff --git a/crates/horizon-world/examples/simple_block_fixture.rs b/crates/horizon-world/examples/probe/simple_block_fixture.rs similarity index 99% rename from crates/horizon-world/examples/simple_block_fixture.rs rename to crates/horizon-world/examples/probe/simple_block_fixture.rs index 742f3b39f..232e56f94 100644 --- a/crates/horizon-world/examples/simple_block_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_block_fixture.rs @@ -553,8 +553,8 @@ fn fixture( )?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/simple_container_fixture.rs b/crates/horizon-world/examples/probe/simple_container_fixture.rs similarity index 98% rename from crates/horizon-world/examples/simple_container_fixture.rs rename to crates/horizon-world/examples/probe/simple_container_fixture.rs index 44f9a382a..c6aef9c2a 100644 --- a/crates/horizon-world/examples/simple_container_fixture.rs +++ b/crates/horizon-world/examples/probe/simple_container_fixture.rs @@ -120,8 +120,8 @@ impl ContainerHooks for World { self.event(c, "changed") } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/spawn_origin.rs b/crates/horizon-world/examples/probe/spawn_origin.rs similarity index 76% rename from crates/horizon-world/examples/spawn_origin.rs rename to crates/horizon-world/examples/probe/spawn_origin.rs index 727b25a91..7162a00a8 100644 --- a/crates/horizon-world/examples/spawn_origin.rs +++ b/crates/horizon-world/examples/probe/spawn_origin.rs @@ -3,6 +3,7 @@ //! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines. //! //! usage: spawn_origin ... +use crate::support::common::tag; use horizon_world::{ DATA_VERSION, nbt::Tag, @@ -14,17 +15,6 @@ use std::{fs, path::Path}; type Error = Box; -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; let states = facts["states"].as_array().ok_or("facts states")?; @@ -39,8 +29,8 @@ fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { Ok(Box::leak(Box::new(registry))) } -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); +pub fn main() -> Result<(), Error> { + let mut args = crate::args().skip(1); let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?; for seed in args { diff --git a/crates/horizon-world/examples/state_provider_fixture.rs b/crates/horizon-world/examples/probe/state_provider_fixture.rs similarity index 97% rename from crates/horizon-world/examples/state_provider_fixture.rs rename to crates/horizon-world/examples/probe/state_provider_fixture.rs index e8a8f9f5a..6164e5d6c 100644 --- a/crates/horizon-world/examples/state_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/state_provider_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::tag; use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom, XoroshiroRandom}; use horizon_world::{ DATA_VERSION, @@ -288,19 +289,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let registry = BlockRegistry::from_nbt(&Tag::compound([ diff --git a/crates/horizon-world/examples/status_effect_fixture.rs b/crates/horizon-world/examples/probe/status_effect_fixture.rs similarity index 97% rename from crates/horizon-world/examples/status_effect_fixture.rs rename to crates/horizon-world/examples/probe/status_effect_fixture.rs index 759aad818..c1307dd3a 100644 --- a/crates/horizon-world/examples/status_effect_fixture.rs +++ b/crates/horizon-world/examples/probe/status_effect_fixture.rs @@ -138,8 +138,8 @@ fn run(f: Value, out: &mut dyn Write) { dump(out, &slots, &mut ids); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/status_tick_fixture.rs b/crates/horizon-world/examples/probe/status_tick_fixture.rs similarity index 98% rename from crates/horizon-world/examples/status_tick_fixture.rs rename to crates/horizon-world/examples/probe/status_tick_fixture.rs index 22aa0d412..23492971c 100644 --- a/crates/horizon-world/examples/status_tick_fixture.rs +++ b/crates/horizon-world/examples/probe/status_tick_fixture.rs @@ -210,8 +210,8 @@ fn run(f: Value, out: &mut dyn Write) { w.all(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/stepped_interpolation_fixture.rs b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stepped_interpolation_fixture.rs rename to crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs index d2228d8b5..568e5ded8 100644 --- a/crates/horizon-world/examples/stepped_interpolation_fixture.rs +++ b/crates/horizon-world/examples/probe/stepped_interpolation_fixture.rs @@ -10,8 +10,8 @@ fn set_rot(entity: &mut PosRot, yaw: f32, pitch: f32) { entity.pitch = (pitch % 360.0 % 360.0).clamp(-90.0, 90.0); } -fn main() { - let args: Vec = std::env::args().collect(); +pub fn main() { + let args: Vec = crate::args().collect(); let input = std::fs::read_to_string(&args[1]).expect("input"); let mut out = String::new(); let mut handler = SteppedInterpolation::new(0); diff --git a/crates/horizon-world/examples/stored_consume_fixture.rs b/crates/horizon-world/examples/probe/stored_consume_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stored_consume_fixture.rs rename to crates/horizon-world/examples/probe/stored_consume_fixture.rs index 7fd9abc91..8f8f6046a 100644 --- a/crates/horizon-world/examples/stored_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_consume_fixture.rs @@ -390,9 +390,9 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); - let side = std::env::args().nth(2).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); + let side = crate::args().nth(2).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?); for line in fs::read_to_string(dir.join(format!("inputs-{side}.txt")))?.lines() { diff --git a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs similarity index 96% rename from crates/horizon-world/examples/stored_effect_attributes_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs index 6abc4f79f..10ae7bf63 100644 --- a/crates/horizon-world/examples/stored_effect_attributes_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_hex; use horizon_world::{ attribute_map::AttributeMap, attributes::{AttributeError, Definition, Instance, Modifier, Observer, Operation}, @@ -38,16 +39,6 @@ enum Stop { Null, Bounds, } -fn bits(v: f64) -> String { - format!( - "{:016x}", - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - ) -} fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } @@ -118,7 +109,7 @@ impl World { format!( "{id}:{}:{}:{}", m.id(), - bits(m.amount()), + f64_hex(m.amount()), m.operation() as u8 ) }) @@ -162,9 +153,9 @@ impl World { let prefix = format!( "instance {id} {} {} {} {}", n.key.id, - bits(a.base_value()), + f64_hex(a.base_value()), a.is_dirty(), - bits(a.cached_value()) + f64_hex(a.cached_value()) ); let all = a.modifiers().to_vec(); let permanent = a.permanent_modifiers().to_vec(); @@ -348,8 +339,8 @@ fn effect_error(e: effects::Error) -> Stop { effects::Error::MissingTemplate | effects::Error::Cursor(_) => Stop::Null, } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); for line in fs::read_to_string(dir.join(format!("inputs-{}.txt", args[2])))?.lines() { @@ -469,7 +460,7 @@ fn main() -> Result<(), Box> { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( diff --git a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs similarity index 98% rename from crates/horizon-world/examples/stored_effect_notifications_fixture.rs rename to crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs index 96c089857..9dccc7cf8 100644 --- a/crates/horizon-world/examples/stored_effect_notifications_fixture.rs +++ b/crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs @@ -169,7 +169,7 @@ mod integration { } } pub fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); + let args: Vec<_> = crate::args().collect(); let dir = Path::new(&args[1]); let mut out = io::BufWriter::new(fs::File::create(dir.join(format!("rust-{}.txt", args[2])))?); @@ -329,7 +329,7 @@ mod integration { "value" => world .handle(op["instance"].as_i64().unwrap()) .and_then(|h| h.ok_or(Stop::Null)) - .map(|h| bits(world.instances[h.id].value.as_mut().unwrap().value())), + .map(|h| f64_hex(world.instances[h.id].value.as_mut().unwrap().value())), _ => world.raw(&mut map, op).map(|()| "ok".into()), }; world.logs.push(format!( @@ -352,6 +352,6 @@ mod integration { Ok(()) } } -fn main() -> Result<(), Box> { +pub fn main() -> Result<(), Box> { integration::run() } diff --git a/crates/horizon-world/examples/structure_density_fixture.rs b/crates/horizon-world/examples/probe/structure_density_fixture.rs similarity index 96% rename from crates/horizon-world/examples/structure_density_fixture.rs rename to crates/horizon-world/examples/probe/structure_density_fixture.rs index 55ef66f83..2159bc566 100644 --- a/crates/horizon-world/examples/structure_density_fixture.rs +++ b/crates/horizon-world/examples/probe/structure_density_fixture.rs @@ -31,8 +31,8 @@ fn bits(value: f32) -> u32 { value.to_bits() } } -fn main() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); +pub fn main() -> Result<(), Box> { + let args: Vec<_> = crate::args().collect(); let mut out = io::BufWriter::new(fs::File::create(&args[2])?); for line in fs::read_to_string(&args[1])?.lines() { let f: Value = serde_json::from_str(line)?; diff --git a/crates/horizon-world/examples/suffocation_fixture.rs b/crates/horizon-world/examples/probe/suffocation_fixture.rs similarity index 97% rename from crates/horizon-world/examples/suffocation_fixture.rs rename to crates/horizon-world/examples/probe/suffocation_fixture.rs index 79a3ccfa0..3e1683394 100644 --- a/crates/horizon-world/examples/suffocation_fixture.rs +++ b/crates/horizon-world/examples/probe/suffocation_fixture.rs @@ -58,8 +58,8 @@ impl DynamicCollisionWorld for World<'_, W> { Ok(None) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name| -> Result<_, Box> { Ok( diff --git a/crates/horizon-world/examples/probe/support/common.rs b/crates/horizon-world/examples/probe/support/common.rs new file mode 100644 index 000000000..17c453363 --- /dev/null +++ b/crates/horizon-world/examples/probe/support/common.rs @@ -0,0 +1,49 @@ +//! Number formats and JSON readers several probes share. +use horizon_core::position::BlockPos; +use horizon_world::nbt::Tag; +use serde_json::Value; + +/// An f64's bits, every NaN as Java's canonical one (Double.doubleToLongBits). +pub fn f64_bits(v: f64) -> u64 { + if v.is_nan() { + f64::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// An f32's bits, every NaN as Java's canonical one (Float.floatToIntBits). +pub fn f32_bits(v: f32) -> u32 { + if v.is_nan() { + f32::NAN.to_bits() + } else { + v.to_bits() + } +} + +/// f64_bits as 16 hex digits. +pub fn f64_hex(v: f64) -> String { + format!("{:016x}", f64_bits(v)) +} + +/// Registry metadata from the oracle's JSON as NBT: strings, ints, lists and compounds. +pub fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(m) => { + Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} + +/// A block position from a JSON `[x, y, z]`. +pub fn position(v: &Value) -> BlockPos { + BlockPos::new( + v[0].as_i64().unwrap() as i32, + v[1].as_i64().unwrap() as i32, + v[2].as_i64().unwrap() as i32, + ) +} diff --git a/crates/horizon-world/examples/support/decoration_storage.rs b/crates/horizon-world/examples/probe/support/decoration_storage.rs similarity index 100% rename from crates/horizon-world/examples/support/decoration_storage.rs rename to crates/horizon-world/examples/probe/support/decoration_storage.rs diff --git a/crates/horizon-world/examples/support/placement_queries.rs b/crates/horizon-world/examples/probe/support/placement_queries.rs similarity index 100% rename from crates/horizon-world/examples/support/placement_queries.rs rename to crates/horizon-world/examples/probe/support/placement_queries.rs diff --git a/crates/horizon-world/examples/probe/support/shapes.rs b/crates/horizon-world/examples/probe/support/shapes.rs new file mode 100644 index 000000000..eed5f436d --- /dev/null +++ b/crates/horizon-world/examples/probe/support/shapes.rs @@ -0,0 +1,85 @@ +//! Shapes and boxes printed the same way by the collision probes. +use super::common::f64_bits; +use horizon_core::geometry::{Aabb, Axis, VoxelShape}; +use std::io::{self, Write}; + +pub fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { + writeln!( + out, + "shape {} {} {}", + shape.is_empty(), + shape.boxes().len(), + shape.is_cube() + )?; + for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { + values(out, name, shape.coordinates(axis).iter().copied())?; + } + let axes = shape.cube_coordinate_axes(); + writeln!( + out, + "axes {}", + u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) + )?; + values( + out, + "extrema", + Axis::ALL + .map(|a| shape.min(a)) + .into_iter() + .chain(Axis::ALL.map(|a| shape.max(a))), + )?; + match shape.bounds() { + Some(b) => box_values(out, "bounds", b)?, + None => writeln!(out, "bounds none")?, + } + for b in shape.boxes() { + box_values(out, "box", *b)?; + } + Ok(()) +} + +/// `label` and each value's bits in hex, NaN as Java's canonical one. +pub fn values( + out: &mut impl Write, + label: &str, + values: impl IntoIterator, +) -> io::Result<()> { + write!(out, "{label}")?; + for v in values { + let bits = if v.is_nan() { + 0x7ff8_0000_0000_0000 + } else { + v.to_bits() + }; + write!(out, " {bits:016x}")?; + } + writeln!(out) +} + +pub fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { + values( + out, + label, + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ], + ) +} + +/// `label` and the box's six bounds' bits in hex. +pub fn bounds(label: &str, b: Aabb) -> String { + format!( + "{label} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + f64_bits(b.min(Axis::X)), + f64_bits(b.min(Axis::Y)), + f64_bits(b.min(Axis::Z)), + f64_bits(b.max(Axis::X)), + f64_bits(b.max(Axis::Y)), + f64_bits(b.max(Axis::Z)) + ) +} diff --git a/crates/horizon-world/examples/swimming_fixture.rs b/crates/horizon-world/examples/probe/swimming_fixture.rs similarity index 96% rename from crates/horizon-world/examples/swimming_fixture.rs rename to crates/horizon-world/examples/probe/swimming_fixture.rs index ebf58cf8b..b31c3a109 100644 --- a/crates/horizon-world/examples/swimming_fixture.rs +++ b/crates/horizon-world/examples/probe/swimming_fixture.rs @@ -79,8 +79,8 @@ impl PlayerSwimmingWorld for World<'_> { self.f["flying"].as_bool().unwrap() } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_bytes_fixture.rs b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs similarity index 98% rename from crates/horizon-world/examples/synced_bytes_fixture.rs rename to crates/horizon-world/examples/probe/synced_bytes_fixture.rs index 288e5fa7c..b6932a4fe 100644 --- a/crates/horizon-world/examples/synced_bytes_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_bytes_fixture.rs @@ -114,8 +114,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/synced_floats_fixture.rs b/crates/horizon-world/examples/probe/synced_floats_fixture.rs similarity index 91% rename from crates/horizon-world/examples/synced_floats_fixture.rs rename to crates/horizon-world/examples/probe/synced_floats_fixture.rs index 4eb2e8046..7f649c18b 100644 --- a/crates/horizon-world/examples/synced_floats_fixture.rs +++ b/crates/horizon-world/examples/probe/synced_floats_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f32_bits; use horizon_world::synced_floats::{DataError, FloatValue, Observer, SyncedFloats}; use serde_json::Value; use std::{ @@ -8,13 +9,6 @@ use std::{ fn single(v: &Value) -> f32 { f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn bits(v: f32) -> u32 { - if v.is_nan() { - f32::NAN.to_bits() - } else { - v.to_bits() - } -} fn parse(v: &Value) -> Vec { v.as_array() .unwrap() @@ -31,7 +25,7 @@ fn values(v: Option<&[FloatValue]>) -> String { Some([]) => "empty".into(), Some(v) => v .iter() - .map(|v| format!("{}:{:08x}", v.id, bits(v.value))) + .map(|v| format!("{}:{:08x}", v.id, f32_bits(v.value))) .collect::>() .join(","), } @@ -59,7 +53,7 @@ impl Observer for Callback<'_> { fn updated(&mut self, data: &mut SyncedFloats, id: u8) -> io::Result<()> { self.event(&format!( "updated {id} {:08x} {} {}", - bits(data.get(id).unwrap()), + f32_bits(data.get(id).unwrap()), data.is_dirty(), data.item_dirty(id).unwrap() ))?; @@ -102,8 +96,8 @@ impl Observer for Callback<'_> { self.event(&format!("assigned {}", values(Some(v)))) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -129,7 +123,7 @@ fn main() -> Result<(), Box> { ), "assign" => data.assign(&parse(&op["values"]), &mut cb), "get" => data.get(id).map_err(DataError::UnknownId).and_then(|v| { - writeln!(cb.out, "get {:08x}", bits(v)).map_err(DataError::Observer) + writeln!(cb.out, "get {:08x}", f32_bits(v)).map_err(DataError::Observer) }), "pack" => writeln!(cb.out, "packed {}", values(data.take_dirty().as_deref())) .map_err(DataError::Observer), @@ -149,7 +143,7 @@ fn main() -> Result<(), Box> { writeln!( cb.out, "state {id} {:08x} {} {}", - bits(data.get(*id).unwrap()), + f32_bits(data.get(*id).unwrap()), data.item_dirty(*id).unwrap(), data.is_default(*id).unwrap() )?; diff --git a/crates/horizon-world/examples/teleport_consume_fixture.rs b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs similarity index 92% rename from crates/horizon-world/examples/teleport_consume_fixture.rs rename to crates/horizon-world/examples/probe/teleport_consume_fixture.rs index 0c21b359c..595fa3855 100644 --- a/crates/horizon-world/examples/teleport_consume_fixture.rs +++ b/crates/horizon-world/examples/probe/teleport_consume_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, position::BlockPos, @@ -13,13 +14,6 @@ use std::{ fn n(v: &Value, k: &str) -> i32 { v[k].as_i64().unwrap() as i32 } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} struct World<'a, R> { f: Value, out: &'a mut dyn Write, @@ -63,10 +57,10 @@ impl World<'_, R> { self.attempts, self.changed, self.riding, - bits(self.pos.x), - bits(self.pos.y), - bits(self.pos.z), - bits(self.fall), + f64_bits(self.pos.x), + f64_bits(self.pos.y), + f64_bits(self.pos.z), + f64_bits(self.fall), self.grace, self.impact ) @@ -128,9 +122,9 @@ impl TeleportConsumeWorld for World<'_, R> { self.attempts += 1; self.event(format!( "teleport {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) ))?; let at = n(self.config(), "success_at"); let success = at >= 0 && i >= at; @@ -142,9 +136,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_event(&mut self, l: i32, p: Vec3) -> Result<(), Self::Error> { self.event(format!( "game-event {l} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn is_fox(&self) -> bool { @@ -153,9 +147,9 @@ impl TeleportConsumeWorld for World<'_, R> { fn teleport_sound(&mut self, l: i32, p: Vec3, fox: bool) -> Result<(), Self::Error> { self.event(format!( "sound {l} {fox} {} {} {}", - bits(p.x), - bits(p.y), - bits(p.z) + f64_bits(p.x), + f64_bits(p.y), + f64_bits(p.z) )) } fn block_position(&mut self) -> Result { @@ -220,8 +214,8 @@ fn run(f: Value, out: &mut dyn Write, make: fn(i64) -> R) { writeln!(w.out, "random {i} {} {}", r.next_long(), r.next_long()).unwrap(); } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/terrain_fixture.rs b/crates/horizon-world/examples/probe/terrain_fixture.rs similarity index 94% rename from crates/horizon-world/examples/terrain_fixture.rs rename to crates/horizon-world/examples/probe/terrain_fixture.rs index 09868a340..506273a10 100644 --- a/crates/horizon-world/examples/terrain_fixture.rs +++ b/crates/horizon-world/examples/probe/terrain_fixture.rs @@ -1,4 +1,5 @@ //! Test transport for registry-backed noise-stage filling against vanilla doFill. +use crate::support::common::tag; use horizon_core::{ density::{ Beardifier, JigsawJunction, RigidPiece, SamplerContext, StructureBounds, TerrainAdjustment, @@ -67,17 +68,6 @@ impl TerrainBlockStates for Properties<'_> { fn n(v: &Value) -> i32 { v.as_i64().unwrap() as i32 } -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(i) => Tag::Int(i.as_i64().unwrap() as i32), - Value::Object(m) => { - Tag::Compound(m.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - _ => panic!("unsupported registry fixture value"), - } -} fn structure(v: &Value) -> Beardifier { let bounds = |v: &Value| { StructureBounds::new( @@ -239,8 +229,8 @@ fn fixture( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts-server.json"))?)?; let bundle: Value = serde_json::from_str(&fs::read_to_string(dir.join("registries.json"))?)?; diff --git a/crates/horizon-world/examples/tick_fixture.rs b/crates/horizon-world/examples/probe/tick_fixture.rs similarity index 93% rename from crates/horizon-world/examples/tick_fixture.rs rename to crates/horizon-world/examples/probe/tick_fixture.rs index 7b5bfa8ed..9e31fa5b6 100644 --- a/crates/horizon-world/examples/tick_fixture.rs +++ b/crates/horizon-world/examples/probe/tick_fixture.rs @@ -11,12 +11,8 @@ use horizon_world::{ tick_data::TickKind, }; use std::{collections::BTreeMap, error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let bytes = fs::read(base.join("ticks-input.nbt"))?; let (root, used) = nbt::read_named(&bytes, Limits::default())?; assert_eq!(used, bytes.len()); diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/probe/tree_feature_fixture.rs similarity index 99% rename from crates/horizon-world/examples/tree_feature_fixture.rs rename to crates/horizon-world/examples/probe/tree_feature_fixture.rs index 0de4fd562..3222254bd 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/probe/tree_feature_fixture.rs @@ -486,8 +486,8 @@ fn survival_rule(rule: &str) -> SurvivalRule { _ => panic!("unknown rule {rule}"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let read = |name: &str| -> Result> { Ok( diff --git a/crates/horizon-world/examples/use_flag_reaction_fixture.rs b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_flag_reaction_fixture.rs rename to crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs index 038b529fc..6c7c7fb97 100644 --- a/crates/horizon-world/examples/use_flag_reaction_fixture.rs +++ b/crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs @@ -243,8 +243,8 @@ impl DurationServices for Services { Ok(self.config()["durations"][kind].as_i64().unwrap() as i32) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/use_remainder_fixture.rs b/crates/horizon-world/examples/probe/use_remainder_fixture.rs similarity index 99% rename from crates/horizon-world/examples/use_remainder_fixture.rs rename to crates/horizon-world/examples/probe/use_remainder_fixture.rs index b572b3ce9..534abb167 100644 --- a/crates/horizon-world/examples/use_remainder_fixture.rs +++ b/crates/horizon-world/examples/probe/use_remainder_fixture.rs @@ -115,8 +115,8 @@ fn all( } Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/value_provider_fixture.rs b/crates/horizon-world/examples/probe/value_provider_fixture.rs similarity index 94% rename from crates/horizon-world/examples/value_provider_fixture.rs rename to crates/horizon-world/examples/probe/value_provider_fixture.rs index be7bf8afe..9cb895e1c 100644 --- a/crates/horizon-world/examples/value_provider_fixture.rs +++ b/crates/horizon-world/examples/probe/value_provider_fixture.rs @@ -51,8 +51,8 @@ fn fixture( writeln!(out, "tail {}", random.next_long())?; Ok(()) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/view_direction_fixture.rs b/crates/horizon-world/examples/probe/view_direction_fixture.rs similarity index 75% rename from crates/horizon-world/examples/view_direction_fixture.rs rename to crates/horizon-world/examples/probe/view_direction_fixture.rs index 6fa6ccd55..0c5f483df 100644 --- a/crates/horizon-world/examples/view_direction_fixture.rs +++ b/crates/horizon-world/examples/probe/view_direction_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::geometry::Vec3; use horizon_world::view_direction; use serde_json::Value; @@ -15,15 +16,8 @@ fn number(v: &Value) -> f64 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).unwrap(); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).unwrap(); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -32,22 +26,22 @@ fn main() -> Result<(), Box> { "acos" => writeln!( out, "angle {:016x}", - bits(view_direction::acos(number(&f["value"]))) + f64_bits(view_direction::acos(number(&f["value"]))) )?, "view" => { let v = view_direction::view_vector(single(&f["pitch"]), single(&f["yaw"])); writeln!( out, "view {:016x} {:016x} {:016x}", - bits(v.x), - bits(v.y), - bits(v.z) + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) )?; } "blocking" => writeln!( out, "angle {:016x}", - bits(view_direction::blocking_angle( + f64_bits(view_direction::blocking_angle( vec(&f["source"]), vec(&f["position"]), single(&f["yaw"]) @@ -56,7 +50,7 @@ fn main() -> Result<(), Box> { "fallback" => writeln!( out, "angle {:016x}", - bits(view_direction::BLOCKING_FALLBACK_ANGLE) + f64_bits(view_direction::BLOCKING_FALLBACK_ANGLE) )?, _ => panic!("mode"), } diff --git a/crates/horizon-world/examples/water_splash_fixture.rs b/crates/horizon-world/examples/probe/water_splash_fixture.rs similarity index 94% rename from crates/horizon-world/examples/water_splash_fixture.rs rename to crates/horizon-world/examples/probe/water_splash_fixture.rs index dd8c71080..8d6eabc79 100644 --- a/crates/horizon-world/examples/water_splash_fixture.rs +++ b/crates/horizon-world/examples/probe/water_splash_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource, XoroshiroRandom}, @@ -18,13 +19,6 @@ fn single(v: &Value) -> f32 { fn vec(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } -} fn float_bits(v: f32) -> u32 { if v.is_nan() { f32::NAN.to_bits() @@ -33,7 +27,12 @@ fn float_bits(v: f32) -> u32 { } } fn vector(v: Vec3) -> String { - format!("{:016x} {:016x} {:016x}", bits(v.x), bits(v.y), bits(v.z)) + format!( + "{:016x} {:016x} {:016x}", + f64_bits(v.x), + f64_bits(v.y), + f64_bits(v.z) + ) } struct World<'a, R> { f: &'a Value, @@ -154,8 +153,8 @@ fn run(f: &Value, out: &mut dyn Write, rng: R) -> io::Result<() writeln!(w.out, "next {}", w.rng.next_long())?; writeln!(w.out, "queries {}", w.calls) } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); let input = fs::read_to_string(dir.join("inputs.txt"))?; diff --git a/crates/horizon-world/examples/world_border_fixture.rs b/crates/horizon-world/examples/probe/world_border_fixture.rs similarity index 64% rename from crates/horizon-world/examples/world_border_fixture.rs rename to crates/horizon-world/examples/probe/world_border_fixture.rs index 60cabdd3d..ab0b8795b 100644 --- a/crates/horizon-world/examples/world_border_fixture.rs +++ b/crates/horizon-world/examples/probe/world_border_fixture.rs @@ -1,5 +1,6 @@ +use crate::support::shapes::{emit, values}; use horizon_core::geometry::{ - Aabb, Axis, Vec3, VoxelShape, + Aabb, Vec3, border::{BorderGeometry, BorderStatus}, }; use serde_json::Value; @@ -11,72 +12,8 @@ use std::{ fn number(v: &Value) -> f64 { f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) } -fn values( - out: &mut impl Write, - label: &str, - values: impl IntoIterator, -) -> io::Result<()> { - write!(out, "{label}")?; - for v in values { - let bits = if v.is_nan() { - 0x7ff8_0000_0000_0000 - } else { - v.to_bits() - }; - write!(out, " {bits:016x}")?; - } - writeln!(out) -} -fn box_values(out: &mut impl Write, label: &str, b: Aabb) -> io::Result<()> { - values( - out, - label, - [ - b.min(Axis::X), - b.min(Axis::Y), - b.min(Axis::Z), - b.max(Axis::X), - b.max(Axis::Y), - b.max(Axis::Z), - ], - ) -} -fn emit(out: &mut impl Write, shape: &VoxelShape) -> io::Result<()> { - writeln!( - out, - "shape {} {} {}", - shape.is_empty(), - shape.boxes().len(), - shape.is_cube() - )?; - for (axis, name) in Axis::ALL.into_iter().zip(["x", "y", "z"]) { - values(out, name, shape.coordinates(axis).iter().copied())?; - } - let axes = shape.cube_coordinate_axes(); - writeln!( - out, - "axes {}", - u8::from(axes[0]) + 2 * u8::from(axes[1]) + 4 * u8::from(axes[2]) - )?; - values( - out, - "extrema", - Axis::ALL - .map(|a| shape.min(a)) - .into_iter() - .chain(Axis::ALL.map(|a| shape.max(a))), - )?; - match shape.bounds() { - Some(b) => box_values(out, "bounds", b)?, - None => writeln!(out, "bounds none")?, - } - for b in shape.boxes() { - box_values(out, "box", *b)?; - } - Ok(()) -} -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/world_fixture.rs b/crates/horizon-world/examples/probe/world_fixture.rs similarity index 96% rename from crates/horizon-world/examples/world_fixture.rs rename to crates/horizon-world/examples/probe/world_fixture.rs index d972643cc..fd89e767b 100644 --- a/crates/horizon-world/examples/world_fixture.rs +++ b/crates/horizon-world/examples/probe/world_fixture.rs @@ -6,12 +6,8 @@ use horizon_world::{ }; use std::{error::Error, fs, path::PathBuf}; -fn main() -> Result<(), Box> { - let base = PathBuf::from( - std::env::args() - .nth(1) - .ok_or("expected fixture directory")?, - ); +pub fn main() -> Result<(), Box> { + let base = PathBuf::from(crate::args().nth(1).ok_or("expected fixture directory")?); let output = base.join("rust/palettes"); fs::create_dir_all(&output)?; for entry in fs::read_dir(base.join("palettes"))? { diff --git a/crates/horizon-world/examples/world_ray_fixture.rs b/crates/horizon-world/examples/probe/world_ray_fixture.rs similarity index 94% rename from crates/horizon-world/examples/world_ray_fixture.rs rename to crates/horizon-world/examples/probe/world_ray_fixture.rs index b418785b0..ded8645c7 100644 --- a/crates/horizon-world/examples/world_ray_fixture.rs +++ b/crates/horizon-world/examples/probe/world_ray_fixture.rs @@ -1,3 +1,4 @@ +use crate::support::common::f64_bits; use horizon_core::{ geometry::{Aabb, ShapeOp, Vec3, VoxelShape}, position::BlockPos, @@ -15,13 +16,6 @@ fn number(v: &Value) -> f64 { fn vector(v: &Value) -> Vec3 { Vec3::new(number(&v[0]), number(&v[1]), number(&v[2])) } -fn bits(v: f64) -> u64 { - if v.is_nan() { - 0x7ff8000000000000 - } else { - v.to_bits() - } -} fn pos(p: BlockPos) -> String { format!("{} {} {}", p.x, p.y, p.z) } @@ -137,8 +131,8 @@ impl RayWorld for World<'_> { Ok(self.shapes[s][4].clone()) } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { @@ -185,9 +179,9 @@ fn main() -> Result<(), Box> { w.out, "hit {} {:016x} {:016x} {:016x} {} {} {}", r.miss, - bits(h.location.x), - bits(h.location.y), - bits(h.location.z), + f64_bits(h.location.x), + f64_bits(h.location.y), + f64_bits(h.location.z), format!("{:?}", h.direction).to_lowercase(), pos(h.block), h.inside diff --git a/crates/horizon-world/examples/worldgen_random_fixture.rs b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs similarity index 97% rename from crates/horizon-world/examples/worldgen_random_fixture.rs rename to crates/horizon-world/examples/probe/worldgen_random_fixture.rs index 1cf37b1f9..1db24cf8a 100644 --- a/crates/horizon-world/examples/worldgen_random_fixture.rs +++ b/crates/horizon-world/examples/probe/worldgen_random_fixture.rs @@ -118,8 +118,8 @@ fn layers(f: &Value, mut source: impl WorldgenSource, out: &mut impl Write) -> i _ => panic!("unsupported layer count"), } } -fn main() -> Result<(), Box> { - let arg = std::env::args().nth(1).expect("private fixture directory"); +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); for line in fs::read_to_string(dir.join("inputs.txt"))?.lines() { diff --git a/crates/horizon-world/examples/vanilla_diff.rs b/crates/horizon-world/examples/vanilla_diff.rs deleted file mode 100644 index 52eb77737..000000000 --- a/crates/horizon-world/examples/vanilla_diff.rs +++ /dev/null @@ -1,441 +0,0 @@ -//! Differential check of decorated chunks against a vanilla world. -//! -//! vanilla_diff --seed S -//! [--dimension minecraft:overworld] [--from CX CZ] [--size N] -//! [--threads T] [--show FROM->TO] [--limit N] [--reverse] [--shuffle SEED] -//! [--other ] -//! -//! Generates an (N+4)² chunk area with the Rust pipeline, decorates the inner -//! (N+2)² chunks (vanilla FEATURES writes reach one neighbor) and compares the -//! N² chunks starting at (CX, CZ) block by block with the region files of a -//! vanilla world generated for the same seed (with ticks frozen, see -//! docs/parity/worldgen.md). Prints mismatches grouped by vanilla → Rust block. -use horizon_core::position::{BlockPos, ChunkPos}; -use horizon_world::{ - DATA_VERSION, - chunk::{BlockSection, BlockState, ChunkData}, - nbt::{Limits, Tag}, - region::RegionFile, - registry::BlockRegistry, - worldgen::generator::{GeneratorData, OverworldGenerator, ProtoChunk}, -}; -use serde_json::Value; -use std::{ - collections::{BTreeMap, HashMap}, - fs, - path::{Path, PathBuf}, - sync::{ - Mutex, - atomic::{AtomicUsize, Ordering}, - }, -}; - -type Error = Box; - -fn tag(v: &Value) -> Tag { - match v { - Value::String(s) => Tag::String(s.as_str().into()), - Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), - Value::Array(a) => Tag::List(a.iter().map(tag).collect()), - Value::Object(o) => { - Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) - } - _ => panic!("invalid registry metadata"), - } -} - -fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { - let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; - let registry = BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - facts["states"] - .as_array() - .unwrap() - .iter() - .map(|v| tag(&v[4])) - .collect(), - ), - ), - ("defaults", tag(&facts["defaults"])), - ]))?; - Ok(Box::leak(Box::new(registry))) -} - -fn describe(state: &BlockState) -> String { - if state.properties.is_empty() { - return state.name.clone(); - } - let props: Vec = state - .properties - .iter() - .map(|(k, v)| format!("{k}={v}")) - .collect(); - format!("{}[{}]", state.name, props.join(",")) -} - -fn region_dir(world: &Path, dimension: &str) -> PathBuf { - let modern = world - .join("dimensions") - .join(dimension.replace(':', "/")) - .join("region"); - if modern.is_dir() { - return modern; - } - match dimension { - "minecraft:the_nether" => world.join("DIM-1/region"), - "minecraft:the_end" => world.join("DIM1/region"), - _ => world.join("region"), - } -} - -/// Terrain-stage chunks of the `full`² area at `origin`, row-major. -fn generate_area( - generator: &OverworldGenerator, - origin: (i32, i32), - full: i32, - threads: usize, -) -> Result, Error> { - let count = (full * full) as usize; - let next = AtomicUsize::new(0); - let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); - std::thread::scope(|scope| -> Result<(), Error> { - let handles = (0..threads) - .map(|_| { - scope.spawn(|| -> Result<(), Error> { - let mut worker = generator.worker(); - loop { - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= count { - return Ok(()); - } - let pos = ChunkPos::new( - origin.0 + (i as i32 % full), - origin.1 + (i as i32 / full), - ); - *slots[i].lock().unwrap() = Some(worker.generate_proto(pos)?); - } - }) - }) - .collect::>(); - handles.into_iter().try_for_each(|h| h.join().unwrap()) - })?; - Ok(slots - .into_iter() - .map(|s| s.into_inner().unwrap().unwrap()) - .collect()) -} - -/// Decorates the chunks at `order` (indices into the `full`² area, each with -/// all eight neighbors present) in that order, one FEATURES pass each. -fn decorate_area( - generator: &OverworldGenerator, - protos: Vec, - full: i32, - order: &[(i32, i32)], -) -> Result, Error> { - let mut chunks: Vec> = protos.into_iter().map(Some).collect(); - let mut worker = generator.worker(); - let (mut unsupported_roots, mut failed) = (0, 0); - let mut skipped = std::collections::BTreeSet::new(); - for &(x, z) in order { - let mut region = Vec::with_capacity(9); - for dz in -1..=1 { - for dx in -1..=1 { - region.push(chunks[((z + dz) * full + x + dx) as usize].take().unwrap()); - } - } - let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region")?; - let stats = worker.decorate(&mut region)?; - unsupported_roots += stats.unsupported; - failed += stats.failed; - skipped.extend(stats.skipped); - for (i, chunk) in region.into_iter().enumerate() { - let (dx, dz) = (i as i32 % 3 - 1, i as i32 / 3 - 1); - chunks[((z + dz) * full + x + dx) as usize] = Some(chunk); - } - } - println!("decoration: unsupported roots {unsupported_roots}, failed {failed}"); - if !skipped.is_empty() { - println!( - "skipped: {}", - skipped.into_iter().collect::>().join(" ") - ); - } - Ok(chunks.into_iter().map(Option::unwrap).collect()) -} - -/// Lazily opened region files of one dimension. -struct Regions { - dir: PathBuf, - files: HashMap<(i32, i32), Option>, -} -impl Regions { - fn new(dir: PathBuf) -> Self { - Self { - dir, - files: HashMap::new(), - } - } - fn chunk(&mut self, pos: ChunkPos) -> Result, Error> { - let key = (pos.x >> 5, pos.z >> 5); - let dir = &self.dir; - let file = self.files.entry(key).or_insert_with(|| { - RegionFile::open(dir.join(format!("r.{}.{}.mca", key.0, key.1))).ok() - }); - let Some(file) = file else { return Ok(None) }; - let Some(record) = file.read(pos)? else { - return Ok(None); - }; - Ok(Some(ChunkData::new(record.nbt(Limits::default())?)?)) - } -} - -fn main() -> Result<(), Error> { - let mut args = std::env::args().skip(1); - let resources = PathBuf::from(args.next().expect("client resource directory")); - let world = PathBuf::from(args.next().expect("vanilla world directory")); - let (mut seed, mut from, mut size, mut threads) = (0i64, (0, 0), 8i32, 4usize); - let mut dimension = String::from("minecraft:overworld"); - let mut show: Option = None; - let mut limit = 40usize; - let mut other: Option = None; - let (mut reverse, mut shuffle) = (false, 0i64); - while let Some(arg) = args.next() { - let mut next = || args.next().expect("argument value"); - match arg.as_str() { - "--seed" => seed = next().parse()?, - "--from" => from = (next().parse()?, next().parse()?), - "--size" => size = next().parse()?, - "--threads" => threads = next().parse()?, - "--dimension" => dimension = next(), - "--show" => show = Some(next()), - "--limit" => limit = next().parse()?, - "--other" => other = Some(PathBuf::from(next())), - "--reverse" => reverse = true, - "--shuffle" => shuffle = next().parse()?, - _ => return Err(format!("unknown argument {arg}").into()), - } - } - let registry = registry(&resources)?; - let data = GeneratorData::load(&resources.join("worldgen"), registry)?; - let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?; - let unsupported = generator.unsupported_features(); - println!("unsupported placed features: {}", unsupported.len()); - - // Rust: terrain for (size+4)², decoration for the inner (size+2)². - let full = size + 4; - let (x0, z0) = (from.0 - 2, from.1 - 2); - let mut order: Vec<(i32, i32)> = (1..full - 1) - .flat_map(|z| (1..full - 1).map(move |x| (x, z))) - .collect(); - if reverse { - let mut reversed = order.clone(); - reversed.reverse(); - let alternate = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &reversed, - )?; - let chunks = decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?; - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut total = 0; - let name = |id| { - registry - .state(id) - .map(|s: &BlockState| s.name.trim_start_matches("minecraft:").to_owned()) - .unwrap_or_default() - }; - for (a, b) in chunks.iter().zip(&alternate) { - let p = a.position(); - if p.x < from.0 || p.z < from.1 || p.x >= from.0 + size || p.z >= from.1 + size { - continue; - } - for section in 0..a.terrain.height() as usize / 16 { - let (sa, sb) = ( - a.terrain.section(section).unwrap(), - b.terrain.section(section).unwrap(), - ); - for index in 0..4096 { - let (x, y) = (sa.get(index)?, sb.get(index)?); - if x != y { - total += 1; - *pairs.entry((name(x), name(y))).or_default() += 1; - } - } - } - } - println!("decoration order sensitivity (raster vs reverse): {total} blocks differ"); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} {v} <-> {r}"); - } - return Ok(()); - } - if shuffle != 0 { - // Deterministic Fisher-Yates with a 64-bit LCG. - let mut state = shuffle as u64; - for i in (1..order.len()).rev() { - state = state - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - order.swap(i, (state >> 33) as usize % (i + 1)); - } - } - let chunks = match other { - Some(_) => Vec::new(), - None => decorate_area( - &generator, - generate_area(&generator, (x0, z0), full, threads)?, - full, - &order, - )?, - }; - let (min_y, height) = match dimension.as_str() { - "minecraft:overworld" => (-64, 384), - _ => (0, 256), - }; - - // Vanilla region files. - let mut vanilla = Regions::new(region_dir(&world, &dimension)); - let mut second = other.map(|w| Regions::new(region_dir(&w, &dimension))); - let air = registry.default_state("minecraft:air").unwrap(); - let mut pairs: BTreeMap<(String, String), usize> = BTreeMap::new(); - let mut examples: Vec<[i32; 3]> = Vec::new(); - let (mut compared, mut differ, mut missing) = (0usize, 0usize, 0usize); - let mut per_chunk = Vec::new(); - for cz in from.1..from.1 + size { - for cx in from.0..from.0 + size { - let pos = ChunkPos::new(cx, cz); - let Some(theirs) = vanilla.chunk(pos)? else { - missing += 1; - continue; - }; - let ours = match &mut second { - Some(second) => match second.chunk(pos)? { - Some(chunk) => Some(chunk), - None => { - missing += 1; - continue; - } - }, - None => None, - }; - let status = match theirs.root().tag.get("Status") { - Some(Tag::String(s)) => s.to_string().unwrap_or_default(), - _ => String::new(), - }; - let rust = chunks.get(((cz - z0) * full + cx - x0) as usize); - if size == 1 { - println!( - "vanilla structures: {:?}", - theirs.root().tag.get("structures") - ); - if let Some(rust) = rust { - println!("rust structures: {:?}", rust.structures()); - } - } - if status != "minecraft:full" { - println!("chunk {cx} {cz}: vanilla status {status}"); - } - let mut chunk_differ = 0; - for section in 0..height as usize / 16 { - let base_y = min_y + section as i32 * 16; - let at = BlockPos::new(cx * 16, base_y, cz * 16); - let ours_loaded; - let ours: Option<&BlockSection> = match (&ours, rust) { - (Some(chunk), _) => { - ours_loaded = chunk.load_block_section(at, registry)?; - ours_loaded.as_ref() - } - (None, Some(rust)) => rust.terrain.section(section), - (None, None) => None, - }; - let theirs = theirs.load_block_section(at, registry)?; - for index in 0..4096 { - let a = ours.map_or(Ok(air), |s| s.get(index))?; - let b = theirs.as_ref().map_or(Ok(air), |s| s.get(index))?; - compared += 1; - if a == b { - continue; - } - differ += 1; - chunk_differ += 1; - let (va, ru) = ( - registry.state(b).map(describe).unwrap_or_default(), - registry.state(a).map(describe).unwrap_or_default(), - ); - let short = |s: &str| { - s.split('[') - .next() - .unwrap() - .trim_start_matches("minecraft:") - .to_owned() - }; - let pair = (short(&va), short(&ru)); - let p = [ - cx * 16 + (index & 15) as i32, - base_y + (index >> 8) as i32, - cz * 16 + ((index >> 4) & 15) as i32, - ]; - if let Some(filter) = &show { - let label = format!("{}->{}", pair.0, pair.1); - if &label == filter && examples.len() < limit { - examples.push(p); - println!(" {p:?}: vanilla {va} rust {ru}"); - } - } - *pairs.entry(pair).or_default() += 1; - } - } - per_chunk.push(((cx, cz), chunk_differ)); - } - } - println!( - "compared {compared} blocks in {} chunks ({missing} missing): {differ} differ ({:.4}%)", - per_chunk.len(), - differ as f64 * 100.0 / compared.max(1) as f64 - ); - let mut sorted: Vec<_> = pairs.into_iter().collect(); - sorted.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((v, r), n) in sorted.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - // Decoration order at chunk borders differs between runs (vanilla's own - // runs disagree), which mostly swaps blocks symmetrically. One-sided - // differences point at real generation differences. - let counts: BTreeMap<_, _> = sorted.iter().cloned().collect(); - let mut net: Vec<(i64, &(String, String))> = counts - .iter() - .map(|(pair, &n)| { - let back = counts - .get(&(pair.1.clone(), pair.0.clone())) - .copied() - .unwrap_or(0); - (n as i64 - back as i64, pair) - }) - .filter(|(n, _)| *n > 0) - .collect(); - net.sort_by_key(|p| std::cmp::Reverse(p.0)); - println!("one-sided differences:"); - for (n, (v, r)) in net.iter().take(limit) { - println!("{n:>9} vanilla {v} -> rust {r}"); - } - let clean = per_chunk.iter().filter(|(_, n)| *n == 0).count(); - println!("chunks identical: {clean}/{}", per_chunk.len()); - let mut worst = per_chunk.clone(); - worst.sort_by_key(|p| std::cmp::Reverse(p.1)); - for ((x, z), n) in worst.iter().take(8).filter(|(_, n)| *n > 0) { - println!(" chunk {x} {z}: {n}"); - } - Ok(()) -} diff --git a/docs/mods.md b/docs/mods.md index 4b356d336..4521d312d 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -137,10 +137,17 @@ proposal, no profiling. Its cranelift backend generates native code for x86-64 and ARM64 on Windows, macOS and Linux, which is why one `.hmod` serves them all. +The game links it only with its `mods` feature: every release build turns it +on (`release.yml`), and a build from source needs +`cargo build --release -p horizon-client --features mods` to run code mods. +Without it (the tests and probes) wasmtime and cranelift aren't built, a +quarter of a clean build; content mods still load, and the game logs why the +code mods don't start. + ### Performance Measured on the Mac mini (M4 Pro), release build, `cargo test -p -horizon-mods --release --test sandbox -- --ignored --nocapture`: +horizon-mods --features runtime,pack --release --test sandbox -- --ignored --nocapture`: | | per call | |---|---| @@ -180,7 +187,8 @@ chat (`Mod Test Guest stopped: it took too long (an endless loop?)`), marks it on the Mods page and carries on; the other mods keep running. Host functions clip what a mod hands back (chat lines per call, HUD lines and lengths). Tests: `crates/horizon-mods/tests/sandbox.rs` (an endless loop, a panic and a 1 GiB -allocation, next to a healthy mod). +allocation, next to a healthy mod; `cargo test -p horizon-mods --features +runtime,pack`). ## Playing with mods diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index dde4b5d41..a2cd10584 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -26,6 +26,8 @@ Vanilla oracle runs are reused as well. `tools/parity_shim.py` stands in for `ja Probes build into `.local/parity-target/` with release optimisation but no LTO and 16 codegen units. On ludodesktop that rebuilds every `horizon-world` probe in 3 seconds after a one-line change, against 122 seconds with the release profile. Rust gives these settings identical results (no fast-math; overflow checks as in release), and the full harness suite passes under them. Probes that harnesses build in the dev profile get `opt-level = 3` too, keeping their overflow checks and debug assertions. Harnesses must locate binaries through `cargo metadata` or `lab.cargo_target()`, never a hard-coded `target/`. +The probes of `horizon-world` and of `horizon-client` are one binary per crate, `cargo build --release -p --example probe`: a harness runs `probe [arguments]`, and `` is a module in `crates//examples/probe/` (add it to the `mod` list and the `probes!` list in its `main.rs`; read arguments with `crate::args()` or `crate::args_os()`, which drop the name). Code several probes share goes in `examples/probe/support/` or a module of its own. Linking one binary instead of ~250 examples is most of what a probe build used to cost. The runner counts only the probes a harness ran, the probes and support modules they name, their own subdirectories and `dispatch.rs` as its dependencies, not `main.rs`, which only lists the probes: editing one probe reruns only its harnesses, and adding one reruns none. + Passes are shared between worktrees. A harness's key depends only on the content of its dependencies, not on where they are, so every pass is also written to `parity-shared/` beside the shared vanilla data (`PARITY_SHARED` overrides it). A worktree whose files match those a harness passed with, in any worktree, counts that pass without running the harness: after merging the integration branch, an agent's gate only runs the harnesses its own changes affect. Every runner on the machine shares `PARITY_MACHINE_JOBS` slots (default: half the CPU threads), so several agents' runs together can't overload it. Parallel harnesses are also admitted by memory: each harness's recorded peak is reserved, within three quarters of the memory available at the start, and a harness starts only if the memory free at that moment still leaves 2 GB. `-j` caps the count here (default: `PARITY_LOCAL_JOBS`, else 3 while other machines help or a third of the CPU threads alone, within `$FLEET_LOAD_JOBS`). diff --git a/docs/parity/meshing.md b/docs/parity/meshing.md index 5b746e76c..bcd1cbc6a 100644 --- a/docs/parity/meshing.md +++ b/docs/parity/meshing.md @@ -20,7 +20,7 @@ emit for the same scenes. `FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through `ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on, cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`. -- **Horizon side**: `crates/horizon-client/examples/section_mesh_fixture.rs` +- **Horizon side**: `crates/horizon-client/examples/probe/section_mesh_fixture.rs` loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`, `load_visibility`, `MeshTables`), builds the same blocks and light in real client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the diff --git a/docs/rust-parity.md b/docs/rust-parity.md index fee801463..98bff8f82 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1471,7 +1471,7 @@ the `hp` text when they no longer fit; and the header and footer wrapped by the list in single player unless a `list` objective is set. `tools/test_tab_list_parity.py` runs vanilla's own `extractRenderState` frame after frame (`VanillaTabListOracle`: stand-in connection, level and options, -real `Scoreboard`) against `examples/tab_list_fixture` and compares every fill, +real `Scoreboard`) against `examples/probe/tab_list_fixture.rs` and compares every fill, styled text run, sprite and face blit (as `hud_layout::GuiDraw` calls, painted like the rest of the HUD): **1,000 cases, 3,476 frames and 844,758 calls match**. The game draws the same layout while the player-list key is @@ -1492,7 +1492,7 @@ nearest first. `WorldBorder::warning_strength` feeds `hud_overlays::vignette` the border's warning strength at the camera. `tools/test_world_border_render_parity.py` drives vanilla's border, renderer and vignette (`VanillaWorldBorderRenderOracle`, with a stand-in GPU device, dynamic-uniform writer and render pass) against -`examples/world_border_render_fixture`: **1,500 cases and 16,859 frames match +`examples/probe/world_border_render_fixture.rs`: **1,500 cases and 16,859 frames match bit for bit** (8,513 with the wall drawn). The game draws the wall with `RenderPipelines.WORLD_BORDER`'s overlay blend and the mipmapped forcefield texture, and follows the server's border packets. One border is kept for all diff --git a/docs/shader-packs.md b/docs/shader-packs.md index d30122544..0b1214557 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -24,7 +24,8 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips, `blend.*`) | done: planned for the three test packs | | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below); `depthtex1`/`depthtex2` before translucent geometry, `blend.*`, PNG `texture..*` and `texture.noise` | | Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light, `wetness` | done for the full-screen passes (below) | -| Java shader packs: `gbuffers_*`, `shadow`, `.dat` and resource-location textures, images, compute | planned | +| Java shader packs: `gbuffers_terrain`, `gbuffers_water` (`gfx/java_terrain.rs`: Horizon's terrain fed to the pack's programs) | first slice: MakeUp Ultra Fast, Chocapic13' and BSL draw their own terrain and water (below) | +| Java shader packs: other `gbuffers_*`, `shadow`, `.dat` and resource-location textures, images, compute | planned | ## How the renderer draws a frame today @@ -396,6 +397,25 @@ Picking one translates every planned pass of each dimension folder (`java_pack.r 4. `final` draws into a target that replaces the world's picture, where Horizon packs' `composite` output goes: the hand, menus and HUD are drawn over it. +When the pack has a `gbuffers_terrain` (or `textured_lit`, `textured`, `basic`, the program Iris falls back to), the +pack draws the terrain itself (`gfx/java_terrain.rs`): Horizon's world pass skips its own solid and translucent +terrain, then + +- at step 2, after Horizon's sky, entities and the rest enter `colortex0` and depth, the pack's terrain program draws + every visible section into its `RENDERTARGETS` (the side the next pass reads), tested against that depth; the + depth is then copied into `depthtex0` and `depthtex1`; +- before the first `composite`, as Iris does, `gbuffers_water` (or the terrain program) draws the translucent + layer with the pack's `blend.*` or vanilla's blending; the depth goes into `depthtex0` only. + +The pack's vertex program reads Horizon's own terrain vertices (the arena pages, instanced or flat draws): a glue +function written before `main` decodes them into Iris's attributes (`vaPosition`/`gl_Vertex` relative to the camera, +`gl_Color` with vanilla's face shading undone, `gl_MultiTexCoord0/1`, the normal and `at_tangent` from the quad's +four corners, `mc_midTexCoord`, `at_midBlock`), and `mc_Entity.x` is the block's id from the pack's +`block.properties`, matched to the sprite's block by name. `gtexture`/`texture` is a 2D atlas built from Horizon's +sprite arrays (animated sprites copied in each frame), `lightmap` is Horizon's lightmap with Iris's texture matrix, +and fragments under alpha 0.1 are discarded (`alphaTestRef`). `RGBA16` targets are 16-bit unorm where the GPU can +render them (Chocapic13' packs its G-buffer into them; half floats broke it). + What makes Horizon look like OpenGL to the pack: - **Layout.** The translator ends every vertex shader by flipping `gl_Position.y` and moving depth from `[-w, w]` to @@ -426,12 +446,15 @@ What makes Horizon look like OpenGL to the pack: Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its -`deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its -shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Horizon's world goes into the target -the pack's `gbuffers_terrain` (or the program Iris falls back to) draws to first: `colortex0` for most packs, -`colortex1` for MakeUp. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), -mipmapped targets (`colortexNMipmapEnabled` is read but ignored), `.dat` and resource-location custom textures (PNG -files in the pack only); shadow matrices are identity. +`deferred` reads the albedo `gbuffers_*` write to `colortex4` (not checked again since the terrain programs run). +Without the other `gbuffers_*` and `shadow`, no pack has its shadows or sky look yet; Distant Horizons' and Voxy's +depth read as far. Horizon's world goes into the target the pack's `gbuffers_terrain` (or the program Iris falls back +to) draws to first: `colortex0` for most packs, `colortex1` for MakeUp. Not supported yet: images and compute (`.csh`; +a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), `.dat` and +resource-location custom textures (PNG files in the pack only); shadow matrices are identity. With the pack's terrain: +entities, the sky, the hand, weather and clouds are still Horizon's (in that first target only), GPU occlusion culling +is off, block ids come from sprite names rather than block states, distant (LOD) terrain doesn't repeat its textures, +and only the overworld has been checked. ### Compatibility @@ -439,19 +462,19 @@ Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default op the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked (`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game -and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet. -The MakeUp, Chocapic13' and Photon rows are from 2026-10-23, on Metal and on Vulkan (RTX 4080). +and screenshotted. Full-screen passes, `gbuffers_terrain` and `gbuffers_water` run (above); no pack has its own +shadows, entities or sky yet. | Pack | Version | Result | First thing that stops it | | --- | --- | --- | --- | -| BSL | v10.1.8 | drawn: 26 passes | | +| BSL | v10.1.8 | drawn: 26 passes and its terrain and water programs | | | Complementary Reimagined | r5.9.3 | drawn: 27 passes | | | Complementary Unbound | r5.8 | loads: 27 passes | | | Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | | | Steadfast | 0.8.0 | drawn: 3 passes | | -| MakeUp Ultra Fast | 9.6 | drawn: 6 passes, its fog, light shafts and grade over Horizon's world | | -| Chocapic13' | V9 High | drawn: 16 passes; its default TAA upscaling shrinks the world in its `gbuffers_*` vertex programs, which don't run, so the picture is magnified 1/0.7: turn TAA Upscaling off in its settings | | -| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | | +| Chocapic13' | V9 High | drawn: 16 passes and its terrain and water programs | | +| MakeUp Ultra Fast | 9.6 | drawn: 6 passes and its terrain and water programs | | +| Photon | v1.4 | loads: 27 passes and its terrain and water programs; draws black | its sky and light come from a compute pass and `.dat` look-up tables, not loaded yet | | Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) | | Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | | Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | @@ -492,9 +515,9 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer 3. **Full-screen programs**: `deferred*`, `composite*`, `final` with `colortex0..15` (formats from the pack), `depthtex0..2`, `noisetex` and the uniforms (most are already computed for the world shaders). This alone runs Sildur's and BSL post-processing over Horizon's own world. -4. **`gbuffers_terrain`, `gbuffers_water`, `gbuffers_sky*`**: Horizon's terrain vertices extended with Iris's - attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second set of - terrain pipelines writing the pack's render targets. +4. **`gbuffers_terrain`, `gbuffers_water`** (done, above), **`gbuffers_sky*`**: Horizon's terrain vertices decoded + into Iris's attributes (`mc_Entity` from `block.properties`, `mc_midTexCoord`, `at_tangent`, lightmap), a second + set of terrain pipelines writing the pack's render targets. 5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`. 6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the light's view, with the pack's distortion. diff --git a/docs/world-generation.md b/docs/world-generation.md index 42cc07cff..f55cbdcb2 100644 --- a/docs/world-generation.md +++ b/docs/world-generation.md @@ -195,7 +195,7 @@ above remains a record of its narrower tested source snapshot. `tools/test_chunk_generation_parity.py` generates chunks in actual vanilla classes (`VanillaChunkGenerationOracle`: structure starts and references, biomes, noise, surface, carvers, then biome decoration and structure pieces through real `WorldGenRegion`s) and with -`crates/horizon-world/examples/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target +`crates/horizon-world/examples/probe/chunk_dump.rs`, and compares every block state, quart biome and block entity (canonical NBT) of each target chunk, and the scheduled block and fluid ticks each proto chunk carries into the live world. Cases are terrain sites for several seeds across the overworld, Nether and End, plus rectangles around every structure kind found by scanning the seed. `--phase structures` isolates terrain plus structure pieces, `--phase terrain` stops before features. `HORIZON_ORDER` (a file of `x z` lines) makes both sides diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index 7653311ac..a851adcbd 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -419,6 +419,20 @@ mod tests { ); } + /// Whether the reference on disk says `want`, whatever line endings the checkout gave it: Git + /// for Windows checks text out with CRLF (core.autocrlf) where .gitattributes does not pin LF. + fn up_to_date(have: &str, want: &str) -> bool { + have.replace("\r\n", "\n") == want + } + + #[test] + fn a_windows_checkout_of_the_reference_is_up_to_date() { + let want = markdown(); + assert!(up_to_date(&want, &want)); + assert!(up_to_date(&want.replace('\n', "\r\n"), &want)); + assert!(!up_to_date(&want.replacen("## ", "### ", 1), &want)); + } + #[test] fn the_launcher_reference_is_up_to_date() { let path = @@ -429,7 +443,7 @@ mod tests { } let have = std::fs::read_to_string(&path).unwrap_or_default(); assert!( - have == want, + up_to_date(&have, &want), "docs/launcher-commands.md is out of date: HORIZON_WRITE_DOCS=1 cargo test --manifest-path launcher/Cargo.toml the_launcher_reference" ); for tool in all() { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 9b4e6e8f5..3c7de61ef 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -37,6 +37,9 @@ public final class VanillaMenuOracle { static final List drops = new ArrayList<>(); /** onEquipItem calls that change the item (its sound and game event): slot and new stack. */ static final List equips = new ArrayList<>(); + /** The sounds the player played ({@code Entity.playSound}: a bundle's insert and remove). */ + static final List sounds = new ArrayList<>(); + static final net.minecraft.util.RandomSource soundRandom = net.minecraft.util.RandomSource.create(0L); /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; /** The block entity behind a "lectern" menu. */ @@ -99,6 +102,8 @@ public final class VanillaMenuOracle { @Override public void scheduleTick(BlockPos pos, net.minecraft.world.level.block.Block block, int delay) { } @Override public void updateNeighborsAt(BlockPos pos, net.minecraft.world.level.block.Block block, net.minecraft.world.level.redstone.Orientation o) { } @Override public void playSound(net.minecraft.world.entity.Entity e, BlockPos pos, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { } + // A bundle sound's pitch: 0.8 + level.getRandom().nextFloat() * 0.4. + @Override public net.minecraft.util.RandomSource getRandom() { return soundRandom; } } /** The maps of the case's level, by id, and the next free id. */ @@ -127,6 +132,9 @@ public final class VanillaMenuOracle { if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now)); } @Override public boolean hasDisconnected() { return false; } + @Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { + sounds.add(sound.location().toString()); + } @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); return null; @@ -251,9 +259,9 @@ public final class VanillaMenuOracle { // No inventory slots: the inventory Take Book fills. StringBuilder items = new StringBuilder(); for (int i = 0; i < 36; i++) items.append(' ').append(ParityData.canon(inv.getItem(i))); - return state(menu, inv) + " | " + String.join(";", equips) + " | inv" + items; + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds) + " | inv" + items; } - return state(menu, inv) + " | " + String.join(";", equips); + return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds); } public static void main(String[] args) throws Exception { @@ -271,6 +279,7 @@ public final class VanillaMenuOracle { try { drops.clear(); equips.clear(); + sounds.clear(); var world = make(World.class); world.server = make(Server.class); var player = make(FakePlayer.class); @@ -325,6 +334,7 @@ public final class VanillaMenuOracle { for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); equips.clear(); + sounds.clear(); out.println("init " + clickState(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index d5e9c86fa..e37e898a3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -65,6 +65,7 @@ import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; import net.minecraft.network.protocol.game.ServerboundChatPacket; import net.minecraft.network.protocol.game.ServerboundChunkBatchReceivedPacket; +import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerLoadedPacket; import net.minecraft.network.protocol.handshake.ClientIntent; @@ -484,6 +485,8 @@ public final class VanillaProtocolClient { // When the dead player sent a command (ServerGamePacketListenerImpl.handleChatCommand runs it // whether the player is alive or not); it respawns once the reply came, or 3 s later. long deadCommandAt = 0; + // When the client last sent where it is. + long positionAt = 0; while (System.currentTimeMillis() < deadline) { Received r; try { @@ -536,6 +539,7 @@ public final class VanillaProtocolClient { // acceptance alone, as the 26.3 client sends. if (!respawning && step < ENTITIES) { send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); + positionAt = now; } if (!loaded) { send(new ServerboundPlayerLoadedPacket()); @@ -635,6 +639,17 @@ public final class VanillaProtocolClient { commandTree(p); } } + if (entities == null && loaded && deadCommandAt == 0 && now - positionAt >= 1000) { + // LocalPlayer.sendPosition: once its level is loaded the 26.3 client sends where it is + // every 20 ticks even standing still, and the server then checks again which entities the + // player sees (ChunkMap.move). An entity whose chunk was sent after the player's last move, + // such as the villager when the first chunks come late, is paired at the next one. The tick + // end first (Minecraft.tick sends one every tick): a server takes one position per client tick. + // Until the death: from then on the steps wait only on entities spawned for the player. + send(ServerboundClientTickEndPacket.INSTANCE); + send(new ServerboundMovePlayerPacket.Pos(position.position(), false, false)); + positionAt = now; + } if (entities != null && loaded && lastChunk > 0 && now - lastChunk > 3000 && step == 0) { // Entity mode: the harness's console summons the scene once it reads this // line; everything tracked from then on is recorded until the client leaves. diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index a9b7ff595..633163bf5 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -49,6 +49,24 @@ class ParityRunnerTests(unittest.TestCase): "--example", "old"], ]) + def test_a_probe_binary_depends_only_on_the_probes_it_ran(self): + commands = [["/t/release/examples/probe", "a_fixture", "/dir"], ["cargo", "run", "--example", "probe", "--", "b_fixture"]] + self.assertEqual(parity.probes_run(commands), {"a_fixture", "b_fixture"}) + with tempfile.TemporaryDirectory() as temp, mock.patch.object(parity, "ROOT", Path(temp)): + probe = Path(temp, "crates/w/examples/probe") + (probe / "support").mkdir(parents=True) + (probe / "a_fixture.rs").write_text('mod integration { include!("d_fixture.rs"); }') + (probe / "d_fixture.rs").write_text("use crate::support::shared as s;") + (probe / "b_fixture.rs").write_text("use crate::e_fixture;") + for name in ("c_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", "support/shared.rs", "support/other.rs"): + (probe / name).write_text("") + paths = [f"crates/w/examples/probe/{name}" for name in ("a_fixture.rs", "b_fixture.rs", "c_fixture.rs", + "d_fixture.rs", "dispatch.rs", "e_fixture.rs", "main.rs", + "support/other.rs", "support/shared.rs")] + self.assertEqual(parity.only_probes_run(["crates/w/src/lib.rs", *paths], {"a_fixture", "b_fixture"}), + ["crates/w/src/lib.rs", *paths[:2], *paths[3:6], paths[8]]) + self.assertEqual(parity.only_probes_run(paths, set()), paths) + def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: sources, classes = Path(temp, "src"), Path(temp, "classes") diff --git a/tests/test_pr_ready.py b/tests/test_pr_ready.py index c10e7b2ac..8268d5ab7 100644 --- a/tests/test_pr_ready.py +++ b/tests/test_pr_ready.py @@ -9,6 +9,7 @@ PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/hor "horizon-theme": "crates/horizon-theme", "xtask": "xtask"} LIBRARIES = set(PACKAGES) - {"xtask"} DEPENDENCIES = {"horizon-client": {"horizon-core"}} +MODS = " --features horizon-mods/runtime,horizon-mods/pack,horizon-client/mods" def args(host="local", quick=False): @@ -58,9 +59,9 @@ class PrReadyTests(unittest.TestCase): steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) by_name = {step.name: step for step in steps} self.assertEqual(by_name["clippy"].command, - "cargo clippy --workspace --all-targets --locked -- -D warnings") + "cargo clippy --workspace" + MODS + " --all-targets --locked -- -D warnings") self.assertEqual(by_name["tests: workspace"].command, - "cargo test --locked --workspace --tests") + "cargo test --locked --workspace" + MODS + " --tests") self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc") def test_non_rust_changes_skip_workspace_checks(self): diff --git a/tools/audio_harness.py b/tools/audio_harness.py index 6a26f2d44..1d5908fe0 100644 --- a/tools/audio_harness.py +++ b/tools/audio_harness.py @@ -37,7 +37,7 @@ def require_sounds(): def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800): - """Run oracle and example on inputs; returns the number of matched lines.""" + """Run oracle and the client probe `example` on inputs; returns the number of matched lines.""" require_sounds() lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() @@ -46,7 +46,7 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= report = build / 'report.json' report.unlink(missing_ok=True) oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java' - example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs' + example_path = lab.ROOT / f'crates/horizon-client/examples/probe/{example}.rs' sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -65,10 +65,10 @@ def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args= dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle_path], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else '')) - run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name == 'nt' else 'probe') + run([binary, example, *rust_args, inputs, build / 'rust.txt'], 'rust') env = dict(os.environ, ALSOFT_DRIVERS='null') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'], 'client', env=env) diff --git a/tools/block_update_harness.py b/tools/block_update_harness.py index 24483f5ed..852c013d5 100644 --- a/tools/block_update_harness.py +++ b/tools/block_update_harness.py @@ -133,8 +133,8 @@ def execute(name, cases, args, facts, origin_of=None): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaBlockUpdateOracle.java')]) run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockUpdateOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'block_update_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) + run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'block_update_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT, env={**os.environ, 'CARGO_BUILD_JOBS': '3'}) ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) native = split_cases((work / 'native.txt').read_text(), ignore) rust = split_cases((work / 'rust.txt').read_text(), ignore) diff --git a/tools/interaction_lab.py b/tools/interaction_lab.py index 0851b6d06..bc574b73d 100644 --- a/tools/interaction_lab.py +++ b/tools/interaction_lab.py @@ -50,7 +50,7 @@ def cargo_example(package, example, *args, profile=None): command = ['cargo', 'run', '-q', '-j3'] if profile: command += ['--profile', profile] - command += ['-p', package, '--example', example, '--', *map(str, args)] + command += ['-p', package, '--example', 'probe', '--', example, *map(str, args)] subprocess.run(command, check=True, cwd=lab.ROOT) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 49ba0d186..801f90220 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -68,6 +68,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; +- styles: a styled tellraw reaches the host and the guest (each its own) with its colour, bold, click and hover + events; each player's /give tells them of the Diamonds! advancement before the give's + own message, and never echoes their command back to them as `[Name: ...]`; - effects: a beacon's power reaches every player in range, the host and the guest; - distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) @@ -142,6 +145,11 @@ address. The script then checks, from both sides, what a guest's game used to ge it (#1222). - frames: the host and the guest each put a diamond in an item frame and turn it, and put a helmet on an armor stand and take it back (#1222). +- hands: the host and the guest each, at a cow that cares for none of it: draw a bow and shoot, and + let go of a golden apple at once without eating it (the click goes on to the item); + milk the cow with a bucket in the off hand and feed it wheat from the off hand; and + punch the diamond out of an item frame, which then shows empty on both sides (#1350, + #1355, #1362). - mounts: the host and the guest each open a tamed horse's, donkey's and llama's inventory (shift + right click, then the inventory key while riding), put on a saddle, armour or a carpet and fill the chest by shift-clicking. @@ -247,7 +255,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -1488,8 +1496,8 @@ def check_loom(host, guest, out): def own_reply(event): """A chat event that answers the guest's own command. On the server thread the guest also gets - its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next - command must not be taken for.""" + its own command's `[Guest: ...]` operator broadcast before #1373, a moment later, which an answer + to the next command must not be taken for.""" return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ') @@ -2054,6 +2062,69 @@ def check_chat(host, guest, out): return seen +def styled_parts(component): + """Every component in a chat line's tree (the line, its `extra` and `with` parts).""" + if isinstance(component, dict): + yield component + for key in ('extra', 'with'): + for part in component.get(key) or []: + yield from styled_parts(part) + elif isinstance(component, list): + for part in component: + yield from styled_parts(part) + + +def check_styles(host, guest, out): + # ChatComponent keeps what the server sent: the style, the click and the hover event. + stamp = f'STYLE {int(time.time())}' + line = {'text': stamp, 'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': {'action': 'show_text', 'value': 'Tip'}} + seen = {} + for g in (host, guest): + # Each to itself: tellraw reaches only the player whose command it is here. + since = g.raw('events')['last'] + g('command', command='tellraw @s ' + json.dumps(line)) + g.raw('wait-for', 'chat', stamp, '--timeout', 10, '--since', since) + part = next((p for c in g.raw('messages', 10)['styled'] for p in styled_parts(c) + if stamp in str(p.get('text', ''))), None) or {} + seen[g.name] = {k: part.get(k) for k in ('color', 'bold', 'click_event', 'hover_event')} + hover = seen[g.name]['hover_event'] or {} + seen[g.name]['hover_event'] = [hover.get('action'), 'Tip' in str(hover.get('value'))] + # InventoryChangeTrigger fires inside /give, before its message; the operator echo + # (broadcastToAdmins) skips the player whose command it was. + order = {} + for g in (host, guest): + for command in ('advancement revoke @s everything', 'clear @s'): + g('command', command=command) + g.wait(5) + since = g.raw('events')['last'] + g('command', command='give @s minecraft:diamond') + g.raw('wait-for', 'chat', 'Diamonds!', '--timeout', 10, '--since', since) + g.wait(20) + chat = g.raw('messages', 8)['chat'] + name = GUEST_NAME if g is guest else host.player + gave = next((i for i, l in enumerate(chat) if l.startswith('Gave 1 [Diamond]')), None) + made = next((i for i, l in enumerate(chat) if '[Diamonds!]' in l), None) + echo = [l for l in chat if l.startswith(f'[{name}: ')] + # Newest first: the give's message is newer than the advancement's. + order[g.name] = {'gave': gave, 'advancement': made, 'echo': echo} + guest.raw('key', 't', 'tap') + guest.wait(5) + guest.shot(out, 'styles') + guest.raw('key', 'esc', 'tap') + want = {'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': ['show_text', True]} + for name, got in seen.items(): + assert got == want, f'{name} styled line: {got}' + for name, o in order.items(): + assert o['gave'] is not None and o['advancement'] is not None, f'{name} chat: {o}' + assert o['gave'] < o['advancement'], f'{name}: the give came before the advancement: {o}' + assert not o['echo'], f'{name} heard its own command: {o}' + return {'styles': seen, 'order': order} + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -3707,6 +3778,88 @@ def check_frames(host, guest, out): return result +def check_hands(host, guest, out): + """#1350, #1355, #1362: right clicks a cow passes go on to the item, the off hand gets its + turn on the cow, and a frame punched empty is empty for everyone.""" + result = {} + spots = apart(host, guest) + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + player('command', command='clear @s') + player('command', command='effect clear @s') + # A cow two blocks ahead that stays put, and a framed diamond on a wall behind the player. + player('command', command=f'summon minecraft:cow {x + 0.5} {y} {z + 3.5} {{NoAI:1b}}') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:stone') + player('command', command=f'summon minecraft:item_frame {x + 0.5} {y + 1.5} {z - 0.97} ' + f'{{block_pos:[I;{x},{y + 1},{z - 1}],Facing:3b,Item:{{id:"minecraft:diamond",count:1}}}}') + player.wait(20) + counts = lambda: player('inventory')['counts'] + aim_cow = lambda: player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 0.8:.2f}', f'{z + 3.5:.2f}') + try: + player('command', command='give @s minecraft:bow') + player('command', command='give @s minecraft:arrow 6') + player.wait(5) + player.raw('select', 'minecraft:bow') + aim_cow() + assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow' + # Half drawn: a full draw is a crit, up to 10 damage (AbstractArrow.onHitEntity), which + # kills the 10 health cow one shot in five. Under 20 ticks the arrow does at most 6. + player.raw('mouse', 'right', 'down') + player.wait(10) + drawn = player('state')['using'] + player.raw('mouse', 'right', 'up') + player.wait(20) + assert drawn, f'the {label}\'s bow is not drawn at the cow' + assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}' + aim_cow() + cow = player('looking_at').get('entity') or {} + assert cow.get('health', 0) > 0, f'the {label}\'s arrow killed the cow: {cow}' + player('command', command='clear @s') + player('command', command='give @s minecraft:golden_apple') + player.wait(5) + player.raw('select', 'minecraft:golden_apple') + aim_cow() + player.raw('mouse', 'right', 'down') + player.wait(5) + player.raw('mouse', 'right', 'up') + player.wait(40) + assert counts().get('minecraft:golden_apple') == 1, f'the {label} ate the apple let go of: {counts()}' + # The main hand empty, a bucket and then wheat in the off hand. + player('command', command='clear @s') + player('command', command='item replace entity @s weapon.offhand with minecraft:bucket') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['item'] == 'minecraft:milk_bucket', f'the {label}\'s off hand holds {offhand}' + player('command', command='item replace entity @s weapon.offhand with minecraft:wheat 3') + player.wait(5) + aim_cow() + player.raw('mouse', 'right', 'click') + player.wait(15) + offhand = player('inventory')['offhand'] + assert offhand and offhand['count'] == 2, f'the {label}\'s cow ate no off hand wheat: {offhand}' + # The framed diamond, punched out. + frame = [o for o in player('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert frame and frame[0]['item'] == 'minecraft:diamond', f'the {label} sees the frame as {frame}' + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z - 0.95:.2f}') + player.raw('mouse', 'left', 'click') + player.wait(20) + for side, game in ((label, player), ('other side', other)): + seen = [o for o in game('status')['objects'] if o['kind'].endswith('item_frame') + and o['position'] == [x, y + 1, z - 1]] + assert seen and seen[0].get('item') is None, f'the {side} sees the punched frame as {seen}' + result[label] = {'bow': 'shot', 'apple': 'kept', 'off hand': 'milked, fed', 'frame': 'emptied'} + finally: + player('command', command=f'kill @e[type=!minecraft:player,x={x - 3},y={y - 1},z={z - 3},dx=6,dy=4,dz=8]') + player('command', command=f'fill {x - 1} {y} {z - 2} {x + 1} {y + 2} {z - 2} minecraft:air') + player('command', command='clear @s') + return result + + # Animals a player rides: (kind, summon NBT, what readies it, what is held to ride, the test # while riding). `move` walks forward, `jump` charges the horse's jump bar, `rise` holds jump on # a happy ghast, `sit` only rides (a llama goes where it likes). @@ -4247,7 +4400,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn, 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, - 'chat': check_chat, 'machines': check_machines, 'brewing': check_brewing, + 'chat': check_chat, 'styles': check_styles, 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom, 'stonecutter': check_stonecutter, 'grindstone': check_grindstone, 'anvil': check_anvil, 'smithing': check_smithing, 'enchanting': check_enchanting, 'beacon': check_beacon, 'crafter': check_crafter, 'lectern': check_lectern, @@ -4262,7 +4415,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, - 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, + 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, 'worldspawn': check_world_spawn, 'beds': check_beds, 'shield': check_shield, 'deathmining': check_death_mining, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, diff --git a/tools/oracle_harness.py b/tools/oracle_harness.py index a19b5ba94..c6f45553f 100644 --- a/tools/oracle_harness.py +++ b/tools/oracle_harness.py @@ -31,12 +31,13 @@ def compile_oracle(build, oracle_name, jars, libraries, java_major): def build_probe(build, example): - run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], + """Build the horizon-client probe binary; returns the command that runs probe `example`.""" + run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3')) import json metadata = json.loads(subprocess.check_output( ['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - return Path(metadata['target_directory']) / 'debug/examples' / example + return [Path(metadata['target_directory']) / 'debug/examples/probe', example] def java_run(build, classes, dependencies, main_class, args, name, jvm=()): @@ -64,13 +65,13 @@ def differential(name, oracle, probe, make_input, scope, sources=(), expected_li all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs', - lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)] + lab.ROOT / f'crates/horizon-client/examples/probe/{probe}.rs', *map(Path, sources)] tested = base.source_hashes(all_sources) input_path, units = make_input(build) input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = build_probe(build, probe) - run_logged([binary, input_path, build / 'rust.txt'], build, 'rust') + command = build_probe(build, probe) + run_logged([*command, input_path, build / 'rust.txt'], build, 'rust') java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client') try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/parity.py b/tools/parity.py index 4113cc791..a1a9f4133 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -65,6 +65,7 @@ SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve() MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2)) HOST = socket.gethostname().split(".")[0] DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here +FAILURE_TAILS, FAILURE_TAIL_LINES = 10, 30 # the summary prints the end of the first failures' logs def harness_settings(path): @@ -464,6 +465,42 @@ def narrow_rust_sources(sources, scope): return sorted(kept), None +PROBE_SOURCE = re.compile(r"/examples/probe/(?:(support)/)?(\w+)\.rs$") + + +def probes_run(commands): + """The probes a harness ran through a crate's probe binary: `probe ...`, or + `cargo run --example probe -- ...`.""" + names = set() + for arguments in commands: + program = Path(arguments[0]).name if arguments else "" + if program in ("probe", "probe.exe") and len(arguments) > 1: + names.add(arguments[1]) + elif program == "cargo" and "--" in arguments and "probe" in arguments[:arguments.index("--")] \ + and len(arguments) > arguments.index("--") + 1: + names.add(arguments[arguments.index("--") + 1]) + return names + + +def only_probes_run(paths, names): + """A probe binary's dep-info lists every probe in it. Keep those the harness ran, the probes they include! or + name (crate::) and the shared support modules they name (support::), so that editing one probe + reruns only its own harnesses. Files in a probe's own subdirectory and dispatch.rs, which runs them, are always + kept; main.rs, which only lists them, is left out, so adding a probe reruns nothing.""" + if not names: + return paths + names, used = {*names, "dispatch"}, "" + while True: + ran = [path for path in paths if (match := PROBE_SOURCE.search(path)) and not match.group(1) and match.group(2) in names] + used = "".join((ROOT / path).read_text(encoding="utf-8", errors="replace") for path in ran) + included = {*re.findall(r'include!\("(\w+)\.rs"\)', used), *re.findall(r"\bcrate::(\w+)", used)} - names + if not included: + break + names |= included + return [path for path in paths if not (match := PROBE_SOURCE.search(path)) + or (f"support::{match.group(2)}" in used if match.group(1) else match.group(2) in names)] + + def dependencies(trace, scope=None): """Repository files a traced harness depended on, relative to ROOT, and the probes it built. @@ -495,7 +532,8 @@ def dependencies(trace, scope=None): for artifact in artifacts: if artifact not in unique: unique.append(artifact) - kept, note = narrow_rust_sources(sorted(kept), scope) if scope else (sorted(kept), None) + kept = only_probes_run(sorted(kept), probes_run(trace["commands"])) + kept, note = narrow_rust_sources(kept, scope) if scope else (kept, None) if note: print(f"note: PARITY_RUST_SCOPE not applied: {note}", flush=True) return kept, unique @@ -1324,8 +1362,17 @@ def main(): failed = sorted(name for name, record in results.items() if record["status"] != "pass") finished_run(failed) print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.") - for name in failed: - print(f" {name}: {STATE_DIR / 'logs' / (name + '.log')}") + for index, name in enumerate(failed): + log = STATE_DIR / 'logs' / (name + '.log') + print(f" {name}: {log}") + # The end of a harness's output says why it failed, and CI shows only this output. + if index < FAILURE_TAILS: + try: + lines = log.read_text(encoding='utf-8', errors='replace').splitlines()[-FAILURE_TAIL_LINES:] + except OSError: + lines = [] + for line in lines: + print(f" {line[:300]}") return 1 if failed else 0 diff --git a/tools/port_regen.py b/tools/port_regen.py index be2d31843..c47e7cc35 100644 --- a/tools/port_regen.py +++ b/tools/port_regen.py @@ -229,10 +229,10 @@ def gen_vanilla_order(root, version, store, build): "dev.horizonlab.parity.VanillaCommandParseOracle", "tree", build], build) env = dict(os.environ, CARGO_TARGET_DIR=str(root / ".local" / "port-target")) jobs = os.environ.get("FLEET_LOAD_JOBS") - run(["cargo", "build", "-p", "horizon-client", "--example", "command_parse_fixture", + run(["cargo", "build", "-p", "horizon-client", "--example", "probe", *(["-j", jobs] if jobs else [])], root, env=env) - fixture = root / ".local/port-target/debug/examples/command_parse_fixture" - run([fixture, "tree", build / "rust_tree.json"], root) + fixture = root / ".local/port-target/debug/examples/probe" + run([fixture, "command_parse_fixture", "tree", build / "rust_tree.json"], root) return [python(), "tools/generate_command_order.py", build / "tree.json", build / "rust_tree.json"] diff --git a/tools/pr_ready.py b/tools/pr_ready.py index e3e317ef8..a944e2116 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -274,6 +274,16 @@ def parity_summary(output): return text +def mod_features(crates): + """Code mods are off by default (docs/mods.md): on wherever horizon-mods is checked, as in CI.""" + if crates is not None and "horizon-mods" not in crates: + return "" + features = ["horizon-mods/runtime", "horizon-mods/pack"] + if crates is None or "horizon-client" in crates: + features.append("horizon-client/mods") + return f" --features {','.join(features)}" + + def plan(args, base, changed, crates_of, libraries, dependencies): """The checks for these changed files, in the order they run.""" rust = any(workspace_rust(path) for path in changed) @@ -297,10 +307,10 @@ def plan(args, base, changed, crates_of, libraries, dependencies): Step("Python tests", "python3 -m unittest discover -s tests", where="here", skip=None if python else "no Python change", summary=unittest_passed), Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust), - Step("clippy", f"cargo clippy {clippy_selection} --all-targets --locked -- -D warnings", + Step("clippy", f"cargo clippy {clippy_selection}{mod_features(clippy_crates)} --all-targets --locked -- -D warnings", skip=None if rust else no_rust), Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""), - f"cargo test --locked {selection} --tests", + f"cargo test --locked {selection}{mod_features(crates)} --tests", skip=test_skip, summary=tests_passed), Step("doc tests", f"cargo test --locked {doc_selection} --doc", skip=test_skip or (None if doc_crates else "no library touched"), summary=tests_passed), diff --git a/tools/test_active_effect_tick_parity.py b/tools/test_active_effect_tick_parity.py index 61207ca45..dcb34ae21 100644 --- a/tools/test_active_effect_tick_parity.py +++ b/tools/test_active_effect_tick_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effect_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effect_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,14 +72,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effect_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effect_tick_fixture.exe' if os.name=='nt' else 'active_effect_tick_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effect_tick_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_active_effects_parity.py b/tools/test_active_effects_parity.py index 16338b15f..926c2ecf8 100644 --- a/tools/test_active_effects_parity.py +++ b/tools/test_active_effects_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaActiveEffectsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/active_effects_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/active_effects_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,14 +61,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaActiveEffectsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','active_effects_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('active_effects_fixture.exe' if os.name=='nt' else 'active_effects_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'active_effects_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_ambient_sound_parity.py b/tools/test_ambient_sound_parity.py index 85cfb20e1..7e272fa94 100644 --- a/tools/test_ambient_sound_parity.py +++ b/tools/test_ambient_sound_parity.py @@ -177,7 +177,7 @@ def main(): 'ambient', 'VanillaAmbientOracle', 'ambient_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, ' 'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance ' diff --git a/tools/test_anchor_parity.py b/tools/test_anchor_parity.py index fbff1d7e6..19b8f6e4b 100644 --- a/tools/test_anchor_parity.py +++ b/tools/test_anchor_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAnchorOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/anchor_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/anchor_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -53,10 +53,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","anchor_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("anchor_fixture.exe" if os.name=="nt" else "anchor_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"anchor_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_arrow_parity.py b/tools/test_arrow_parity.py index 0daa2e311..72692eb55 100644 --- a/tools/test_arrow_parity.py +++ b/tools/test_arrow_parity.py @@ -3,7 +3,7 @@ Real vanilla `Arrow` entities tick in an independently built copy of the scene (`VanillaArrowOracle`, client and server jars); Horizon's -`arrows::tick` runs over the scene itself (`examples/arrow_probe.rs`). Every +`arrows::tick` runs over the scene itself (`examples/probe/arrow_probe.rs`). Every operation prints the arrow's position, motion, rotation, ground state, life, shake, stuck block, fire ticks, water flags, fluid heights, removal, crit flag, fall distance and old position (what rendering interpolates from) by exact @@ -224,7 +224,7 @@ def main(): 'VanillaHeightmapOracle', 'VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaSuffocationOracle', 'VanillaFaceSupportOracle', 'VanillaEntityAttributeOracle', 'VanillaBlockLandingOracle', 'VanillaMovementRegistryOracle', 'VanillaDamageSourceOracle']] sources = [Path(__file__), lab.ROOT / 'tools/test_native_client.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', - oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/arrow_probe.rs'] + oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/arrow_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -241,15 +241,15 @@ def main(): expected = 3 * operations + len(fixtures) (build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(build / 'inputs.txt', 'sha256') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'arrow_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'debug/examples' / ('arrow_probe.exe' if os.name == 'nt' else 'arrow_probe') - run([binary, resources, build, '--describe'], 'describe') + binary = Path(metadata['target_directory']) / 'debug/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'arrow_probe',resources, build, '--describe'], 'describe') references = [] for side, jar in jars.items(): run(['java', '-Xmx768M', '-cp', os.pathsep.join([str(classes), str(jar), dependencies]), 'dev.horizonlab.parity.VanillaArrowOracle', side, build, resources], side) - run([binary, resources, build, side], 'rust-' + side) + run([binary, 'arrow_probe',resources, build, side], 'rust-' + side) matched = base.compare(build / (side + '.txt'), build / ('rust-' + side + '.txt')) if matched != expected: raise AssertionError('Incomplete arrow output') diff --git a/tools/test_attribute_health_parity.py b/tools/test_attribute_health_parity.py index e243b60ea..eaf06d857 100644 --- a/tools/test_attribute_health_parity.py +++ b/tools/test_attribute_health_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_health_fixture.exe' if os.name=='nt' else 'attribute_health_fixture') - run([binary,build],'rust');run([binary,build,'live'],'rust-live');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_health_fixture',build],'rust');run([binary,'attribute_health_fixture',build,'live'],'rust-live');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') live_matched=base.compare(reference,build/'rust-live.txt') diff --git a/tools/test_attribute_map_queries_parity.py b/tools/test_attribute_map_queries_parity.py index 24c1b134e..ca222a07c 100644 --- a/tools/test_attribute_map_queries_parity.py +++ b/tools/test_attribute_map_queries_parity.py @@ -69,9 +69,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeMapQueriesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_map_queries_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_map_queries_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py',lab.ROOT/'tools/test_stored_effect_notifications_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,14 +82,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeMapQueriesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_map_queries_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_map_queries_fixture.exe' if os.name=='nt' else 'attribute_map_queries_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_map_queries_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} attribute map query output lines match Rust',flush=True) diff --git a/tools/test_attribute_parity.py b/tools/test_attribute_parity.py index c5bd95210..02051188d 100644 --- a/tools/test_attribute_parity.py +++ b/tools/test_attribute_parity.py @@ -78,7 +78,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -89,10 +89,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'attributes.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'attributes.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_fixture.exe' if os.name=='nt' else 'attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_attribute_updates_parity.py b/tools/test_attribute_updates_parity.py index f4959be0a..cc4f70d1a 100644 --- a/tools/test_attribute_updates_parity.py +++ b/tools/test_attribute_updates_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaAttributeUpdatesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/attribute_updates_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/"tools/test_effect_notifications_parity.py",lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/attribute_updates_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,14 +70,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaAttributeUpdatesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','attribute_updates_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('attribute_updates_fixture.exe' if os.name=='nt' else 'attribute_updates_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'attribute_updates_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py index 3e9da7d5a..348bbdbc8 100644 --- a/tools/test_auto_jump_parity.py +++ b/tools/test_auto_jump_parity.py @@ -115,7 +115,7 @@ def main(): sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java', parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/auto_jump_probe.rs', lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs'] tested = base.source_hashes(sources) fixtures = list(cases(random.Random(0x4155544f))) @@ -123,8 +123,8 @@ def main(): inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures)) input_hash = lab.digest(inputs, 'sha256') classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, 'auto_jump_probe') - harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) + command = harness.build_probe(build, 'auto_jump_probe') + harness.run_logged([*command, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600) harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client') matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures)) base.ensure_sources_unchanged(sources, tested) diff --git a/tools/test_basic_feature_parity.py b/tools/test_basic_feature_parity.py index 001397965..2de93cd1a 100644 --- a/tools/test_basic_feature_parity.py +++ b/tools/test_basic_feature_parity.py @@ -57,7 +57,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBasicFeatureOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/basic_feature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/basic_feature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -71,10 +71,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","basic_feature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("basic_feature_fixture.exe" if os.name=="nt" else "basic_feature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"basic_feature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_chunk_parity.py b/tools/test_biome_chunk_parity.py index f484c1c5f..f24370455 100644 --- a/tools/test_biome_chunk_parity.py +++ b/tools/test_biome_chunk_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeChunkOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_chunk_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_chunk_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -57,10 +57,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_chunk_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_chunk_fixture.exe" if os.name=="nt" else "biome_chunk_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_chunk_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_generation_parity.py b/tools/test_biome_generation_parity.py index 4c38070d7..67c642585 100644 --- a/tools/test_biome_generation_parity.py +++ b/tools/test_biome_generation_parity.py @@ -53,7 +53,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeGenerationOracle.java" exporter=oracle.with_name("VanillaBiomeExport.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_generation_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_generation_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -76,10 +76,10 @@ def main(): registries=build/'registries.json';registries.write_text(json.dumps(bundle,separators=(',',':')),encoding='utf-8') fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,registries,*exports];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_generation_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_generation_fixture.exe" if os.name=="nt" else "biome_generation_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_generation_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_placement_parity.py b/tools/test_biome_placement_parity.py index 21408e20f..caf99b7c9 100644 --- a/tools/test_biome_placement_parity.py +++ b/tools/test_biome_placement_parity.py @@ -44,7 +44,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomePlacementOracle.java' helper=oracle.with_name("VanillaPlacementOracle.java") - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/biome_placement_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/biome_placement_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','biome_placement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('biome_placement_fixture.exe' if os.name=='nt' else 'biome_placement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'biome_placement_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaBiomePlacementOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_biome_source_codec_parity.py b/tools/test_biome_source_codec_parity.py index 58989d884..9363378af 100644 --- a/tools/test_biome_source_codec_parity.py +++ b/tools/test_biome_source_codec_parity.py @@ -72,7 +72,7 @@ def main(): exporter=oracle.with_name("VanillaBiomeExport.java") helpers=[oracle.with_name(name+".java") for name in ["VanillaMaterialConditionOracle","VanillaAnchorOracle","VanillaBiomeTemperatureOracle"]] sources=[oracle,exporter,*helpers,lab.ROOT/"tools/test_biome_temperature_parity.py",lab.ROOT/"tools/test_material_condition_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_codec_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_codec_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -95,10 +95,10 @@ def main(): fixtures=list(corpus(bundle));inputs=build/'inputs.txt';inputs.write_text('\n'.join(fixtures)+'\n',encoding='utf-8') (build/'positions.json').write_text(json.dumps(positions(),separators=(',',':')),encoding='utf-8') fixture_paths=[inputs,*exports,build/'positions.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_codec_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_codec_fixture.exe" if os.name=="nt" else "biome_source_codec_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_codec_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_source_parity.py b/tools/test_biome_source_parity.py index 093c92427..7616f7545 100644 --- a/tools/test_biome_source_parity.py +++ b/tools/test_biome_source_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeSourceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_source_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_source_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -44,10 +44,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_source_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_source_fixture.exe" if os.name=="nt" else "biome_source_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_source_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_biome_temperature_parity.py b/tools/test_biome_temperature_parity.py index 1edec516e..af8d75976 100644 --- a/tools/test_biome_temperature_parity.py +++ b/tools/test_biome_temperature_parity.py @@ -74,7 +74,7 @@ def main(): (build/'biomes.json').write_text(json.dumps(biomes,separators=(',',':')),encoding='utf-8') oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBiomeTemperatureOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/biome_temperature_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/biome_temperature_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(biomes)];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"biomes.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -82,10 +82,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","biome_temperature_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("biome_temperature_fixture.exe" if os.name=="nt" else "biome_temperature_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"biome_temperature_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_block_collision_scan_parity.py b/tools/test_block_collision_scan_parity.py index 97c6e12b7..a59bfd8f9 100644 --- a/tools/test_block_collision_scan_parity.py +++ b/tools/test_block_collision_scan_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockCollisionScanOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_collision_scan_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_collision_scan_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockCollisionScanOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_collision_scan_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_collision_scan_fixture.exe' if os.name=='nt' else 'block_collision_scan_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_collision_scan_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index 8935afef4..b0c462aee 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -9,7 +9,7 @@ on a stand-in client level, then per scripted step applies the block event (triggerEvent), runs the entity's own client ticker and the renderer's extractRenderState, printing the fields, the level calls the tick made (neighbour updates, entity pushes/queries, sounds, particles) and the render -state. `examples/block_entity_anim_fixture` replays the steps through +state. `examples/probe/block_entity_anim_fixture` replays the steps through `horizon_client::block_entity_anim` and derives the render state from the `BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits). @@ -279,8 +279,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', inputs, build / 'vanilla.txt'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--', - resources, inputs, build / 'rust.txt'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_anim_fixture', resources, inputs, build / 'rust.txt'], 'rust') def split(path): result, current = {}, None diff --git a/tools/test_block_entity_render_parity.py b/tools/test_block_entity_render_parity.py index 3c096bdcc..901f4300f 100644 --- a/tools/test_block_entity_render_parity.py +++ b/tools/test_block_entity_render_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaBlockEntityRenderOracle) builds each case's vanilla block entity, sets its animation fields, runs the real BlockEntityRenderer's extractRenderState and submit, and captures what it submits: model vertices after setupAnim and the pose stack (sprite-local UVs, tint, normal, light), -text calls and items. `examples/block_entity_render_fixture` replays the case +text calls and items. `examples/probe/block_entity_render_fixture` replays the case through Horizon's BlockEntityRenderer. Quads are matched by texture and position; colours compare vanilla's tint times the entity shader's `minecraft_mix_light` for the vanilla normal with Horizon's baked colour. @@ -303,8 +303,8 @@ def main(): vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] textures = sorted({s['texture'] for v in vanilla for s in v.get('submits', []) if 'texture' in s}) (build / 'textures.txt').write_text(''.join(t + '\n' for t in textures)) - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_render_fixture', '--', - resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'block_entity_render_fixture', resources, inputs, build / 'textures.txt', build / 'rust.jsonl'], 'rust') rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) groups, errors, skipped, passed = {}, {}, {}, 0 diff --git a/tools/test_block_entity_storage_parity.py b/tools/test_block_entity_storage_parity.py index 7e90ac530..a1f378f31 100644 --- a/tools/test_block_entity_storage_parity.py +++ b/tools/test_block_entity_storage_parity.py @@ -67,7 +67,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_entity_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_entity_storage_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','block_entity_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_entity_storage_fixture.exe' if os.name=='nt' else 'block_entity_storage_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_entity_storage_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaBlockEntityStorageOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_block_entity_tickers_parity.py b/tools/test_block_entity_tickers_parity.py index 459e7a926..66a84cf48 100644 --- a/tools/test_block_entity_tickers_parity.py +++ b/tools/test_block_entity_tickers_parity.py @@ -6,7 +6,7 @@ one chunk to make its block entity map grow), place, replace and remove block entities, give jukeboxes a record and take it, and unload chunks, with ticks in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s of a server level and prints, after each tick, the positions of the live -tickers in list order; `examples/block_entity_tickers_fixture` runs the same +tickers in list order; `examples/probe/block_entity_tickers_fixture` runs the same on `horizon_client::block_entities::BlockEntities`. The block entities are the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners, trial spawners, vaults, hives, crafters, brewing stands, jukebox), with chests and barrels, @@ -120,7 +120,7 @@ def main(): run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla') run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', - 'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust') + 'probe', '--', 'block_entity_tickers_fixture', inputs, build / 'rust.txt'], 'rust') matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') ticks = sum(1 for line in lines if line == 'tick') listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines()) diff --git a/tools/test_block_landing_parity.py b/tools/test_block_landing_parity.py index 0b2792d82..822ff1614 100644 --- a/tools/test_block_landing_parity.py +++ b/tools/test_block_landing_parity.py @@ -56,7 +56,7 @@ def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-block-landing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[root/(n+'.java') for n in ['VanillaBlockLandingOracle','VanillaMovementRegistryOracle','VanillaHeightmapOracle','VanillaCollisionOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/block_landing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/block_landing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -69,9 +69,9 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(states,definitions):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','landing-states.json','landing-definitions.json','movement-properties.nbt','block-registry.nbt','cached-collision.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','block_landing_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('block_landing_fixture.exe' if os.name=='nt' else 'block_landing_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered block landing lines match',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_block_particles_parity.py b/tools/test_block_particles_parity.py index 3f0f0f99c..7e08e98f8 100644 --- a/tools/test_block_particles_parity.py +++ b/tools/test_block_particles_parity.py @@ -13,7 +13,7 @@ def main(): resources = lab.RESOURCES build = lab.LOCAL / "block-particles-parity" build.mkdir(exist_ok=True) - paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] + paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/probe/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] tested = base.source_hashes(paths) rows = [dict(case=i, seed=(-1 if i % 2 else 1) * i * 987654321, **row) for i, row in enumerate(breaking.cases(resources))] rows[0]["seed"] = -(2**63) @@ -21,8 +21,8 @@ def main(): inputs = build / "inputs.jsonl" inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes, dependencies, _ = harness.compile_oracle(build, "VanillaBlockParticlesOracle", jars, baking.client_libraries(), lock["minecraft"]["java_major"]) - binary = harness.build_probe(build, "block_particles_fixture") - harness.run_logged([binary, resources, inputs, build / "rust.jsonl"], build, "rust") + command = harness.build_probe(build, "block_particles_fixture") + harness.run_logged([*command, resources, inputs, build / "rust.jsonl"], build, "rust") harness.java_run(build, classes, dependencies, "VanillaBlockParticlesOracle", [inputs, build / "client.jsonl"], "client") count = hits = burst = 0 max_error = 0.0 diff --git a/tools/test_block_properties_parity.py b/tools/test_block_properties_parity.py index da2f9dd11..28cd2832c 100644 --- a/tools/test_block_properties_parity.py +++ b/tools/test_block_properties_parity.py @@ -45,7 +45,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPropertiesOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_properties_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_properties_fixture.exe' if os.name=='nt' else 'block_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_push_parity.py b/tools/test_block_push_parity.py index 273f9e8de..986a3b1c9 100644 --- a/tools/test_block_push_parity.py +++ b/tools/test_block_push_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockPushOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_push_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_push_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockPushOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_push_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_push_fixture.exe' if os.name=='nt' else 'block_push_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_push_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_state_codec_parity.py b/tools/test_block_state_codec_parity.py index 1eb3ebe4a..e6db50860 100644 --- a/tools/test_block_state_codec_parity.py +++ b/tools/test_block_state_codec_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockStateCodecOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_state_codec_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_state_codec_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_state_codec_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_state_codec_fixture.exe' if os.name=='nt' else 'block_state_codec_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_state_codec_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_support_parity.py b/tools/test_block_support_parity.py index 2d7cb8b9c..928f099d1 100644 --- a/tools/test_block_support_parity.py +++ b/tools/test_block_support_parity.py @@ -24,7 +24,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSupportOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_support_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -35,10 +35,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockSupportOracle',mode,path],side+'-'+mode) java('server','export',build) fixture_paths=[build/'block-registry.nbt',build/'cached-support.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_support_fixture.exe' if os.name=='nt' else 'block_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'block_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_block_survival_parity.py b/tools/test_block_survival_parity.py index fac8f64b1..2d99db9e2 100644 --- a/tools/test_block_survival_parity.py +++ b/tools/test_block_survival_parity.py @@ -205,7 +205,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockSurvivalOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/block_survival_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/block_survival_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -236,9 +236,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'fluid-tags.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'facts.json',build/'survival-classes.json',build/'survival-rules.json',build/'tags.json',build/'block-registry.nbt',build/'cached-collision.nbt',build/'block-properties.nbt',build/'cached-support.nbt'] tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','block_survival_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('block_survival_fixture.exe' if os.name=='nt' else 'block_survival_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':{'supported_blocks':len(definitions),'supported_states':sum(state['id'] in definitions for state in facts['states']),'survival_rules':len(set(definitions.values())),'survival_rule_kinds':len({rule.split(':',1)[0] for rule in definitions.values()}),'fluid_tag_files':len(fluid_tags),'fixtures':fixture_count},'outputs':{}} save_checkpoint(checkpoint_path,checkpoint) @@ -251,7 +251,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust')) + stage('rust',lambda:run([checkpoint['binary'],'block_survival_fixture',build],'rust')) references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build)) diff --git a/tools/test_blocking_item_damage_parity.py b/tools/test_blocking_item_damage_parity.py index d9a8c9669..b8b3ea251 100644 --- a/tools/test_blocking_item_damage_parity.py +++ b/tools/test_blocking_item_damage_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingItemDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_item_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_item_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingItemDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_item_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_item_damage_fixture.exe' if os.name=='nt' else 'blocking_item_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_item_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_blocking_rules_parity.py b/tools/test_blocking_rules_parity.py index 5afc38333..2ff5763d6 100644 --- a/tools/test_blocking_rules_parity.py +++ b/tools/test_blocking_rules_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockingRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/blocking_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/blocking_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBlockingRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','blocking_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('blocking_rules_fixture.exe' if os.name=='nt' else 'blocking_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'blocking_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_breaking_model_parity.py b/tools/test_breaking_model_parity.py index 92b74d582..272e57dea 100644 --- a/tools/test_breaking_model_parity.py +++ b/tools/test_breaking_model_parity.py @@ -29,13 +29,13 @@ def canonical(quads): def main(): lock,jars,_=base.verify_artifacts();libraries=baking.client_libraries() resources=lab.RESOURCES;build=lab.LOCAL/"breaking-model-parity";build.mkdir(exist_ok=True) - paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] + paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/probe/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"] tested=base.source_hashes(paths) rows=[dict(case=i,**row) for i,row in enumerate(cases(resources))] inputs=build/"inputs.jsonl";inputs.write_text("".join(json.dumps(row)+"\n" for row in rows)) classes,dependencies,_=harness.compile_oracle(build,"VanillaBreakingModelOracle",jars,libraries,lock["minecraft"]["java_major"]) - binary=harness.build_probe(build,"breaking_fixture") - harness.run_logged([binary,resources,inputs,build/"rust.jsonl"],build,"rust") + command=harness.build_probe(build,"breaking_fixture") + harness.run_logged([*command,resources,inputs,build/"rust.jsonl"],build,"rust") harness.java_run(build,classes,dependencies,"VanillaBreakingModelOracle",[inputs,build/"client.jsonl"],"client") count=vertices=0;max_error=0.0 with (build/"client.jsonl").open() as native, (build/"rust.jsonl").open() as rust: diff --git a/tools/test_bulk_section_parity.py b/tools/test_bulk_section_parity.py index 414613067..b9a9ae3a8 100644 --- a/tools/test_bulk_section_parity.py +++ b/tools/test_bulk_section_parity.py @@ -52,7 +52,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/bulk_section_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/bulk_section_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","bulk_section_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("bulk_section_fixture.exe" if os.name=="nt" else "bulk_section_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"bulk_section_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_bundle_weight_parity.py b/tools/test_bundle_weight_parity.py index 0d42a2ded..c509e08a1 100644 --- a/tools/test_bundle_weight_parity.py +++ b/tools/test_bundle_weight_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBundleWeightOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/bundle_weight_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/bundle_weight_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaBundleWeightOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','bundle_weight_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('bundle_weight_fixture.exe' if os.name=='nt' else 'bundle_weight_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'bundle_weight_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_canyon_carver_parity.py b/tools/test_canyon_carver_parity.py index 81d281a4c..25fbc30de 100644 --- a/tools/test_canyon_carver_parity.py +++ b/tools/test_canyon_carver_parity.py @@ -54,7 +54,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCanyonCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/canyon_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/canyon_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","canyon_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("canyon_carver_fixture.exe" if os.name=="nt" else "canyon_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"canyon_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_geometry_parity.py b/tools/test_carving_geometry_parity.py index 0ad9e6da0..e69331bbe 100644 --- a/tools/test_carving_geometry_parity.py +++ b/tools/test_carving_geometry_parity.py @@ -63,7 +63,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingGeometryOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_geometry_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_geometry_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") reach=list(reach_corpus());reach_path=build/'reach.txt';reach_path.write_text(''.join(json.dumps(q,separators=(',',':'))+'\n' for q in reach),encoding='utf-8') @@ -72,10 +72,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_geometry_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_geometry_fixture.exe" if os.name=="nt" else "carving_geometry_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_geometry_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_carving_mask_parity.py b/tools/test_carving_mask_parity.py index a3d4e375c..15dacf52e 100644 --- a/tools/test_carving_mask_parity.py +++ b/tools/test_carving_mask_parity.py @@ -57,7 +57,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCarvingMaskOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/carving_mask_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/carving_mask_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -65,10 +65,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","carving_mask_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("carving_mask_fixture.exe" if os.name=="nt" else "carving_mask_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"carving_mask_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_cave_carver_parity.py b/tools/test_cave_carver_parity.py index 863dd15d4..d79914762 100644 --- a/tools/test_cave_carver_parity.py +++ b/tools/test_cave_carver_parity.py @@ -49,7 +49,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCaveCarverOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/cave_carver_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/cave_carver_fixture.rs"] tested_sources=base.source_hashes(sources) resources=worldgen.registry_resources(jars['server'],'carver') if not resources or resources!=worldgen.registry_resources(jars['client'],'carver'):raise ValueError('reference carver resources differ') @@ -60,10 +60,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","cave_carver_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("cave_carver_fixture.exe" if os.name=="nt" else "cave_carver_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"cave_carver_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_chat_screen_parity.py b/tools/test_chat_screen_parity.py index 1447ebaa6..fead1b5cb 100644 --- a/tools/test_chat_screen_parity.py +++ b/tools/test_chat_screen_parity.py @@ -8,7 +8,7 @@ all, history up and down, Tab and Shift+Tab through suggestions, Escape) and clicks (on the suggestion list, on the input). The Java oracle (VanillaChatScreenOracle) drives a real ChatScreen, whose CommandSuggestions parse with vanilla's client command tree and ask the server's dispatcher -for the suggestions a node leaves to it; examples/chat_screen_fixture runs +for the suggestions a node leaves to it; examples/probe/chat_screen_fixture runs horizon_client::chat::ChatScreen on Horizon's dispatcher. After the actions the input's value, cursor, selection and scroll and the screen's GUI calls (the input background, the EditBox with its argument colouring, cursor, diff --git a/tools/test_chunk_generation_parity.py b/tools/test_chunk_generation_parity.py index 13262dc3b..6951e4355 100644 --- a/tools/test_chunk_generation_parity.py +++ b/tools/test_chunk_generation_parity.py @@ -4,7 +4,7 @@ Vanilla side: VanillaChunkGenerationOracle drives the actual ChunkGenerator stages (structure starts and references, biomes, terrain with surface and carvers, then biome decoration with every placed feature and structure piece) -through real WorldGenRegion instances. Horizon side: the chunk_dump example +through real WorldGenRegion instances. Horizon side: the chunk_dump probe runs the same stages in the same order. Every block state, quart biome and block entity (canonical NBT) of each target chunk is compared. @@ -71,9 +71,9 @@ class Oracle: def rust_binary(): - subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'chunk_dump'], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'probe'], check=True, cwd=lab.ROOT) metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - return Path(metadata['target_directory']) / 'release/examples/chunk_dump' + return Path(metadata['target_directory']) / 'release/examples/probe' def run_rust(binary, out, seed, dimension, rects, scan=False): @@ -81,7 +81,7 @@ def run_rust(binary, out, seed, dimension, rects, scan=False): if scan: env['HORIZON_SCAN'] = '1' with open(out, 'w') as handle: - result = subprocess.run([str(binary), str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) + result = subprocess.run([str(binary), 'chunk_dump', str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT) if result.returncode: raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:]) return result.stderr diff --git a/tools/test_chunk_stage_parity.py b/tools/test_chunk_stage_parity.py index 6e055f631..b8aaa6153 100644 --- a/tools/test_chunk_stage_parity.py +++ b/tools/test_chunk_stage_parity.py @@ -55,7 +55,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_chunk_status_parity.py b/tools/test_chunk_status_parity.py index cd6c7a2d6..17c3d65ed 100644 --- a/tools/test_chunk_status_parity.py +++ b/tools/test_chunk_status_parity.py @@ -34,7 +34,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkStatusOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/chunk_status_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/chunk_status_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -42,10 +42,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','chunk_status_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('chunk_status_fixture.exe' if os.name=='nt' else 'chunk_status_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'chunk_status_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaChunkStatusOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_climbing_parity.py b/tools/test_climbing_parity.py index 9c5a57260..7b54fc4fb 100644 --- a/tools/test_climbing_parity.py +++ b/tools/test_climbing_parity.py @@ -40,7 +40,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-climbing-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaClimbingOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/climbing_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/climbing_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -54,7 +54,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','climbing_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('climbing_fixture.exe' if os.name=='nt' else 'climbing_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'climbing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} climbing output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_collision_context_parity.py b/tools/test_collision_context_parity.py index 212e0d28e..da1f382db 100644 --- a/tools/test_collision_context_parity.py +++ b/tools/test_collision_context_parity.py @@ -48,7 +48,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_collision_parity.py b/tools/test_collision_parity.py index b4d2904a8..3031e47b2 100644 --- a/tools/test_collision_parity.py +++ b/tools/test_collision_parity.py @@ -39,7 +39,7 @@ def main(): lock, jars, libraries = test_rust_parity.verify_artifacts() base = Path(tempfile.mkdtemp(prefix="run-", dir=directory)) oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionOracle.java" - sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/collision_fixture.rs"] + sources = [oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/collision_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -51,10 +51,10 @@ def main(): result.check_returncode() return result.stdout expected = counts(java("server", "generate")) - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "collision_fixture"]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) metadata = json.loads(subprocess.check_output(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=lab.ROOT, text=True)) - binary = Path(metadata["target_directory"]) / "release/examples" / ("collision_fixture.exe" if os.name == "nt" else "collision_fixture") - actual = counts(subprocess.check_output([str(binary), str(base)], cwd=lab.ROOT, text=True)) + binary = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + actual = counts(subprocess.check_output([str(binary), "collision_fixture", str(base)], cwd=lab.ROOT, text=True)) if actual != expected: raise AssertionError(f"Collision coverage differs: vanilla={expected}, Rust={actual}") canonical = {"empty_states":0,"block_states":0,"other_cached_states":0} diff --git a/tools/test_combat_rules_parity.py b/tools/test_combat_rules_parity.py index e7d2f89ac..642c0603d 100644 --- a/tools/test_combat_rules_parity.py +++ b/tools/test_combat_rules_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCombatRulesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/combat_rules_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/combat_rules_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCombatRulesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','combat_rules_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('combat_rules_fixture.exe' if os.name=='nt' else 'combat_rules_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'combat_rules_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_command_parse_parity.py b/tools/test_command_parse_parity.py index 192cc5b9f..c43e66b54 100644 --- a/tools/test_command_parse_parity.py +++ b/tools/test_command_parse_parity.py @@ -64,9 +64,9 @@ def main(): registries = json.loads((build / 'registries.json').read_text()) corpus = corpus_module.corpus(tree, registries) (build / 'corpus.txt').write_text(''.join(line + '\n' for line in corpus), encoding='utf-8') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'command_parse_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('command_parse_fixture.exe' if os.name == 'nt' else 'command_parse_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') resources = lab.RESOURCES total_failures = 0 summary = [] @@ -79,7 +79,7 @@ def main(): if not (stamp.exists() and stamp.read_text() == digest and (level_dir / 'vanilla.jsonl').exists()): java('run', str(level_dir), str(build / 'corpus.txt'), str(permission)) stamp.write_text(digest) - run([binary, resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') + run([binary, 'command_parse_fixture',resources, build / 'registries.json', build / 'corpus.txt', str(permission), level_dir / 'rust.jsonl'], f'rust{permission}') failures = compare(level_dir / 'vanilla.jsonl', level_dir / 'rust.jsonl', args.limit) count = sum(1 for _ in (level_dir / 'vanilla.jsonl').open()) print(f'permission {permission}: {count - failures}/{count} commands match', flush=True) diff --git a/tools/test_component_durability_parity.py b/tools/test_component_durability_parity.py index fa97e30d4..e912fa80b 100644 --- a/tools/test_component_durability_parity.py +++ b/tools/test_component_durability_parity.py @@ -60,7 +60,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -71,10 +71,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_durability_fixture.exe' if os.name=='nt' else 'component_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_component_patch_parity.py b/tools/test_component_patch_parity.py index dcbb1ed27..bae69bb56 100644 --- a/tools/test_component_patch_parity.py +++ b/tools/test_component_patch_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaComponentPatchOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/component_patch_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/component_patch_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaComponentPatchOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','component_patch_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('component_patch_fixture.exe' if os.name=='nt' else 'component_patch_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'component_patch_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_emission_parity.py b/tools/test_consumable_emission_parity.py index 3919be5bc..7e8085087 100644 --- a/tools/test_consumable_emission_parity.py +++ b/tools/test_consumable_emission_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_emission_fixture.exe' if os.name=='nt' else 'consumable_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consumable_parity.py b/tools/test_consumable_parity.py index 36ccf0138..083ff810f 100644 --- a/tools/test_consumable_parity.py +++ b/tools/test_consumable_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumableOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consumable_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consumable_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumableOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consumable_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consumable_fixture.exe' if os.name=='nt' else 'consumable_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consumable_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_consume_effect_parity.py b/tools/test_consume_effect_parity.py index bf3a31961..4f4037073 100644 --- a/tools/test_consume_effect_parity.py +++ b/tools/test_consume_effect_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaConsumeEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/consume_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/consume_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaConsumeEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','consume_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('consume_effect_fixture.exe' if os.name=='nt' else 'consume_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'consume_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_contextual_collision_parity.py b/tools/test_contextual_collision_parity.py index 2a2eb9090..bbfe45b02 100644 --- a/tools/test_contextual_collision_parity.py +++ b/tools/test_contextual_collision_parity.py @@ -36,7 +36,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaCollisionOracle','VanillaContextualCollisionAudit']] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars['server']),dependency_path]),'dev.horizonlab.parity.VanillaCollisionOracle','generate',build],'export') fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaContextualCollisionAudit',side,build],side+'-audit') audited=base.compare(build/(side+'-audit.txt'),build/'rust-audit.txt') diff --git a/tools/test_creative_parity.py b/tools/test_creative_parity.py index aa23cbbc9..6a96d3c52 100644 --- a/tools/test_creative_parity.py +++ b/tools/test_creative_parity.py @@ -7,7 +7,7 @@ tab built by vanilla's CreativeModeTabs over the vanilla data pack's registries), then what the vanilla client shows: every tab's display items and, for each search query, CreativeModeInventoryScreen.refreshSearchResults' items, searched through the client's own SessionSearchTrees. -examples/creative_search_fixture loads the export into +examples/probe/creative_search_fixture loads the export into horizon_client::creative::Creative. The tabs it shows (id, title, icon, position, every stack with its components), the search tab's stacks and the results of every query must agree. The queries are QUERIES below, then every diff --git a/tools/test_damage_immunity_parity.py b/tools/test_damage_immunity_parity.py index 962634bcc..d68277dd8 100644 --- a/tools/test_damage_immunity_parity.py +++ b/tools/test_damage_immunity_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageImmunityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_immunity_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_immunity_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageImmunityOracle',mode,path],side+'-'+mode) java('server','export',build);fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_immunity_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_immunity_fixture.exe' if os.name=='nt' else 'damage_immunity_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_immunity_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_reduction_parity.py b/tools/test_damage_reduction_parity.py index ad53500fb..06c827dcf 100644 --- a/tools/test_damage_reduction_parity.py +++ b/tools/test_damage_reduction_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageReductionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_reduction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_reduction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): java('server','export',build) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_reduction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_reduction_fixture.exe' if os.name=='nt' else 'damage_reduction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_reduction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_damage_source_parity.py b/tools/test_damage_source_parity.py index a532e4ff0..75f360822 100644 --- a/tools/test_damage_source_parity.py +++ b/tools/test_damage_source_parity.py @@ -45,7 +45,7 @@ def main(): resources={'minecraft:'+n[len(prefix):-5]:archive.read(n).decode('utf-8') for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')};lab.write_json(build/file,resources) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/damage_source_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/damage_source_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaDamageSourceOracle',mode,path],side+'-'+mode) java('server','export',build);catalog=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(catalog));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'types.json',build/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','damage_source_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('damage_source_fixture.exe' if os.name=='nt' else 'damage_source_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'damage_source_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index 4c189983f..dc5a2495b 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -9,7 +9,7 @@ generated automatically when missing), two upgrades run on a copy: vanilla VanillaDataFixOracle: FileFixerUpper, then DataFixers on level.dat, every chunk, entity chunk and POI chunk, player, saved data, advancements and statistics file, exactly as 26.3 does when it opens the world - horizon the `datafix_world` example of horizon-world, which does the same with + horizon the `datafix_world` probe of horizon-world, which does the same with horizon_world::datafix Then every file is compared: region files chunk by chunk, NBT files and JSON @@ -72,11 +72,11 @@ def java_classpath(): def build_rust(): - subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'datafix_world'], + subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], cwd=ROOT, check=True) meta = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=ROOT)) - return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world' + return Path(meta['target_directory']) / 'release' / 'examples' / 'probe' def run_vanilla(classpath, world, out, target=None): @@ -92,7 +92,8 @@ 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), *([str(target)] if target else [])], check=True, stdout=f, stderr=subprocess.STDOUT) + subprocess.run([str(binary), 'datafix_world', str(world), str(out), *([str(target)] if target else [])], check=True, + stdout=f, stderr=subprocess.STDOUT) # ---------------------------------------------------------------- comparison @@ -201,7 +202,7 @@ def main(): p.add_argument('versions', nargs='*') 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('--binary', help='a prebuilt horizon-world probe binary') 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() diff --git a/tools/test_decorated_region_parity.py b/tools/test_decorated_region_parity.py index 2716a99e0..71ba5b469 100644 --- a/tools/test_decorated_region_parity.py +++ b/tools/test_decorated_region_parity.py @@ -66,7 +66,7 @@ def build_dir(): def vanilla_order(binary, cx, cz, view): - out = subprocess.run([str(binary), str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, + out = subprocess.run([str(binary), 'chunk_dump', str(cg.RESOURCES), '0', 'overworld'], capture_output=True, text=True, check=True, env=dict(os.environ, HORIZON_LIST_ORDER=f'{cx},{cz},{view}'), cwd=lab.ROOT).stdout return [tuple(map(int, line.split())) for line in out.splitlines()] diff --git a/tools/test_decoration_parity.py b/tools/test_decoration_parity.py index 1b8fa4065..ae8c7ce02 100644 --- a/tools/test_decoration_parity.py +++ b/tools/test_decoration_parity.py @@ -65,7 +65,7 @@ def main(): resources=sort.biome_features(jars['server']) if len(resources)!=67 or resources!=sort.biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDecorationOracle.java';helper=oracle.with_name('VanillaPlacementOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/decoration_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_feature_sort_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/decoration_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -75,10 +75,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,helper],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','decoration_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('decoration_fixture.exe' if os.name=='nt' else 'decoration_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'decoration_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaDecorationOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_decoration_region_parity.py b/tools/test_decoration_region_parity.py index 0b59c4817..c91ab86e8 100644 --- a/tools/test_decoration_region_parity.py +++ b/tools/test_decoration_region_parity.py @@ -55,7 +55,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_feature_region_parity.py",lab.ROOT/"tools/test_decoration_parity.py",lab.ROOT/"tools/test_feature_sort_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/decoration_storage.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/decoration_region_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/decoration_storage.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","decoration_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("decoration_region_fixture.exe" if os.name=="nt" else "decoration_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"decoration_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 07d61f3d5..f45df9822 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -7,7 +7,9 @@ respawn_radius 0) and stops; a vanilla dedicated server and Horizon's server.properties, server-icon.png and lists. VanillaProtocolClient, a headless client made of vanilla's own codecs (any byte vanilla would not read is an error), pings each server, joins it in offline mode through -login, configuration and play, accepts the spawn teleport, receives the +login, configuration and play, accepts the spawn teleport (then, standing +still until its death, sends its position every 20 ticks as LocalPlayer +does: the server checks then which entities it sees), receives the chunks around the spawn (their bytes are compared: the world is loaded from the same files), chats, runs /list and commands that fail (`/random value 7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by @@ -244,6 +246,20 @@ def console_lines(lines): return out +# What a failure's diff doesn't say: warnings, errors, panics and why a player left. +NOTABLE = re.compile(r'/(WARN|ERROR)\]|Exception|panicked|lost connection') + + +def notable_lines(path, limit=20): + """A server's notable lines from its `Done (` on (the startup warnings are every run's), or a client's.""" + try: + lines = path.read_text(encoding='utf-8', errors='replace').splitlines() + except OSError: + return [] + start = next((i for i, l in enumerate(lines) if 'Done (' in l), 0) + return [f'{path.name}: {l[:300]}' for l in lines[start:] if NOTABLE.search(l)][-limit:] + + def server_files(directory): out = [] for name in ['server.properties', 'eula.txt', 'ops.json', 'whitelist.json', 'banned-players.json', 'banned-ips.json', @@ -420,9 +436,13 @@ def main(): (world / 'playerdata').mkdir(exist_ok=True) def client(port, out): - oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, - 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, - out.stem, timeout=300) + try: + oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient', '127.0.0.1', port, PLAYER, out], build, + out.stem, timeout=300) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + log = (build / f'{out.stem}.log').read_text(encoding='utf-8', errors='replace').splitlines() + raise AssertionError(f'{out.stem}: {error}:\n' + '\n'.join(log[-30:])) from None results = {} for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: @@ -448,8 +468,10 @@ def main(): if a != b: differences.append(f'chunk {key}: vanilla {a} horizon {b}') if differences or errors: + notes = [line for name in ('vanilla', 'vanilla-client', 'horizon', 'horizon-client') + for line in notable_lines(build / f'{name}.log')] raise AssertionError(f'{len([d for d in differences if d[:1] in "+-" and d[:3] not in ("+++", "---")])} differing lines ' - f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80])) + f'(see {build}/vanilla.txt and horizon.txt):\n' + '\n'.join(differences[:80] + notes)) lab.write_json(report, dict( schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], diff --git a/tools/test_dynamic_support_parity.py b/tools/test_dynamic_support_parity.py index ac876fa5a..76beb65c8 100644 --- a/tools/test_dynamic_support_parity.py +++ b/tools/test_dynamic_support_parity.py @@ -68,7 +68,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDynamicSupportOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/dynamic_support_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/dynamic_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): if len(states)!=199:raise ValueError('incomplete uncached support registry') fixtures=list(collision_corpus(facts,states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'uncached-states.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','dynamic_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('dynamic_support_fixture.exe' if os.name=='nt' else 'dynamic_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'dynamic_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_edge_backoff_parity.py b/tools/test_edge_backoff_parity.py index 60dd0d66d..58d5ba8dd 100644 --- a/tools/test_edge_backoff_parity.py +++ b/tools/test_edge_backoff_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEdgeBackoffOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/edge_backoff_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/edge_backoff_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEdgeBackoffOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','edge_backoff_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('edge_backoff_fixture.exe' if os.name=='nt' else 'edge_backoff_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'edge_backoff_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_attribute_modifiers_parity.py b/tools/test_effect_attribute_modifiers_parity.py index 0d6a45619..9fd9694aa 100644 --- a/tools/test_effect_attribute_modifiers_parity.py +++ b/tools/test_effect_attribute_modifiers_parity.py @@ -112,7 +112,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectAttributeModifiersOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_attribute_modifiers_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_attribute_modifiers_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -123,10 +123,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectAttributeModifiersOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_attribute_modifiers_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_attribute_modifiers_fixture.exe' if os.name=='nt' else 'effect_attribute_modifiers_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'effect_attribute_modifiers_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_effect_notifications_parity.py b/tools/test_effect_notifications_parity.py index 58f5b2ca6..e39258a8b 100644 --- a/tools/test_effect_notifications_parity.py +++ b/tools/test_effect_notifications_parity.py @@ -65,7 +65,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/effect_notifications_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -76,14 +76,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('effect_notifications_fixture.exe' if os.name=='nt' else 'effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_effect_sync_parity.py b/tools/test_effect_sync_parity.py index ecfd8fe68..5aeeae09b 100644 --- a/tools/test_effect_sync_parity.py +++ b/tools/test_effect_sync_parity.py @@ -101,7 +101,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/effect_sync_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/effect_sync_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -129,16 +129,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'effect_sync_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('effect_sync_fixture.exe' if os.name == 'nt' else 'effect_sync_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'effect_sync_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_enchanting_parity.py b/tools/test_enchanting_parity.py index 4b5c975d0..9f5f5647f 100644 --- a/tools/test_enchanting_parity.py +++ b/tools/test_enchanting_parity.py @@ -42,7 +42,7 @@ def main(): catalog = json.loads((resources / 'items.json').read_text()) items = sorted(k for k, v in catalog.items() if 'minecraft:enchantable' in v) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnchantingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/enchanting_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/enchanting_fixture.rs', *sorted((lab.ROOT / 'crates/horizon-client/src').glob('*.rs'))] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -56,10 +56,10 @@ def main(): with (build / (name + '.log')).open('w', encoding='utf-8') as log: base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'enchanting_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('enchanting_fixture.exe' if os.name == 'nt' else 'enchanting_fixture') - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'enchanting_fixture',resources, inputs, build / 'rust.txt'], 'rust') references = [] for side in ['server']: run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars[side]), deps]), 'dev.horizonlab.parity.VanillaEnchantingOracle', inputs, build / f'{side}.txt'], side) diff --git a/tools/test_entity_attribute_parity.py b/tools/test_entity_attribute_parity.py index b117694d2..045488ee3 100644 --- a/tools/test_entity_attribute_parity.py +++ b/tools/test_entity_attribute_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_attribute_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_attribute_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityAttributeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_attribute_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_attribute_fixture.exe' if os.name=='nt' else 'entity_attribute_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_attribute_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_collision_parity.py b/tools/test_entity_collision_parity.py index b57afa4b6..6fe12a7aa 100644 --- a/tools/test_entity_collision_parity.py +++ b/tools/test_entity_collision_parity.py @@ -54,7 +54,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityCollisionOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_collision_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_collision_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -65,10 +65,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityCollisionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_collision_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_collision_fixture.exe' if os.name=='nt' else 'entity_collision_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_collision_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index 000a2ea6f..b0f77cbfd 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -122,7 +122,7 @@ def main(): tables = resources / 'data/minecraft/loot_table/entities' types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/entity_death_loot_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -139,10 +139,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'entity_death_loot_fixture', resources, inputs, build / 'rust.txt'], 'rust') errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')] if errors: raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index 609a869de..712db03b5 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -68,7 +68,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -79,10 +79,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_fluid_tick_parity.py b/tools/test_entity_fluid_tick_parity.py index f9b4699ce..58380bd03 100644 --- a/tools/test_entity_fluid_tick_parity.py +++ b/tools/test_entity_fluid_tick_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 37c61b4ac..ba54797fa 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -4,7 +4,7 @@ The Java oracle bakes each vanilla model layer, builds the model's own render state class with the generated walk/age/head/attack inputs (plus per-species state fields), runs the real `setupAnim` and writes every part's pose. -`examples/entity_anim_fixture` replays the same inputs through Horizon's +`examples/probe/entity_anim_fixture` replays the same inputs through Horizon's `mobs::anim::setup` and the loaded model tree; the two must agree on every part pose and on the baked polygon count and vertex sums. @@ -364,8 +364,8 @@ def main(): run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle', inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--', - resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'entity_anim_fixture', resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_entity_move_parity.py b/tools/test_entity_move_parity.py index 2f5dc0da1..d17bb2444 100644 --- a/tools/test_entity_move_parity.py +++ b/tools/test_entity_move_parity.py @@ -45,7 +45,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityMoveOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_move_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_move_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -56,10 +56,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityMoveOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_move_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_move_fixture.exe' if os.name=='nt' else 'entity_move_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_move_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_obstruction_parity.py b/tools/test_entity_obstruction_parity.py index 8dc86453d..210c2080f 100644 --- a/tools/test_entity_obstruction_parity.py +++ b/tools/test_entity_obstruction_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityObstructionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/entity_obstruction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/entity_obstruction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaEntityObstructionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','entity_obstruction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('entity_obstruction_fixture.exe' if os.name=='nt' else 'entity_obstruction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'entity_obstruction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_entity_particles_parity.py b/tools/test_entity_particles_parity.py index 2156f97ec..f34528b4c 100644 --- a/tools/test_entity_particles_parity.py +++ b/tools/test_entity_particles_parity.py @@ -74,13 +74,13 @@ def main(): 'tools/test_entity_particles_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(), lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) - harness.run_logged([binary, cases_path, build / 'rust.txt'], build, 'rust') + command = harness.build_probe(build, probe) + harness.run_logged([*command, cases_path, build / 'rust.txt'], build, 'rust') harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') vanilla = (build / 'client.txt').read_text().splitlines() rust = (build / 'rust.txt').read_text().splitlines() diff --git a/tools/test_environment_render_parity.py b/tools/test_environment_render_parity.py index 2e14bb356..893a1c70d 100755 --- a/tools/test_environment_render_parity.py +++ b/tools/test_environment_render_parity.py @@ -5,7 +5,7 @@ The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack (dimension attributes, one biome's attributes, the dimension timelines and the weather layers) and prints every visual/gameplay attribute for a grid of dimensions, world times, rain/thunder levels and biomes. -`examples/environment_fixture` samples the same cases through Horizon's +`examples/probe/environment_fixture` samples the same cases through Horizon's `Environment::sample` + `apply_weather`; every attribute Horizon computes must agree with vanilla. @@ -66,8 +66,8 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'environment_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust), (len(vanilla), len(rust)) diff --git a/tools/test_extra_items_parity.py b/tools/test_extra_items_parity.py index b9b060ee3..83752e515 100644 --- a/tools/test_extra_items_parity.py +++ b/tools/test_extra_items_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaExtraItemsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/extra_items_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/extra_items_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaExtraItemsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','extra_items_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('extra_items_fixture.exe' if os.name=='nt' else 'extra_items_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'extra_items_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_support_parity.py b/tools/test_face_support_parity.py index c82c23453..ad6db8922 100644 --- a/tools/test_face_support_parity.py +++ b/tools/test_face_support_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/face_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/face_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFaceSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','face_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('face_support_fixture.exe' if os.name=='nt' else 'face_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_face_visibility_parity.py b/tools/test_face_visibility_parity.py index c505fd03f..fa8c6696a 100644 --- a/tools/test_face_visibility_parity.py +++ b/tools/test_face_visibility_parity.py @@ -49,7 +49,7 @@ def main(): oracle = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFaceVisibilityOracle.java' helpers = [oracle.with_name(name) for name in ['VanillaCollisionOracle.java','VanillaHeightmapOracle.java']] sources = [oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py', - lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/face_visibility_fixture.rs'] + lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/face_visibility_fixture.rs'] for crate in ['horizon-core','horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -71,10 +71,10 @@ def main(): for a,b in pairs(definitions):output.write(f'{a} {b}\n');pair_count+=1 fixture_paths = [build/name for name in ['pairs.txt','block-registry.nbt','occlusion.nbt','definitions.json','tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','face_visibility_fixture'],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata = json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('face_visibility_fixture.exe' if os.name=='nt' else 'face_visibility_fixture') - run([binary,build],'rust');references=[] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'face_visibility_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side) matched = base.compare(build/(side+'.txt'),build/'rust.txt') diff --git a/tools/test_fall_damage_parity.py b/tools/test_fall_damage_parity.py index 2f080215d..585084eb4 100644 --- a/tools/test_fall_damage_parity.py +++ b/tools/test_fall_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFallDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fall_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fall_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFallDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fall_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fall_damage_fixture.exe' if os.name=='nt' else 'fall_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fall_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_feature_catalog_parity.py b/tools/test_feature_catalog_parity.py index 39a290ed3..52a19a652 100644 --- a/tools/test_feature_catalog_parity.py +++ b/tools/test_feature_catalog_parity.py @@ -85,7 +85,7 @@ def main(): helper=oracle.with_name("VanillaPlacementOracle.java") state_helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,state_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_catalog_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_catalog_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") resources=build/"catalog.json";resources.write_text(json.dumps(catalog(),separators=(",",":")),encoding="utf-8") @@ -100,10 +100,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_catalog_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_catalog_fixture.exe" if os.name=="nt" else "feature_catalog_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_catalog_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_graph_parity.py b/tools/test_feature_graph_parity.py index 876b9bc3c..553baaf09 100644 --- a/tools/test_feature_graph_parity.py +++ b/tools/test_feature_graph_parity.py @@ -69,7 +69,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureGraphOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_graph_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_graph_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -83,10 +83,10 @@ def main(): fixture_paths.append(path) if json.loads((build/"facts-client.json").read_text())!=json.loads((build/"facts-server.json").read_text()):raise ValueError("reference feature block states differ") tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_graph_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_graph_fixture.exe" if os.name=="nt" else "feature_graph_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_graph_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_placement_parity.py b/tools/test_feature_placement_parity.py index 630b593bf..58dc3167a 100644 --- a/tools/test_feature_placement_parity.py +++ b/tools/test_feature_placement_parity.py @@ -79,7 +79,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeaturePlacementOracle.java" helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -87,10 +87,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","feature_placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_placement_fixture.exe" if os.name=="nt" else "feature_placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_feature_region_parity.py b/tools/test_feature_region_parity.py index 901743e1c..2cc8d78a7 100644 --- a/tools/test_feature_region_parity.py +++ b/tools/test_feature_region_parity.py @@ -75,7 +75,7 @@ def main(): placement_helper=oracle.with_name("VanillaPlacementOracle.java") sources=[oracle,helper,placement_helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/feature_region_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/feature_region_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -107,10 +107,10 @@ def main(): height_inputs=build/'heights.json';height_inputs.write_text(json.dumps(heights,separators=(',',':'))) fixture_paths=[height_inputs,zone_inputs,inputs,build/"tags.json",build/"fluid-tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","feature_region_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("feature_region_fixture.exe" if os.name=="nt" else "feature_region_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"feature_region_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_feature_sort_parity.py b/tools/test_feature_sort_parity.py index 9da7f17e4..6c0e4a44e 100644 --- a/tools/test_feature_sort_parity.py +++ b/tools/test_feature_sort_parity.py @@ -54,7 +54,7 @@ def main(): resources=biome_features(jars['server']) if len(resources)!=67 or resources!=biome_features(jars['client']):raise ValueError('pinned biome feature resources differ') oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFeatureSortOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/feature_sort_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/feature_sort_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus(resources));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') resource_path=build/'biome-features.json';resource_path.write_text(json.dumps(resources,separators=(',',':')),encoding='utf-8') @@ -64,10 +64,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','feature_sort_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('feature_sort_fixture.exe' if os.name=='nt' else 'feature_sort_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'feature_sort_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaFeatureSortOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_fill_layer_parity.py b/tools/test_fill_layer_parity.py index 0adf9f6c1..b23521d02 100644 --- a/tools/test_fill_layer_parity.py +++ b/tools/test_fill_layer_parity.py @@ -42,7 +42,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFillLayerOracle.java" helper=oracle.with_name("VanillaBlockStateCodecOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/fill_layer_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/fill_layer_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","fill_layer_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("fill_layer_fixture.exe" if os.name=="nt" else "fill_layer_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"fill_layer_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_finalize_spawn_parity.py b/tools/test_finalize_spawn_parity.py index 7c995fa83..c3130d380 100644 --- a/tools/test_finalize_spawn_parity.py +++ b/tools/test_finalize_spawn_parity.py @@ -118,7 +118,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/finalize_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -148,10 +148,10 @@ def main(): print(f'{len(vanilla)} oracle lines') return halloween = vanilla[0].split()[1] - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'finalize_spawn_fixture', resources, inputs, build / 'rust.txt', halloween], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index b3114c01a..14a4138b5 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -4,7 +4,7 @@ Random rockets (flight durations 0 to 3 and higher, up to six explosions, runs of equal ones) and stars, with dye and custom colours, fade colours, trails and twinkles, some without the component (a rocket's default) and some whose tooltip_display hides it. Vanilla prints what `Fireworks.addToTooltip` and `FireworkExplosion.addToTooltip` add -(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/firework_tooltip_fixture). +(VanillaFireworkTooltipOracle); Horizon what `item_tooltip::firework_lines` gives (examples/probe/firework_tooltip_fixture). """ import random try: diff --git a/tools/test_fluid_box_parity.py b/tools/test_fluid_box_parity.py index 40056ed31..1b4e7743c 100644 --- a/tools/test_fluid_box_parity.py +++ b/tools/test_fluid_box_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidBoxOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_box_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_box_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidBoxOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_box_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_box_fixture.exe' if os.name=='nt' else 'fluid_box_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_box_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_flow_parity.py b/tools/test_fluid_flow_parity.py index b243fa34b..ef1606d91 100644 --- a/tools/test_fluid_flow_parity.py +++ b/tools/test_fluid_flow_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidFlowOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_flow_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_flow_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,10 +67,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidFlowOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_flow_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_flow_fixture.exe' if os.name=='nt' else 'fluid_flow_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_flow_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_occupancy_parity.py b/tools/test_fluid_occupancy_parity.py index 50906f32e..90af340d3 100644 --- a/tools/test_fluid_occupancy_parity.py +++ b/tools/test_fluid_occupancy_parity.py @@ -44,7 +44,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-fluid-occupancy-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaFluidOccupancyOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/fluid_occupancy_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/fluid_occupancy_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) @@ -57,7 +57,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','fluid_occupancy_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('fluid_occupancy_fixture.exe' if os.name=='nt' else 'fluid_occupancy_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'fluid_occupancy_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} fluid-occupancy output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_fluid_parity.py b/tools/test_fluid_parity.py index f8fb98b4e..3acfc3702 100644 --- a/tools/test_fluid_parity.py +++ b/tools/test_fluid_parity.py @@ -46,7 +46,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidOracle.java' helper=oracle.with_name('VanillaBlockStateCodecOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') codec_inputs=build/'codec-inputs.txt';codec_fixtures=list(codec_corpus());codec_inputs.write_text(''.join(json.dumps(v,separators=(',',':'))+'\n' for v in codec_fixtures),encoding='utf-8') fixture_paths=[inputs,codec_inputs,build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_fixture.exe' if os.name=='nt' else 'fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_fluid_shape_parity.py b/tools/test_fluid_shape_parity.py index 55d395ffa..1378d33a5 100644 --- a/tools/test_fluid_shape_parity.py +++ b/tools/test_fluid_shape_parity.py @@ -37,7 +37,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFluidShapeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/fluid_shape_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/fluid_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -48,10 +48,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFluidShapeOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'fluid-states.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'fluid-states.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','fluid_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('fluid_shape_fixture.exe' if os.name=='nt' else 'fluid_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'fluid_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_parity.py b/tools/test_food_parity.py index 519be39e6..c2e451fd0 100644 --- a/tools/test_food_parity.py +++ b/tools/test_food_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_fixture.exe' if os.name=='nt' else 'food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_properties_parity.py b/tools/test_food_properties_parity.py index 195c554ab..950c19ee3 100644 --- a/tools/test_food_properties_parity.py +++ b/tools/test_food_properties_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodPropertiesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_properties_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_properties_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodPropertiesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_properties_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_properties_fixture.exe' if os.name=='nt' else 'food_properties_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_properties_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_food_storage_parity.py b/tools/test_food_storage_parity.py index fc974185c..aeedde587 100644 --- a/tools/test_food_storage_parity.py +++ b/tools/test_food_storage_parity.py @@ -41,7 +41,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFoodStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/food_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/food_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -52,10 +52,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaFoodStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','food_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('food_storage_fixture.exe' if os.name=='nt' else 'food_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'food_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_free_space_parity.py b/tools/test_free_space_parity.py index 19e421265..a81fb0fe7 100644 --- a/tools/test_free_space_parity.py +++ b/tools/test_free_space_parity.py @@ -64,7 +64,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -94,10 +94,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_ghost_recipe_parity.py b/tools/test_ghost_recipe_parity.py index ad722109b..ac902a68c 100644 --- a/tools/test_ghost_recipe_parity.py +++ b/tools/test_ghost_recipe_parity.py @@ -10,7 +10,7 @@ against the real menu for every display of the recipe and prints the GhostSlots it fills: the menu slot, whether it is the result and the stacks the slot cycles through (PlaceRecipeHelper's centred placement of shaped recipes, the first slots for shapeless ones, every fuel for an empty fuel slot); -examples/ghost_recipe_fixture prints the same from +examples/probe/ghost_recipe_fixture prints the same from horizon_client::recipe_book::Book::ghost, which the game fills its ghost slots from. The lines must agree. """ diff --git a/tools/test_ground_support_parity.py b/tools/test_ground_support_parity.py index 931aaa372..4393daf21 100644 --- a/tools/test_ground_support_parity.py +++ b/tools/test_ground_support_parity.py @@ -65,7 +65,7 @@ def main(): sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_block_collision_scan_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] names=['block_collision_scan_fixture','ground_state_fixture'] - sources += [lab.ROOT/'crates/horizon-world/examples'/(name+'.rs') for name in names] + sources += [lab.ROOT/'crates/horizon-world/examples/probe'/(name+'.rs') for name in names] tested=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True);dependencies=os.pathsep.join(map(str,libraries)) def run(command,name): @@ -78,10 +78,10 @@ def main(): for f in corpus():output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 counts[name]=count;fixture_paths.append(path) fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example',names[0],'--example',names[1]],'compile-rust') + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) for group,name in zip(['selection','state'],names): - binary=Path(metadata['target_directory'])/'release/examples'/(name+'.exe' if os.name=='nt' else name);run([binary,build/group],'rust-'+group) + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,name,build/group],'rust-'+group) references=[] for side,jar in jars.items(): results=[] diff --git a/tools/test_height_provider_parity.py b/tools/test_height_provider_parity.py index a14b7f8ca..4f63c80cd 100644 --- a/tools/test_height_provider_parity.py +++ b/tools/test_height_provider_parity.py @@ -65,7 +65,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightProviderOracle.java" helper=oracle.with_name("VanillaAnchorOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/height_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/height_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -73,10 +73,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,helper],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","height_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("height_provider_fixture.exe" if os.name=="nt" else "height_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"height_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_heightmap_parity.py b/tools/test_heightmap_parity.py index 86368997c..502f165ab 100644 --- a/tools/test_heightmap_parity.py +++ b/tools/test_heightmap_parity.py @@ -82,7 +82,7 @@ def main(): oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/heightmap_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/heightmap_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -100,10 +100,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","heightmap_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("heightmap_fixture.exe" if os.name=="nt" else "heightmap_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"heightmap_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py index 842ad3d8a..d2f215050 100644 --- a/tools/test_held_drop_parity.py +++ b/tools/test_held_drop_parity.py @@ -35,7 +35,7 @@ def main(): 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) with (build / 'rust.txt').open('w') as out: subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', - 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) + 'probe', '--', 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Held drop parity passed: {matched} inventory/drop/swing/packet snapshots match vanilla') diff --git a/tools/test_hotbar_parity.py b/tools/test_hotbar_parity.py index 336bda274..b8c83b87c 100644 --- a/tools/test_hotbar_parity.py +++ b/tools/test_hotbar_parity.py @@ -9,7 +9,7 @@ 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 +examples/probe/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine rows' stacks are compared. """ import argparse diff --git a/tools/test_hud_parity.py b/tools/test_hud_parity.py index a0baa3214..4dcd19a7b 100644 --- a/tools/test_hud_parity.py +++ b/tools/test_hud_parity.py @@ -5,7 +5,7 @@ The Java oracle (VanillaHudOracle) runs vanilla's own code on a stand-in client whose player answers from the case, and records every GuiGraphicsExtractor blit (sprite, texture, position, size, region, colour, pose), fill, text call (string, style runs, position, colour, shadow, pose) -and hotbar item (slot, position, seed, pose). `examples/hud_fixture` lays +and hotbar item (slot, position, seed, pose). `examples/probe/hud_fixture` lays out the same state with `horizon_client::hud_layout`, `hud_overlays` and `chat`; the ordered call lists (and any state read back) must agree. @@ -114,8 +114,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaHudOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaHudOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'hud_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'hud_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) diff --git a/tools/test_interaction_shape_parity.py b/tools/test_interaction_shape_parity.py index 6e372fcda..d40ca2c0b 100644 --- a/tools/test_interaction_shape_parity.py +++ b/tools/test_interaction_shape_parity.py @@ -36,7 +36,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionShapeOracle.java' helper=oracle.with_name('VanillaCollisionOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/interaction_shape_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/interaction_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -47,10 +47,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInteractionShapeOracle',mode,path],side+'-'+mode) java('server','export',build);info=json.loads((build/'info.json').read_text());fixtures=list(corpus(info));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'info.json',build/'block-registry.nbt',build/'interaction-shapes.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','interaction_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('interaction_shape_fixture.exe' if os.name=='nt' else 'interaction_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'interaction_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_pickup_parity.py b/tools/test_inventory_pickup_parity.py index 073b56a50..a3172f472 100644 --- a/tools/test_inventory_pickup_parity.py +++ b/tools/test_inventory_pickup_parity.py @@ -61,7 +61,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryPickupOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_pickup_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_pickup_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -72,10 +72,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryPickupOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_pickup_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_pickup_fixture.exe' if os.name=='nt' else 'inventory_pickup_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_pickup_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_tick_parity.py b/tools/test_inventory_tick_parity.py index 02941c7b7..2dd34b76f 100644 --- a/tools/test_inventory_tick_parity.py +++ b/tools/test_inventory_tick_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_tick_fixture.exe' if os.name=='nt' else 'inventory_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_parity.py b/tools/test_inventory_use_parity.py index f4ba01980..925567c3f 100644 --- a/tools/test_inventory_use_parity.py +++ b/tools/test_inventory_use_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_fixture.exe' if os.name=='nt' else 'inventory_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_inventory_use_start_parity.py b/tools/test_inventory_use_start_parity.py index 9de828505..67e282c06 100644 --- a/tools/test_inventory_use_start_parity.py +++ b/tools/test_inventory_use_start_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInventoryUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/inventory_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/inventory_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaInventoryUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','inventory_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('inventory_use_start_fixture.exe' if os.name=='nt' else 'inventory_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'inventory_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_after_use_parity.py b/tools/test_item_after_use_parity.py index 9073cdee7..4aa5258f9 100644 --- a/tools/test_item_after_use_parity.py +++ b/tools/test_item_after_use_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemAfterUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_after_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_after_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemAfterUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_after_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_after_use_fixture.exe' if os.name=='nt' else 'item_after_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_after_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_blocking_parity.py b/tools/test_item_blocking_parity.py index f72fd6977..08d8dce24 100644 --- a/tools/test_item_blocking_parity.py +++ b/tools/test_item_blocking_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemBlockingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_blocking_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_blocking_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemBlockingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_blocking_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_blocking_fixture.exe' if os.name=='nt' else 'item_blocking_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_blocking_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_cooldowns_parity.py b/tools/test_item_cooldowns_parity.py index 003394f88..807c576dc 100644 --- a/tools/test_item_cooldowns_parity.py +++ b/tools/test_item_cooldowns_parity.py @@ -53,7 +53,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemCooldownsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_cooldowns_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_cooldowns_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -64,10 +64,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemCooldownsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_cooldowns_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_cooldowns_fixture.exe' if os.name=='nt' else 'item_cooldowns_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_cooldowns_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_durability_parity.py b/tools/test_item_durability_parity.py index 92b34c9e6..e3cdebb07 100644 --- a/tools/test_item_durability_parity.py +++ b/tools/test_item_durability_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemDurabilityOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_durability_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_durability_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemDurabilityOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_durability_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_durability_fixture.exe' if os.name=='nt' else 'item_durability_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_durability_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_particles_parity.py b/tools/test_item_particles_parity.py index eb11f85da..0e030a3b3 100644 --- a/tools/test_item_particles_parity.py +++ b/tools/test_item_particles_parity.py @@ -42,7 +42,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemParticlesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_particles_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_particles_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -53,10 +53,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemParticlesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_particles_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_particles_fixture.exe' if os.name=='nt' else 'item_particles_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_particles_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_stack_storage_parity.py b/tools/test_item_stack_storage_parity.py index 5f41b968e..953dc8300 100644 --- a/tools/test_item_stack_storage_parity.py +++ b/tools/test_item_stack_storage_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemStackStorageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_stack_storage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_stack_storage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemStackStorageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_stack_storage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_stack_storage_fixture.exe' if os.name=='nt' else 'item_stack_storage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_stack_storage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_template_parity.py b/tools/test_item_template_parity.py index 1e01cef69..837465bb3 100644 --- a/tools/test_item_template_parity.py +++ b/tools/test_item_template_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemTemplateOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_template_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_template_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemTemplateOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_template_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_template_fixture.exe' if os.name=='nt' else 'item_template_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_template_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_catalog_parity.py b/tools/test_item_use_catalog_parity.py index ca83e3c26..38664bd03 100644 --- a/tools/test_item_use_catalog_parity.py +++ b/tools/test_item_use_catalog_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseCatalogOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_catalog_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_catalog_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if exports[0]!=exports[1]:raise RuntimeError('native item catalogs differ') catalog_path=build/'catalog.json';lab.write_json(catalog_path,exports[0]);fixtures=list(corpus(exports[0]));inputs=build/'inputs.txt' ;inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,catalog_path];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_catalog_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_catalog_fixture.exe' if os.name=='nt' else 'item_use_catalog_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_catalog_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_lifecycle_parity.py b/tools/test_item_use_lifecycle_parity.py index f0615c64c..0c3c4ee6e 100644 --- a/tools/test_item_use_lifecycle_parity.py +++ b/tools/test_item_use_lifecycle_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseLifecycleOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_lifecycle_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_lifecycle_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseLifecycleOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_lifecycle_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_lifecycle_fixture.exe' if os.name=='nt' else 'item_use_lifecycle_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_lifecycle_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_parity.py b/tools/test_item_use_parity.py index 9460ffb83..f69d49e35 100644 --- a/tools/test_item_use_parity.py +++ b/tools/test_item_use_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_fixture.exe' if os.name=='nt' else 'item_use_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_item_use_start_parity.py b/tools/test_item_use_start_parity.py index 6325fc5a6..e59945e82 100644 --- a/tools/test_item_use_start_parity.py +++ b/tools/test_item_use_start_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaItemUseStartOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/item_use_start_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/item_use_start_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaItemUseStartOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','item_use_start_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('item_use_start_fixture.exe' if os.name=='nt' else 'item_use_start_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'item_use_start_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_hash_map_parity.py b/tools/test_java_hash_map_parity.py index c51404aa8..5ae1cce41 100644 --- a/tools/test_java_hash_map_parity.py +++ b/tools/test_java_hash_map_parity.py @@ -62,7 +62,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaHashMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_hash_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_hash_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaHashMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_hash_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_hash_map_fixture.exe' if os.name=='nt' else 'java_hash_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'java_hash_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_java_identity_map_parity.py b/tools/test_java_identity_map_parity.py index c104eafcc..9e9f04c1d 100644 --- a/tools/test_java_identity_map_parity.py +++ b/tools/test_java_identity_map_parity.py @@ -56,7 +56,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaJavaIdentityMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/java_identity_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/java_identity_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -67,14 +67,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaJavaIdentityMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','java_identity_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('java_identity_map_fixture.exe' if os.name=='nt' else 'java_identity_map_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'java_identity_map_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_level_place_parity.py b/tools/test_level_place_parity.py index 23a68800c..18e90e348 100644 --- a/tools/test_level_place_parity.py +++ b/tools/test_level_place_parity.py @@ -105,8 +105,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockPlacementOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_place_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_place_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_level_shape_parity.py b/tools/test_level_shape_parity.py index 212284656..c86f51fe6 100644 --- a/tools/test_level_shape_parity.py +++ b/tools/test_level_shape_parity.py @@ -80,8 +80,8 @@ def main(): subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaLevelShapeOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')], check=True) - subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'level_shape_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) + subprocess.run(['cargo', 'run', '-q', '-j2', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'level_shape_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], check=True, cwd=lab.ROOT) native = (work / 'native.txt').read_text().splitlines() rust = (work / 'rust.txt').read_text().splitlines() differences = {} diff --git a/tools/test_light_parity.py b/tools/test_light_parity.py index ad3945ba8..3ed2351fa 100755 --- a/tools/test_light_parity.py +++ b/tools/test_light_parity.py @@ -4,7 +4,7 @@ Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass, leaves, water and glowstone in a fresh vanilla world, lets the vanilla light engine settle, stops the server so the SkyLight/BlockLight arrays are saved, -then relights every saved chunk with `examples/light_parity` and requires every +then relights every saved chunk with `examples/probe/light_parity` and requires every value to agree. The example also replays block edits through the incremental `light::relight` and checks them against a full relight. @@ -92,7 +92,7 @@ def main(): dimension = run / 'world' for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']): status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', - '--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra], + '--example', 'probe', '--', 'light_parity', str(RESOURCES), str(dimension), *extra], cwd=ROOT).returncode if status: sys.exit('light mismatch against vanilla') diff --git a/tools/test_liquid_collision_parity.py b/tools/test_liquid_collision_parity.py index 9989da2e7..6a4ca638b 100644 --- a/tools/test_liquid_collision_parity.py +++ b/tools/test_liquid_collision_parity.py @@ -59,7 +59,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_live_attribute_updates_parity.py b/tools/test_live_attribute_updates_parity.py index cd619de72..1e05f4bae 100644 --- a/tools/test_live_attribute_updates_parity.py +++ b/tools/test_live_attribute_updates_parity.py @@ -131,8 +131,8 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attribute_updates_fixture.rs', - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attribute_updates_fixture.rs', + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -160,16 +160,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attribute_updates_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attribute_updates_fixture.exe' if os.name == 'nt' else 'live_attribute_updates_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attribute_updates_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_live_attributes_parity.py b/tools/test_live_attributes_parity.py index 74bd083f2..f221fa27e 100644 --- a/tools/test_live_attributes_parity.py +++ b/tools/test_live_attributes_parity.py @@ -104,7 +104,7 @@ def main(): lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), - lab.ROOT / 'crates/horizon-world/examples/live_attributes_fixture.rs'] + lab.ROOT / 'crates/horizon-world/examples/probe/live_attributes_fixture.rs'] tested_sources = base.source_hashes(sources) classes = build / 'classes' classes.mkdir(exist_ok=True) @@ -132,16 +132,16 @@ def main(): inputs.write_text(''.join(json.dumps(row, separators=(',', ':')) + '\n' for row in fixtures), encoding='utf-8') fixture_paths = [inputs, build / 'catalog.json', build / 'catalog-client.json', build / 'catalog-server.json'] tested_fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'live_attributes_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('live_attributes_fixture.exe' if os.name == 'nt' else 'live_attributes_fixture') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') references = [] for side, jar in jars.items(): java(side, side) enriched = build / f'inputs-{side}.txt' fixture_paths.append(enriched) tested_fixtures.update(base.source_hashes([enriched])) - run([binary, build, side], 'rust-' + side) + run([binary, 'live_attributes_fixture', build, side], 'rust-' + side) reference = build / f'{side}.txt' candidate = build / f'rust-{side}.txt' matched = base.compare(reference, candidate) diff --git a/tools/test_living_air_parity.py b/tools/test_living_air_parity.py index 85da124e3..4d837f02a 100644 --- a/tools/test_living_air_parity.py +++ b/tools/test_living_air_parity.py @@ -70,7 +70,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingAirOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_air_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_air_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -81,10 +81,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingAirOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_air_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_air_fixture.exe' if os.name=='nt' else 'living_air_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_air_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_damage_parity.py b/tools/test_living_damage_parity.py index 43c45c926..ae97c4686 100644 --- a/tools/test_living_damage_parity.py +++ b/tools/test_living_damage_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingDamageOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_damage_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingDamageOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_damage_fixture.exe' if os.name=='nt' else 'living_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fall_parity.py b/tools/test_living_fall_parity.py index db79c440f..db55b5728 100644 --- a/tools/test_living_fall_parity.py +++ b/tools/test_living_fall_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFallOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fall_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fall_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFallOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fall_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fall_fixture.exe' if os.name=='nt' else 'living_fall_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fall_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_fluid_parity.py b/tools/test_living_fluid_parity.py index f50289e04..19748fef2 100644 --- a/tools/test_living_fluid_parity.py +++ b/tools/test_living_fluid_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingFluidOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_fluid_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_fluid_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingFluidOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_fluid_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_fluid_fixture.exe' if os.name=='nt' else 'living_fluid_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_health_parity.py b/tools/test_living_health_parity.py index b58f3e357..ab97d0061 100644 --- a/tools/test_living_health_parity.py +++ b/tools/test_living_health_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHealthOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_health_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHealthOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_health_fixture.exe' if os.name=='nt' else 'living_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_hurt_parity.py b/tools/test_living_hurt_parity.py index 4e7d951b8..38ade5720 100644 --- a/tools/test_living_hurt_parity.py +++ b/tools/test_living_hurt_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_hurt_fixture.exe' if os.name=='nt' else 'living_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_landing_parity.py b/tools/test_living_landing_parity.py index 84e6c705d..eb65800da 100644 --- a/tools/test_living_landing_parity.py +++ b/tools/test_living_landing_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingLandingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_landing_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_landing_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingLandingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_landing_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_landing_fixture.exe' if os.name=='nt' else 'living_landing_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_landing_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_living_motion_parity.py b/tools/test_living_motion_parity.py index 66190f812..39935303c 100644 --- a/tools/test_living_motion_parity.py +++ b/tools/test_living_motion_parity.py @@ -69,7 +69,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLivingMotionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/living_motion_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/living_motion_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -80,10 +80,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaLivingMotionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','living_motion_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('living_motion_fixture.exe' if os.name=='nt' else 'living_motion_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'living_motion_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_local_input_parity.py b/tools/test_local_input_parity.py index 2873f11a7..adfea1a4b 100644 --- a/tools/test_local_input_parity.py +++ b/tools/test_local_input_parity.py @@ -35,7 +35,7 @@ def main(): build=lab.LOCAL/'rust-local-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLocalInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/input_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/input_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -44,10 +44,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','input_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('input_probe.exe' if os.name=='nt' else 'input_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'input_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaLocalInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_material_condition_parity.py b/tools/test_material_condition_parity.py index 43e0fa48b..adddd336b 100644 --- a/tools/test_material_condition_parity.py +++ b/tools/test_material_condition_parity.py @@ -285,7 +285,7 @@ def main(): anchor_oracle=oracle.with_name("VanillaAnchorOracle.java") biome_oracle=oracle.with_name("VanillaBiomeTemperatureOracle.java") sources=[oracle,anchor_oracle,biome_oracle,lab.ROOT/"tools/test_biome_temperature_parity.py",Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_condition_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_condition_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=[*corpus(),*codec_corpus(conditions),*rule_corpus(conditions),*noise_corpus(noises),*biome_corpus(biomes),*biome_tag_corpus(biomes,biome_tags),*preliminary_corpus(),*ore_corpus()];inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json",build/"conditions.json",build/"biomes.json",build/"biome_tags.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -293,10 +293,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle,anchor_oracle,biome_oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_condition_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_condition_fixture.exe" if os.name=="nt" else "material_condition_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_condition_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_material_extension_parity.py b/tools/test_material_extension_parity.py index 7ce03502c..4036ecc37 100644 --- a/tools/test_material_extension_parity.py +++ b/tools/test_material_extension_parity.py @@ -60,15 +60,15 @@ def main(): if not biomes or biomes!=biome.biome_resources(jars['client']):raise ValueError('reference biome resources differ') for name,data in [('noises',noises),('biomes',biomes)]:(build/(name+'.json')).write_text(json.dumps(data,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialExtensionOracle','VanillaBiomeTemperatureOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_extension_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_extension_fixture.rs'] tested_sources=base.source_hashes(sources);fixtures=list(corpus(biomes));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'noises.json',build/'biomes.json'];tested_fixtures=base.source_hashes(fixture_paths);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,*oracles],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','material_extension_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_extension_fixture.exe' if os.name=='nt' else 'material_extension_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_extension_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaMaterialExtensionOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt');references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-extension output lines match Rust',flush=True) diff --git a/tools/test_material_rule_library_parity.py b/tools/test_material_rule_library_parity.py index d2e7023ae..1e9b82357 100644 --- a/tools/test_material_rule_library_parity.py +++ b/tools/test_material_rule_library_parity.py @@ -67,7 +67,7 @@ def main(): for field,value in bundle.items():(build/(field+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' oracles=[folder/(name+'.java') for name in ['VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_condition_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_condition_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -79,9 +79,9 @@ def main(): if facts!=json.loads((build/'facts-client.json').read_text()):raise ValueError('reference block metadata differs') fixtures=list(corpus(bundle['rules'],bundle['biomes']));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts-client.json',build/'facts-server.json',*[build/(field+'.json') for field in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_condition_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_condition_fixture.exe' if os.name=='nt' else 'material_condition_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'material_condition_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,'VanillaMaterialConditionOracle',side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched});print(f'{side}: {matched:,} material-rule library output lines match Rust',flush=True) diff --git a/tools/test_material_stage_parity.py b/tools/test_material_stage_parity.py index 29de0d9e0..46bb4649b 100644 --- a/tools/test_material_stage_parity.py +++ b/tools/test_material_stage_parity.py @@ -110,7 +110,7 @@ def main(): counts={key:len(value) for key,value in bundle.items()};bundle['rules'].update(synthetic_rules()) for name,value in bundle.items():(build/(name+'.json')).write_text(json.dumps(value,separators=(',',':')),encoding='utf-8') folder=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[folder/(name+'.java') for name in ['VanillaMaterialStageOracle','VanillaMaterialConditionOracle','VanillaAnchorOracle','VanillaBiomeTemperatureOracle','VanillaHeightmapOracle','VanillaBiomeExport']] - sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/material_stage_fixture.rs'] + sources=[*oracles,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_material_condition_parity.py','test_biome_temperature_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/material_stage_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) @@ -132,7 +132,7 @@ def main(): f['top_queries']=top_queries(f);f['carving']=carving_fixture(f,facts) inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs,*preset_exports,build/'facts-client.json',build/'facts-server.json',*[build/(name+'.json') for name in bundle]];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','material_stage_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('material_stage_fixture.exe' if os.name=='nt' else 'material_stage_fixture');run([binary,build],'rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'material_stage_fixture',build],'rust') with (build/'rust.txt').open() as stream: if any((line.startswith('surface ') or line.startswith('top ') or line.startswith('carving ') or line.startswith('generatedcarving ')) and line.endswith(' error\n') for line in stream):raise AssertionError('valid surface fixture failed; inspect private Rust log') references=[] diff --git a/tools/test_material_surface_parity.py b/tools/test_material_surface_parity.py index 30df0f4da..120decbe7 100644 --- a/tools/test_material_surface_parity.py +++ b/tools/test_material_surface_parity.py @@ -44,7 +44,7 @@ def main(): (build/"noises.json").write_text(json.dumps(noises,separators=(",",":")),encoding="utf-8") oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMaterialSurfaceOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/material_surface_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/material_surface_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs,build/"noises.json"];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -52,10 +52,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","material_surface_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("material_surface_fixture.exe" if os.name=="nt" else "material_surface_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"material_surface_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 4e34b39cc..e1998e579 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -22,8 +22,10 @@ results, and the scaled and locked copies a take makes), the lectern (over the block entity: its page buttons, clamped to the book's pages, and Take Book, with the inventory compared too) and the server's furnace menus over their block entities (`*_be`: a new input restarts -cooking, other clicks keep its progress). After -every click the slots, carried stack, data slots and drops are compared. +cooking, other clicks keep its progress). Bundles (empty, partly and fully +loaded, nested) are among the stacks and often in hand, for BundleItem's click +overrides. After every click the slots, carried stack, data slots, drops and +the player's sounds are compared. """ import argparse import json @@ -37,6 +39,8 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'cartography': 39, 'lectern': 1, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} +# Where a carried bundle is common: the containers that hold anything. +BUNDLE_MENUS = {'inventory', 'chest1', 'chest3', 'shulker', 'hopper', 'dispenser'} DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'lectern': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} @@ -91,8 +95,10 @@ def snbt(item, count, damage=0, curse=False, potion=None): class Gen: - def __init__(self, rng, items): + def __init__(self, rng, items, bundles=None): self.rng = rng + # Bundles come from their own generator, so the other stacks stay as they were. + self.bundles = bundles or random.Random(0) self.items = items self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items] self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k @@ -108,7 +114,37 @@ class Gen: damage = rng.randrange(1, info['minecraft:max_damage']) count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)]) potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None - return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + stack = snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion) + return self.bundle() if self.bundles.random() < 0.06 else stack + + def bundle(self, room=64): + """A bundle, empty or holding up to its weight (in 64ths: 1 per item of a + 64-stack, 4 of a 16-stack, 64 of a tool), now and then another bundle.""" + return self.loaded_bundle(room)[0] + + def loaded_bundle(self, room): + rng = self.bundles + color = rng.choice(['', '', 'red_', 'light_blue_']) + inside, used = [], 0 + for _ in range(rng.choice([0, 0, 1, 1, 2, 3, 5])): + if room == 64 and rng.random() < 0.1: + # A nested bundle weighs its contents plus 1/16. + if room - used > 4: + nested, weight = self.loaded_bundle(min(room - used - 4, 16)) + inside.append(nested) + used += weight + 4 + continue + item = rng.choice(self.pool) + top = self.items[item].get('minecraft:max_stack_size', 64) + unit = 64 // top + if unit > room - used or 'shulker_box' in item: + continue + most = min(top, (room - used) // unit) + count = min(most, rng.choice([1, 1, 2, rng.randrange(1, most + 1)])) + used += count * unit + inside.append(snbt(item, count)) + body = ',components:{"minecraft:bundle_contents":[%s]}' % ','.join(inside) if inside else '' + return '{id:"minecraft:%sbundle",count:1%s}' % (color, body), used def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] @@ -333,7 +369,7 @@ def main(): vanilla.compile('ParityData', 'VanillaMenuOracle') items = json.loads((lib.RESOURCES / 'items.json').read_text()) rng = random.Random(args.seed) - g = Gen(rng, items) + g = Gen(rng, items, random.Random(args.seed + 1)) cases = [] chosen = args.menus.split(',') if args.menus else list(MENUS) for n in range(args.cases): @@ -442,6 +478,9 @@ def main(): 'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' if carried_food is not None: carried = carried_food + elif menu in BUNDLE_MENUS and g.bundles.random() < 0.3: + # A bundle in hand, emptied into slots and filled from them. + carried = g.bundle() if menu == 'lectern': carried = '-' extra = {} diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 01ed4680f..07f41b2af 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -467,7 +467,7 @@ def main(): 'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world], build, 'vanilla', timeout=3600) if not args.java_only: - command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'] + command = ['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'probe'] target, env = lab.cargo_target(), None if args.trace: target = lab.LOCAL / 'mob-ai-trace-target' @@ -475,8 +475,8 @@ def main(): env = dict(os.environ, CARGO_TARGET_DIR=str(target), CARGO_PROFILE_RELEASE_DEBUG='line-tables-only', CARGO_PROFILE_RELEASE_LTO='false', CARGO_PROFILE_RELEASE_CODEGEN_UNITS='16') oracle_harness.run_logged(command, build, 'compile-rust', env=env) - binary = target / 'release/examples/mob_ai_probe' - oracle_harness.run_logged([binary, lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') + binary = target / 'release/examples/probe' + oracle_harness.run_logged([binary, 'mob_ai_probe', lab.RESOURCES, inputs, build / 'horizon.txt'], build, 'horizon') if args.java_only: return names = {s[0] for _, s in chosen} diff --git a/tools/test_mob_attributes_parity.py b/tools/test_mob_attributes_parity.py index 1e4057eb7..6cefdc4b8 100755 --- a/tools/test_mob_attributes_parity.py +++ b/tools/test_mob_attributes_parity.py @@ -62,10 +62,10 @@ def main(): subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'mob_attributes_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/mob_attributes_fixture' + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' resources = lab.RESOURCES - run([binary, resources, build / 'rust.txt'], 'rust') + run([binary, 'mob_attributes_fixture', resources, build / 'rust.txt'], 'rust') vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt') problems = [] living = [i for i, r in vanilla.items() if 'attrs' in r] diff --git a/tools/test_movement_emission_parity.py b/tools/test_movement_emission_parity.py index 14977b45b..7db2c16d0 100644 --- a/tools/test_movement_emission_parity.py +++ b/tools/test_movement_emission_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementEmissionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_emission_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_emission_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementEmissionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_emission_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_emission_fixture.exe' if os.name=='nt' else 'movement_emission_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_emission_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_movement_registry_parity.py b/tools/test_movement_registry_parity.py index ef1542415..190c34d37 100644 --- a/tools/test_movement_registry_parity.py +++ b/tools/test_movement_registry_parity.py @@ -40,7 +40,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/movement_registry_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/movement_registry_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -69,10 +69,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'registry-info.json', 'movement-properties.nbt', 'block-registry.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'movement_registry_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('movement_registry_fixture.exe' if os.name=='nt' else 'movement_registry_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'movement_registry_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_movement_support_parity.py b/tools/test_movement_support_parity.py index dbc727c76..793804a9e 100644 --- a/tools/test_movement_support_parity.py +++ b/tools/test_movement_support_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMovementSupportOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/movement_support_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/movement_support_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaMovementSupportOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','movement_support_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('movement_support_fixture.exe' if os.name=='nt' else 'movement_support_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'movement_support_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_music_parity.py b/tools/test_music_parity.py index 7d41be5f1..b56c9ab25 100644 --- a/tools/test_music_parity.py +++ b/tools/test_music_parity.py @@ -154,7 +154,7 @@ def main(): 'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines), extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java', h.lab.ROOT / 'crates/horizon-client/src/music.rs', - h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'], + h.lab.ROOT / 'crates/horizon-client/examples/probe/audio_common/mod.rs'], java_args=[h.RESOURCES], rust_args=[h.RESOURCES], scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded ' 'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading ' diff --git a/tools/test_native_scene_collision.py b/tools/test_native_scene_collision.py index a70cf48fb..8efc6946b 100644 --- a/tools/test_native_scene_collision.py +++ b/tools/test_native_scene_collision.py @@ -70,7 +70,7 @@ def main(): sources = [Path(__file__), lab.ROOT/'tools/test_native_client.py', lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py', oracle, *helpers, lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_collision_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_collision_probe.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -82,16 +82,16 @@ def main(): dependencies = os.pathsep.join(map(str, libraries)) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server'])+os.pathsep+dependencies, '-d', classes, oracle, *helpers], 'compile-java') - run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'scene_collision_probe'], 'compile-rust') + run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - executable = Path(metadata['target_directory'])/'debug/examples'/('scene_collision_probe.exe' if os.name == 'nt' else 'scene_collision_probe') + executable = Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') cases = [] for radius in [1, 2]: build = root/str(radius); build.mkdir(exist_ok=True) fixtures = list(corpus(radius)) (build/'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':'))+'\n' for f in fixtures)) input_hash = lab.digest(build/'inputs.txt', 'sha256') - run([executable, resources, build, radius], f'rust-{radius}') + run([executable, 'scene_collision_probe',resources, build, radius], f'rust-{radius}') scene_hash = lab.digest(build/'scene.json', 'sha256') references = [] for side, jar in jars.items(): diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 4b8089795..a917d7337 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -789,7 +789,7 @@ def main(): if args.sprint_input:helpers.append(oracle.with_name('VanillaSprintInputOracle.java')) sources=[Path(__file__),lab.ROOT/'tools/test_native_client.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py', lab.ROOT/'tools/prepare_native_client.py',oracle,*helpers,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-client/examples/scene_motion_probe.rs'] + lab.ROOT/'crates/horizon-client/examples/probe/scene_motion_probe.rs'] for crate in ['horizon-core','horizon-world','horizon-assets','horizon-client']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] if args.sprint_input:sources.append(lab.ROOT/'tools/test_model_baking_parity.py') @@ -807,16 +807,16 @@ def main(): damage_dir=build/'damage';damage_dir.mkdir(exist_ok=True) for target, source in [('types.json','damage-types.json'),('tags.json','damage-tags.json')]: (damage_dir/target).write_bytes((resources/source).read_bytes()) - run(['cargo','build','--locked','-p','horizon-client','--example','scene_motion_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('scene_motion_probe.exe' if os.name=='nt' else 'scene_motion_probe') - run([binary,resources,build,'--describe'],'describe') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'scene_motion_probe',resources,build,'--describe'],'describe') references=[] for side,jar in jars.items(): run(['java','-Xmx768M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]), 'dev.horizonlab.parity.VanillaSceneMotionOracle',side,build,resources],side) replay_hash=lab.digest(build/('inputs-'+side+'.txt'),'sha256') - run([binary,resources,build,side],'rust-'+side) + run([binary,'scene_motion_probe',resources,build,side],'rust-'+side) if replay_hash!=lab.digest(build/('inputs-'+side+'.txt'),'sha256'):raise AssertionError('Identity replay changed') matched=base.compare(build/(side+'.txt'),build/('rust-'+side+'.txt')) if matched!=expected_lines:raise AssertionError('Incomplete motion output') diff --git a/tools/test_natural_spawn_parity.py b/tools/test_natural_spawn_parity.py index fabdc184b..3c95e6ac2 100644 --- a/tools/test_natural_spawn_parity.py +++ b/tools/test_natural_spawn_parity.py @@ -550,7 +550,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) @@ -568,10 +568,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_nether_portal_parity.py b/tools/test_nether_portal_parity.py index 08e707e90..71cbf7be8 100644 --- a/tools/test_nether_portal_parity.py +++ b/tools/test_nether_portal_parity.py @@ -145,8 +145,8 @@ def main(): '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaPortalOracle.java')]) h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle', str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) - h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'portal_travel_fixture', '--', - str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) + h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'probe', '--', + 'portal_travel_fixture', str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) native = h.split_cases((work / 'native.txt').read_text(), ()) rust = h.split_cases((work / 'rust.txt').read_text(), ()) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) diff --git a/tools/test_object_open_map_parity.py b/tools/test_object_open_map_parity.py index 0a4633b3d..72bafc1a4 100644 --- a/tools/test_object_open_map_parity.py +++ b/tools/test_object_open_map_parity.py @@ -117,7 +117,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenMapOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_map_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_map_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -128,10 +128,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenMapOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_map_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_map_fixture.exe' if os.name=='nt' else 'object_open_map_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_map_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_object_open_set_parity.py b/tools/test_object_open_set_parity.py index cdbe43a15..3801cdb60 100644 --- a/tools/test_object_open_set_parity.py +++ b/tools/test_object_open_set_parity.py @@ -66,7 +66,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaObjectOpenSetOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/object_open_set_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/object_open_set_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,10 +77,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaObjectOpenSetOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','object_open_set_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('object_open_set_fixture.exe' if os.name=='nt' else 'object_open_set_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'object_open_set_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_pack_screen_parity.py b/tools/test_pack_screen_parity.py index a73f734fe..1f3f03ede 100644 --- a/tools/test_pack_screen_parity.py +++ b/tools/test_pack_screen_parity.py @@ -14,7 +14,7 @@ records every GuiGraphicsExtractor call of the screen shown at the end (widgets, list backgrounds, scissor, separators, scroll bars, entries with their incompatibility tint, hover overlay and arrows, the selection outline, the search box, the buttons and their tooltip); -examples/pack_screen_fixture runs horizon_client::pack_screen, which the +examples/probe/pack_screen_fixture runs horizon_client::pack_screen, which the game's pack screen is, through the same actions. The call lists must agree. test_pack_screen_parity.py [--count N] [--detail N] diff --git a/tools/test_pack_selection_parity.py b/tools/test_pack_selection_parity.py index 8610d85f3..9af372d1e 100644 --- a/tools/test_pack_selection_parity.py +++ b/tools/test_pack_selection_parity.py @@ -7,7 +7,7 @@ initial selection as options.txt stores it, and the actions the screen's entries take on a click or key press: select (an incompatible pack only when its confirmation is accepted), unselect, move up, move down. The Java oracle (VanillaPackSelectionOracle) runs vanilla's PackRepository and -PackSelectionModel; examples/pack_selection_fixture runs +PackSelectionModel; examples/probe/pack_selection_fixture runs horizon_client::packs::SelectionModel, which the game's pack screen uses. After every action both lists, in order, with each entry's canSelect, canUnselect, canMoveUp and canMoveDown, and the selection committed at the @@ -71,8 +71,8 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaPackSelectionOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackSelectionOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'pack_selection_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'pack_selection_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index 2fdd510d9..def7e3bfa 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -197,14 +197,14 @@ def main(): 'tools/test_particle_providers_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py', f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock', 'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs', - f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']] + f'crates/horizon-client/examples/probe/{probe}.rs', 'crates/horizon-core/src/random.rs']] tested = base.source_hashes(sources) cases_path, units = make_cases(build) classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major']) - binary = harness.build_probe(build, probe) + command = harness.build_probe(build, probe) # The oracle runs first: the probe replays the particle seeds it recovered. harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client') - harness.run_logged([binary, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') + harness.run_logged([*command, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust') tolerance = 0 try: matched = base.compare(build / 'client.txt', build / 'rust.txt') diff --git a/tools/test_piston_movement_parity.py b/tools/test_piston_movement_parity.py index 9b580c1ee..82bcd09ca 100644 --- a/tools/test_piston_movement_parity.py +++ b/tools/test_piston_movement_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonMovementOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_movement_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_movement_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPistonMovementOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_movement_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_movement_fixture.exe' if os.name=='nt' else 'piston_movement_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_movement_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_piston_shape_parity.py b/tools/test_piston_shape_parity.py index 0816b3f8b..74ae48e39 100644 --- a/tools/test_piston_shape_parity.py +++ b/tools/test_piston_shape_parity.py @@ -49,7 +49,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonShapeOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaFaceSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/piston_shape_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/piston_shape_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -63,10 +63,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned registry') fixtures=list(corpus(facts));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'facts.json',build/'block-registry.nbt',build/'cached-collision.nbt'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','piston_shape_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('piston_shape_fixture.exe' if os.name=='nt' else 'piston_shape_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'piston_shape_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_place_recipe_parity.py b/tools/test_place_recipe_parity.py index 405ad8009..0b4bdf08e 100644 --- a/tools/test_place_recipe_parity.py +++ b/tools/test_place_recipe_parity.py @@ -9,7 +9,7 @@ renamed copies the book must not use, junk, and sometimes a nearly full inventory; the grid is empty, holds the same recipe already (placing again adds one set, or a full stack with shift) or something else. The Java oracle (VanillaPlaceRecipeOracle) runs RecipeBookMenu.handlePlacement as the server's -packet handler does; examples/place_recipe_fixture runs +packet handler does; examples/probe/place_recipe_fixture runs horizon_client::menu's place_recipe. Every menu slot, the whole inventory, the drops and whether the client gets a ghost recipe are compared. diff --git a/tools/test_placement_parity.py b/tools/test_placement_parity.py index 8ac2f9247..d4e84eaf8 100644 --- a/tools/test_placement_parity.py +++ b/tools/test_placement_parity.py @@ -100,7 +100,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlacementOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/support/placement_queries.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/placement_fixture.rs",lab.ROOT/"crates/horizon-world/examples/probe/support/placement_queries.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -108,10 +108,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","placement_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("placement_fixture.exe" if os.name=="nt" else "placement_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"placement_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_player_equipment_parity.py b/tools/test_player_equipment_parity.py index dd54b4c24..5f2499eab 100644 --- a/tools/test_player_equipment_parity.py +++ b/tools/test_player_equipment_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerEquipmentOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_equipment_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_equipment_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerEquipmentOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_equipment_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_equipment_fixture.exe' if os.name=='nt' else 'player_equipment_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_equipment_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_food_parity.py b/tools/test_player_food_parity.py index 5f8bf6784..ff38abe39 100644 --- a/tools/test_player_food_parity.py +++ b/tools/test_player_food_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerFoodOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_food_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_food_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerFoodOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_food_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_food_fixture.exe' if os.name=='nt' else 'player_food_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_food_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_health_parity.py b/tools/test_player_health_parity.py index 40d6d2e5e..256ffdf46 100644 --- a/tools/test_player_health_parity.py +++ b/tools/test_player_health_parity.py @@ -47,7 +47,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_health_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_health_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHealthOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_health_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_health_fixture.exe' if os.name=='nt' else 'player_health_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_health_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_hurt_parity.py b/tools/test_player_hurt_parity.py index abc429a0c..34ce6a9dd 100644 --- a/tools/test_player_hurt_parity.py +++ b/tools/test_player_hurt_parity.py @@ -71,7 +71,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHurtOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_hurt_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_hurt_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -82,10 +82,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerHurtOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_hurt_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_hurt_fixture.exe' if os.name=='nt' else 'player_hurt_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_hurt_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_inventory_parity.py b/tools/test_player_inventory_parity.py index 13d90b9c0..10f6af812 100644 --- a/tools/test_player_inventory_parity.py +++ b/tools/test_player_inventory_parity.py @@ -57,7 +57,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerInventoryOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_inventory_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_inventory_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerInventoryOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_inventory_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_inventory_fixture.exe' if os.name=='nt' else 'player_inventory_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_inventory_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_player_travel_parity.py b/tools/test_player_travel_parity.py index 2fc9e1b48..9b96ba8e8 100644 --- a/tools/test_player_travel_parity.py +++ b/tools/test_player_travel_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerTravelOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/player_travel_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/player_travel_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,10 +66,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaPlayerTravelOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','player_travel_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('player_travel_fixture.exe' if os.name=='nt' else 'player_travel_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'player_travel_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_powder_snow_collision_parity.py b/tools/test_powder_snow_collision_parity.py index 737e367be..10c287cc5 100644 --- a/tools/test_powder_snow_collision_parity.py +++ b/tools/test_powder_snow_collision_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py index 6df5f8fa6..be1ed7e25 100644 --- a/tools/test_raid_parity.py +++ b/tools/test_raid_parity.py @@ -316,7 +316,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/raid_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/raid_fixture.rs', lab.ROOT / 'crates/horizon-client/src/raid.rs', lab.ROOT / 'crates/horizon-client/src/patrol.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -335,10 +335,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'raid_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/raid_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'raid_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_random_tick_sections_parity.py b/tools/test_random_tick_sections_parity.py index 632808523..0b78afadb 100644 --- a/tools/test_random_tick_sections_parity.py +++ b/tools/test_random_tick_sections_parity.py @@ -7,7 +7,7 @@ Each case loads sections (every block state fills one, alone, so each state's ow ticking and a non-ticking state), ticks, sets and removes randomly ticking blocks (leaving them in the palette), and ticks again. Vanilla runs ServerLevel.tickChunk's section loop on real sections with the real getBlockRandomPos (VanillaRandomTickSectionsOracle); Horizon runs Behaviours::tick_chunk_random with the game's RandomTickSections -(examples/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick +(examples/probe/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick randomly, and the final randValue. """ import itertools diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py index 4aa91686e..c25f180ac 100644 --- a/tools/test_recipe_book_parity.py +++ b/tools/test_recipe_book_parity.py @@ -8,7 +8,7 @@ having seen a highlighted recipe, the open and filter settings of the four book types, and saving and loading the player's recipeBook compound (with unknown ids dropped, and a compound missing a list ignored). The Java oracle (VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; -examples/recipe_book_fixture drives horizon_client::recipe_book. After each +examples/probe/recipe_book_fixture drives horizon_client::recipe_book. After each operation the count, the known and highlighted recipes, the settings and the saved compound are compared. """ diff --git a/tools/test_recipe_book_render_parity.py b/tools/test_recipe_book_render_parity.py index 78d911d72..f60ac83fb 100644 --- a/tools/test_recipe_book_render_parity.py +++ b/tools/test_recipe_book_render_parity.py @@ -11,7 +11,7 @@ the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's widgets for that state as RecipeBookComponent.initVisuals and RecipeBookPage.init do and records every GuiGraphicsExtractor call of their extractRenderState, the tooltips and GhostSlots.extractRenderState, with its -pose; examples/recipe_book_render_fixture lays out the same state with +pose; examples/probe/recipe_book_render_fixture lays out the same state with horizon_client::recipe_book_screen, which the game paints. The call lists must agree. """ diff --git a/tools/test_recipe_book_view_parity.py b/tools/test_recipe_book_view_parity.py index a38d04eca..dcdc88a88 100644 --- a/tools/test_recipe_book_view_parity.py +++ b/tools/test_recipe_book_view_parity.py @@ -8,7 +8,7 @@ grid, the furnace, blast furnace or smoker) with random inventory and menu contents and the craftable filter on or off. The Java oracle (VanillaRecipeBookViewOracle, on the client jar) runs ClientRecipeBook, RecipeCollection.selectRecipes and the tab and page logic of -RecipeBookComponent; examples/recipe_book_view_fixture runs +RecipeBookComponent; examples/probe/recipe_book_view_fixture runs horizon_client::recipe_book::ClientBook. Per tab: visibility, pages and every button's displays with their selected and craftable flags, in order (the client's HashMap of display ids decides it). Most cases also carry a diff --git a/tools/test_registered_entity_fluid_parity.py b/tools/test_registered_entity_fluid_parity.py index c994c392a..ff7a83eb6 100644 --- a/tools/test_registered_entity_fluid_parity.py +++ b/tools/test_registered_entity_fluid_parity.py @@ -53,7 +53,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registered-entity-fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegisteredEntityFluidOracle','VanillaEntityFluidOracle','VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/entity_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_entity_fluid_parity.py',lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/entity_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -67,7 +67,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','entity_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('entity_fluid_fixture.exe' if os.name=='nt' else 'entity_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'entity_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered entity fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registered_player_combat_parity.py b/tools/test_registered_player_combat_parity.py index 219d75e52..eecb6e6cf 100644 --- a/tools/test_registered_player_combat_parity.py +++ b/tools/test_registered_player_combat_parity.py @@ -48,7 +48,7 @@ def main(): helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' damage_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDamageSourceOracle.java' - sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/registered_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,damage_helper,lab.ROOT/'tools/test_server_player_combat_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/registered_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRegisteredPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());damage=json.loads((damage_dir/'catalog.json').read_text());fixtures=list(corpus(states,damage));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json',damage_dir/'catalog.json',damage_dir/'types.json',damage_dir/'tags.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','registered_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('registered_player_combat_fixture.exe' if os.name=='nt' else 'registered_player_combat_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'registered_player_combat_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_registry_collision_scan_parity.py b/tools/test_registry_collision_scan_parity.py index e183875ca..5b40d7285 100644 --- a/tools/test_registry_collision_scan_parity.py +++ b/tools/test_registry_collision_scan_parity.py @@ -66,7 +66,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -96,10 +96,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_registry_fall_ray_parity.py b/tools/test_registry_fall_ray_parity.py index b343663e3..a7639c3ab 100644 --- a/tools/test_registry_fall_ray_parity.py +++ b/tools/test_registry_fall_ray_parity.py @@ -47,7 +47,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry-fall-ray-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFallRayOracle','VanillaInteractionShapeOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fall_ray_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fall_ray_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']);fluids=fluid_tags(jars['server']) if tags!=worldgen.tag_resources(jars['client']) or fluids!=fluid_tags(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -61,7 +61,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','info.json','block-registry.nbt','interaction-shapes.nbt','tags.json','fluid-tags.json','bound-tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fall_ray_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fall_ray_fixture.exe' if os.name=='nt' else 'registry_fall_ray_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fall_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registered fall-ray output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_registry_fluid_parity.py b/tools/test_registry_fluid_parity.py index 2ae0486fe..fd0fb106b 100644 --- a/tools/test_registry_fluid_parity.py +++ b/tools/test_registry_fluid_parity.py @@ -48,7 +48,7 @@ def corpus(info): def main(): lock,jars,libraries=base.verify_artifacts();build=lab.LOCAL/'rust-registry_fluid-parity';build.mkdir(exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) root=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity';oracles=[root/(n+'.java') for n in ['VanillaRegistryFluidOracle','VanillaHeightmapOracle','VanillaBlockSupportOracle','VanillaCollisionOracle','VanillaBlockStateCodecOracle']] - sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/registry_fluid_fixture.rs'] + sources=[*oracles,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-world/examples/probe/registry_fluid_fixture.rs'] for crate in ['horizon-core','horizon-world']:sources += [lab.ROOT/'crates'/crate/'Cargo.toml',*sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] tested=base.source_hashes(sources);tags=worldgen.tag_resources(jars['server']) if tags!=worldgen.tag_resources(jars['client']):raise AssertionError('Native tags differ between artifacts') @@ -62,7 +62,7 @@ def main(): with (build/'inputs.txt').open('w') as output: for f in corpus(info):output.write(json.dumps(f,separators=(',',':'))+'\n');count+=1 fixture_paths=[build/n for n in ['inputs.txt','facts.json','fluid-info.json','block-registry.nbt','cached-support.nbt','tags.json']];fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--locked','--release','-p','horizon-world','--example','registry_fluid_fixture'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('registry_fluid_fixture.exe' if os.name=='nt' else 'registry_fluid_fixture');run([binary,build],'rust');references=[] + run(['cargo','build','--locked','--release','-p','horizon-world','--example','probe'],'compile-rust');metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe');run([binary,'registry_fluid_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side);matched=base.compare(build/(side+'.txt'),build/'rust.txt');references.append(dict(side=side,jar_sha256=lab.digest(jar,'sha256'),output_sha256=lab.digest(build/(side+'.txt'),'sha256'),matched_output_lines=matched));print(f'{side}: {matched:,} registry_fluid output lines match Rust',flush=True) base.ensure_sources_unchanged(sources,tested);base.ensure_sources_unchanged(fixture_paths,fixtures) diff --git a/tools/test_replace_block_parity.py b/tools/test_replace_block_parity.py index 8ca916b07..e96bf4c72 100644 --- a/tools/test_replace_block_parity.py +++ b/tools/test_replace_block_parity.py @@ -51,7 +51,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/replace_block_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/replace_block_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -68,10 +68,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","replace_block_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("replace_block_fixture.exe" if os.name=="nt" else "replace_block_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"replace_block_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_resource_pack_parity.py b/tools/test_resource_pack_parity.py index 6169542c5..2d9ae2a85 100644 --- a/tools/test_resource_pack_parity.py +++ b/tools/test_resource_pack_parity.py @@ -9,7 +9,7 @@ sources) and selects them over the prepared vanilla resources. The Java oracle and MultiPackResourceManager and asks what each reload listener reads: which pack a file comes from, translations (ClientLanguage), sound events (SoundManager.prepare), font providers (FontManager) and atlas sources -(SpriteSourceList). examples/pack_resources_fixture builds Horizon's resource +(SpriteSourceList). examples/probe/pack_resources_fixture builds Horizon's resource root for the same selection (packs::build_overlay) and reads it with Horizon's loaders. Every answer must agree. """ diff --git a/tools/test_restitution_parity.py b/tools/test_restitution_parity.py index bbb2d95ba..ada050a13 100644 --- a/tools/test_restitution_parity.py +++ b/tools/test_restitution_parity.py @@ -51,7 +51,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRestitutionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/restitution_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/restitution_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaRestitutionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','restitution_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('restitution_fixture.exe' if os.name=='nt' else 'restitution_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'restitution_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_retrogen_chunk_parity.py b/tools/test_retrogen_chunk_parity.py index 2fe4be7ef..9a13e1303 100644 --- a/tools/test_retrogen_chunk_parity.py +++ b/tools/test_retrogen_chunk_parity.py @@ -56,7 +56,7 @@ def main(): helper=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,helper,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/chunk_stage_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/chunk_stage_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -74,10 +74,10 @@ def main(): (build/"tags.json").write_text(json.dumps(tags,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"tags.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","chunk_stage_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("chunk_stage_fixture.exe" if os.name=="nt" else "chunk_stage_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"chunk_stage_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_retrogen_data_parity.py b/tools/test_retrogen_data_parity.py index 5904cbe93..242f3b5d3 100644 --- a/tools/test_retrogen_data_parity.py +++ b/tools/test_retrogen_data_parity.py @@ -38,7 +38,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRetrogenDataOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/retrogen_data_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/retrogen_data_fixture.rs'] tested_sources=base.source_hashes(sources) commands=list(corpus());inputs=build/'inputs.txt';inputs.write_text('\n'.join(json.dumps(command) for command in commands)+'\n') tested_fixtures=base.source_hashes([inputs]);classes=build/'classes';classes.mkdir(exist_ok=True) @@ -46,10 +46,10 @@ def main(): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) dependencies=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','retrogen_data_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('retrogen_data_fixture.exe' if os.name=='nt' else 'retrogen_data_fixture') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'retrogen_data_fixture',inputs,build/'rust.txt'],'rust') references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependencies]),'dev.horizonlab.parity.VanillaRetrogenDataOracle',inputs,build/(side+'.txt')],side) diff --git a/tools/test_rule_test_parity.py b/tools/test_rule_test_parity.py index f87283982..8fef86b95 100644 --- a/tools/test_rule_test_parity.py +++ b/tools/test_rule_test_parity.py @@ -58,7 +58,7 @@ def main(): tags=worldgen.tag_resources(jars['server']) if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') - sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/rule_test_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/rule_test_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,10 +73,10 @@ def main(): if len(facts['states'])!=35723:raise ValueError('incomplete pinned state registry') fixtures=list(corpus(facts,tags));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','rule_test_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('rule_test_fixture.exe' if os.name=='nt' else 'rule_test_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'rule_test_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_scaffolding_collision_parity.py b/tools/test_scaffolding_collision_parity.py index 3e60f229a..bebd63087 100644 --- a/tools/test_scaffolding_collision_parity.py +++ b/tools/test_scaffolding_collision_parity.py @@ -44,7 +44,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCollisionContextOracle.java' helpers=[oracle.with_name('VanillaFaceSupportOracle.java')] runner=lab.ROOT/'tools/test_collision_context_parity.py' - sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/collision_context_fixture.rs'] + sources=[oracle,*helpers,runner,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/collision_context_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -55,10 +55,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaCollisionContextOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','collision_context_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('collision_context_fixture.exe' if os.name=='nt' else 'collision_context_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'collision_context_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_scattered_ore_parity.py b/tools/test_scattered_ore_parity.py index b6bbd5aa7..0cbb6fcac 100644 --- a/tools/test_scattered_ore_parity.py +++ b/tools/test_scattered_ore_parity.py @@ -52,7 +52,7 @@ def main(): if not tags or tags!=worldgen.tag_resources(jars['client']):raise ValueError('client/server tags differ') (build/'tags.json').write_text(json.dumps(tags,separators=(',',':')),encoding='utf-8') sources=[oracle,helper,tag_helper,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/scattered_ore_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/scattered_ore_fixture.rs"] tested_sources=base.source_hashes(sources) fixture_paths=[build/"tags.json"];classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -69,10 +69,10 @@ def main(): fixtures=list(corpus(facts));inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths.append(inputs) tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","scattered_ore_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("scattered_ore_fixture.exe" if os.name=="nt" else "scattered_ore_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"scattered_ore_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index 8a035eb17..db308d861 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -13,7 +13,7 @@ of each collection in vanilla's iteration order (objectivesByName and playerScores as fastutil open hash maps, teamsByName, each team's HashSet of players), and the ScoreboardSaveData.Packed codec output that data/minecraft/scoreboard.dat holds, before and after loading it back. -`examples/scoreboard_fixture` runs the same cases on +`examples/probe/scoreboard_fixture` runs the same cases on `horizon_client::scoreboard`, reloads vanilla's NBT, and vanilla reloads Horizon's NBT; all must agree. The one order vanilla leaves to identity hash codes (each holder's scores within PlayerScores) is compared as a set. @@ -250,10 +250,10 @@ def main(): inputs = build / 'inputs.jsonl' inputs.write_text(''.join(json.dumps(c, ensure_ascii=False) + '\n' for c in chosen), encoding='utf-8') run([*oracle, 'run', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'scoreboard_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('scoreboard_fixture.exe' if os.name == 'nt' else 'scoreboard_fixture') - run([binary, build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'scoreboard_fixture',build / 'registries.json', inputs, build / 'rust.jsonl', build / 'vanilla.jsonl'], 'rust') read = lambda p: [json.loads(l) for l in p.read_text(encoding='utf-8').splitlines()] vanilla, rust = read(build / 'vanilla.jsonl'), read(build / 'rust.jsonl') assert len(vanilla) == len(rust) diff --git a/tools/test_screen_layout_parity.py b/tools/test_screen_layout_parity.py index d488716f6..c9e791afb 100644 --- a/tools/test_screen_layout_parity.py +++ b/tools/test_screen_layout_parity.py @@ -6,7 +6,7 @@ a loom screen and menu whose state comes from the case (inputs present, the selectable patterns, the selected one, the scroller, the result banner or the six-layer error, the mouse over a pattern button) and CrafterScreen's background, disabled slots and redstone arrow, recording every -GuiGraphicsExtractor call; examples/screen_layout_fixture lays out the same +GuiGraphicsExtractor call; examples/probe/screen_layout_fixture lays out the same state with horizon_client::screen_layout, which the game paints. The ordered call lists must agree. """ diff --git a/tools/test_section_mesh_parity.py b/tools/test_section_mesh_parity.py index 78c0d68e9..65878bc97 100644 --- a/tools/test_section_mesh_parity.py +++ b/tools/test_section_mesh_parity.py @@ -481,7 +481,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java' helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']] sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers, - lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs'] + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/probe/section_mesh_fixture.rs'] for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']: sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))] tested = base.source_hashes(sources) @@ -502,14 +502,14 @@ def main(): dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'), '-cp', dependencies, '-d', classes, oracle, *helpers], 'compile-java') env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3') - run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory']) / 'fast/examples' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture') + binary = Path(metadata['target_directory']) / 'fast/examples' / ('probe.exe' if os.name=='nt' else 'probe') java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle'] - run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust') + run([binary, 'section_mesh_fixture',resources, inputs, BUILD / 'rust.jsonl'], 'rust') run([*java, inputs, BUILD / 'client.jsonl', resources], 'client') run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts') - run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') + run([binary, 'section_mesh_fixture',resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts') report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0, 'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}} diff --git a/tools/test_server_files_parity.py b/tools/test_server_files_parity.py index 735bca302..82c0eaa8a 100644 --- a/tools/test_server_files_parity.py +++ b/tools/test_server_files_parity.py @@ -194,7 +194,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerFilesOracle.java' sources = [Path(__file__).resolve(), oracle, lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.lock', - lab.ROOT / 'crates/horizon-client/examples/server_files_probe.rs', + lab.ROOT / 'crates/horizon-client/examples/probe/server_files_probe.rs', *sorted((lab.ROOT / 'crates/horizon-client/src/server').glob('*.rs'))] tested = base.source_hashes(sources) cases, count = make_cases(build) @@ -204,8 +204,8 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], build, 'compile-java') - binary = oh.build_probe(build, 'server_files_probe') - oh.run_logged([binary, cases, build / 'rust.txt'], build, 'rust') + command = oh.build_probe(build, 'server_files_probe') + oh.run_logged([*command, cases, build / 'rust.txt'], build, 'rust') oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaServerFilesOracle', cases, build / 'server.txt'], build, 'server') diff --git a/tools/test_server_player_combat_parity.py b/tools/test_server_player_combat_parity.py index 7192e7109..161c4cbcf 100644 --- a/tools/test_server_player_combat_parity.py +++ b/tools/test_server_player_combat_parity.py @@ -66,7 +66,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerCombatOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_combat_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_player_hurt_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_combat_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -77,11 +77,11 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerCombatOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json',build/'head.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_combat_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_combat_fixture.exe' if os.name=='nt' else 'server_player_combat_fixture') - run([binary,build],'rust') - run([binary,build,'--live'],'rust-live') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_combat_fixture',build],'rust') + run([binary,'server_player_combat_fixture',build,'--live'],'rust-live') base.compare(build/'rust.txt',build/'rust-live.txt');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') diff --git a/tools/test_server_player_damage_parity.py b/tools/test_server_player_damage_parity.py index 4a0e0b9c7..8e1418f4e 100644 --- a/tools/test_server_player_damage_parity.py +++ b/tools/test_server_player_damage_parity.py @@ -51,7 +51,7 @@ def main(): oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerPlayerDamageOracle.java' helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAttributeOracle.java' health_helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerHealthOracle.java' - sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/server_player_damage_fixture.rs'] + sources=[oracle,helper,health_helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/server_player_damage_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -62,10 +62,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaServerPlayerDamageOracle',mode,path],side+'-'+mode) java('server','export',build);states=json.loads((build/'catalog.json').read_text());fixtures=list(corpus(states));inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs,build/'catalog.json',build/'ids.json',build/'slots.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','server_player_damage_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('server_player_damage_fixture.exe' if os.name=='nt' else 'server_player_damage_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'server_player_damage_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_simple_block_parity.py b/tools/test_simple_block_parity.py index f68f3c92e..3af85a241 100644 --- a/tools/test_simple_block_parity.py +++ b/tools/test_simple_block_parity.py @@ -93,7 +93,7 @@ def run(corpus, build_name, source_file, scope): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts();oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleBlockOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] - sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_block_fixture.rs'] + sources=[oracle,*helpers,Path(__file__),Path(source_file),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_block_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=3600,stdout=log,stderr=subprocess.STDOUT) @@ -116,9 +116,9 @@ def run(corpus, build_name, source_file, scope): with inputs.open('w',encoding='utf-8') as output: for fixture in corpus(facts,placement):output.write(json.dumps(fixture,separators=(',',':'))+'\n');fixture_count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=base.source_hashes(fixtures);print(f'Prepared {fixture_count:,} placement fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','simple_block_fixture'],'compile-rust') - metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('simple_block_fixture.exe' if os.name=='nt' else 'simple_block_fixture') - run([binary,build],'rust');references=[] + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True));binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_block_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} {label} output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_simple_container_parity.py b/tools/test_simple_container_parity.py index 8365276dd..0af91292a 100644 --- a/tools/test_simple_container_parity.py +++ b/tools/test_simple_container_parity.py @@ -59,7 +59,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSimpleContainerOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/simple_container_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/simple_container_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSimpleContainerOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','simple_container_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('simple_container_fixture.exe' if os.name=='nt' else 'simple_container_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'simple_container_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_spawn_rules_parity.py b/tools/test_spawn_rules_parity.py index e71a032b5..19bd8db46 100644 --- a/tools/test_spawn_rules_parity.py +++ b/tools/test_spawn_rules_parity.py @@ -138,7 +138,7 @@ def main(): entity_types = json.loads((resources / 'entity-types.json').read_text()) types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/spawn_rules_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -155,10 +155,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'spawn_rules_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index b1637cf4e..5aa9029e3 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -230,7 +230,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] @@ -249,10 +249,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_sprint_input_parity.py b/tools/test_sprint_input_parity.py index 0fe9eecec..0ac515e44 100644 --- a/tools/test_sprint_input_parity.py +++ b/tools/test_sprint_input_parity.py @@ -40,7 +40,7 @@ def main(): build=lab.LOCAL/'rust-sprint-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/sprint_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/sprint_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) @@ -49,10 +49,10 @@ def main(): classes=build/'classes';classes.mkdir(exist_ok=True) dependencies=os.pathsep.join(map(str,[jars['client'],*libraries])) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',dependencies,'-d',classes,oracle],'compile-java') - run(['cargo','build','--locked','-p','horizon-client','--example','sprint_probe'],'compile-rust') + run(['cargo','build','--locked','-p','horizon-client','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--locked','--no-deps','--format-version','1'],cwd=lab.ROOT)) - binary=Path(metadata['target_directory'])/'debug/examples'/('sprint_probe.exe' if os.name=='nt' else 'sprint_probe') - run([binary,inputs,build/'rust.txt'],'rust') + binary=Path(metadata['target_directory'])/'debug/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'sprint_probe',inputs,build/'rust.txt'],'rust') run(['java','-Xmx768M','-cp',str(classes)+os.pathsep+dependencies,'dev.horizonlab.parity.VanillaSprintInputOracle',inputs,build/'client.txt'],'client') matched=base.compare(build/'client.txt',build/'rust.txt') if matched!=operations+len(fixtures):raise AssertionError('Incomplete input output') diff --git a/tools/test_state_provider_parity.py b/tools/test_state_provider_parity.py index 1cc74b2b3..9f7523273 100644 --- a/tools/test_state_provider_parity.py +++ b/tools/test_state_provider_parity.py @@ -309,7 +309,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStateProviderOracle.java' helpers=[oracle.with_name(name+'.java') for name in ['VanillaBlockStateCodecOracle','VanillaHeightmapOracle','VanillaMaterialConditionOracle','VanillaBiomeTemperatureOracle','VanillaAnchorOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockSurvivalOracle','VanillaCollisionOracle']] - sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/state_provider_fixture.rs'] + sources=[oracle,*helpers,lab.ROOT/'tools/test_block_survival_parity.py',lab.ROOT/'tools/test_biome_temperature_parity.py',lab.ROOT/'tools/test_material_condition_parity.py',lab.ROOT/'tools/test_worldgen_parity.py',Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/state_provider_fixture.rs'] tested_sources=base.source_hashes(sources) environment={'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'dependencies':{str(path):lab.digest(path,'sha256') for path in [*jars.values(),*libraries]}} checkpoint=survival.load_checkpoint(checkpoint_path,tested_sources,environment) if args.resume else None @@ -371,9 +371,9 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n') fixture_count+=1;requested_samples+=len(fixture['states'])*fixture['repeats']*2 fixture_paths=[inputs,build/'survival-extra-definitions.json',build/'survival-placement-classes.json',build/'survival-support-tags.json',build/'survival-classes.json',build/'survival-rules.json',build/'cached-support.nbt',build/'support-cached-states.json',build/'block-properties.nbt',build/'cached-collision.nbt',build/'biomes.json',build/'biome_tags.json',build/'fluid-tags.json',build/'catalog.json',build/'providers.json',build/'tags.json',build/'facts-client.json',build/'facts-server.json'];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','state_provider_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('state_provider_fixture.exe' if os.name=='nt' else 'state_provider_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') counts={'block_states':len(facts['states']),'blocks':len(facts['defaults']),'integer_properties':len(facts['integers']),'codec_inputs':fixture_count,'provider_types':10,'named_providers':len(catalog_resources),'rule_predicate_types':16,'survival_supported_blocks':len(survival_rules),'survival_supported_states':sum(s['id'] in survival_rules for s in facts['states']),'support_cached_states':len(support_states),'support_dynamic_states':len(facts['states'])-len(support_states),'biomes':len(biomes),'biome_tag_files':len(biome_tags),'fluid_tag_files':len(fluid_tags),'bundled_provider_definitions':len(provider_resources),'block_tag_files':len(tags),'requested_samples':requested_samples} base.ensure_sources_unchanged(sources,tested_sources) checkpoint={'schema':1,'environment':environment,'sources_sha256':tested_sources,'fixtures_sha256':{str(lab.ROOT/name):digest for name,digest in tested_fixtures.items()},'artifacts_sha256':{str(path):lab.digest(path,'sha256') for path in [binary,*sorted(classes.rglob('*.class'))]},'binary':str(binary),'counts':counts,'outputs':{}} @@ -386,7 +386,7 @@ def main(): checkpoint['outputs'][name]=lab.digest(output,'sha256') survival.save_checkpoint(checkpoint_path,checkpoint) print(f'{name}: completed output checkpointed',flush=True) - stage('rust',lambda:run([checkpoint['binary'],build],'rust'));references=[] + stage('rust',lambda:run([checkpoint['binary'],'state_provider_fixture',build],'rust'));references=[] for side,jar in jars.items(): stage(side,lambda:java(side,side,build));reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_status_effect_parity.py b/tools/test_status_effect_parity.py index 5c94af434..6f369c683 100644 --- a/tools/test_status_effect_parity.py +++ b/tools/test_status_effect_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusEffectOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_effect_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_effect_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusEffectOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_effect_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_effect_fixture.exe' if os.name=='nt' else 'status_effect_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_effect_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_status_tick_parity.py b/tools/test_status_tick_parity.py index c14f72bf9..40786fe3c 100644 --- a/tools/test_status_tick_parity.py +++ b/tools/test_status_tick_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStatusTickOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/status_tick_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/status_tick_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStatusTickOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','status_tick_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('status_tick_fixture.exe' if os.name=='nt' else 'status_tick_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'status_tick_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_stepped_interpolation_parity.py b/tools/test_stepped_interpolation_parity.py index 998d5a4ba..e5586c981 100644 --- a/tools/test_stepped_interpolation_parity.py +++ b/tools/test_stepped_interpolation_parity.py @@ -94,7 +94,7 @@ def main(): 'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')], check=True) subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example', - 'stepped_interpolation_fixture', '--', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) + 'probe', '--', 'stepped_interpolation_fixture', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla') diff --git a/tools/test_stored_consume_parity.py b/tools/test_stored_consume_parity.py index e10a020ca..3ddfed86a 100644 --- a/tools/test_stored_consume_parity.py +++ b/tools/test_stored_consume_parity.py @@ -55,7 +55,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -66,14 +66,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_consume_fixture.exe' if os.name=='nt' else 'stored_consume_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';enriched_hash=base.source_hashes([enriched]) - run([binary,build,side],'rust-'+side) + run([binary,'stored_consume_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';rust_output=build/f'rust-{side}.txt';matched=base.compare(reference,rust_output) base.ensure_sources_unchanged([enriched],enriched_hash) tested_fixtures.update(enriched_hash);fixture_paths.append(enriched) diff --git a/tools/test_stored_effect_attributes_parity.py b/tools/test_stored_effect_attributes_parity.py index 3d3d0a543..2a8fe799d 100644 --- a/tools/test_stored_effect_attributes_parity.py +++ b/tools/test_stored_effect_attributes_parity.py @@ -83,7 +83,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -94,14 +94,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectAttributesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_attributes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_attributes_fixture.exe' if os.name=='nt' else 'stored_effect_attributes_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_attributes_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect attribute output lines match Rust',flush=True) diff --git a/tools/test_stored_effect_notifications_parity.py b/tools/test_stored_effect_notifications_parity.py index 82bcb65ad..6a0cee403 100644 --- a/tools/test_stored_effect_notifications_parity.py +++ b/tools/test_stored_effect_notifications_parity.py @@ -60,9 +60,9 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectNotificationsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/stored_effect_notifications_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_notifications_fixture.rs'] helper=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStoredEffectAttributesOracle.java' - sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) + sources.extend([helper,lab.ROOT/'crates/horizon-world/examples/probe/stored_effect_attributes_fixture.rs',lab.ROOT/'tools/test_stored_effect_attributes_parity.py']) tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -73,14 +73,14 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaStoredEffectNotificationsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','stored_effect_notifications_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('stored_effect_notifications_fixture.exe' if os.name=='nt' else 'stored_effect_notifications_fixture') + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') references=[] for side,jar in jars.items(): java(side,side,build) enriched=build/f'inputs-{side}.txt';fixture_paths.append(enriched);tested_fixtures.update(base.source_hashes([enriched])) - run([binary,build,side],'rust-'+side) + run([binary,'stored_effect_notifications_fixture',build,side],'rust-'+side) reference=build/f'{side}.txt';candidate=build/f'rust-{side}.txt';matched=base.compare(reference,candidate) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched,'rust_output_sha256':lab.digest(candidate,'sha256')}) print(f'{side}: {matched:,} stored effect notification output lines match Rust',flush=True) diff --git a/tools/test_structure_density_parity.py b/tools/test_structure_density_parity.py index 75094c3e6..ad15790e0 100644 --- a/tools/test_structure_density_parity.py +++ b/tools/test_structure_density_parity.py @@ -60,7 +60,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureDensityOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/structure_density_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/structure_density_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") tested_fixtures=base.source_hashes([inputs]);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -68,10 +68,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","structure_density_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("structure_density_fixture.exe" if os.name=="nt" else "structure_density_fixture") - run([binary,inputs,build/"rust.txt"],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"structure_density_fixture",inputs,build/"rust.txt"],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_subtitle_parity.py b/tools/test_subtitle_parity.py index 21b4c7175..1444bb5bd 100644 --- a/tools/test_subtitle_parity.py +++ b/tools/test_subtitle_parity.py @@ -11,7 +11,7 @@ it renders), the notification display time, the text background opacity and its "chat only" setting, and a GUI size. Each frame records the fills and texts in order with the pose: which subtitles show, their order, merging of repeats, expiry, the fade by age (looping sounds stay bright longer), the direction -arrows and the box width. `examples/subtitle_fixture` replays the cases through +arrows and the box width. `examples/probe/subtitle_fixture` replays the cases through `horizon_client::subtitles`; the frames must agree exactly. test_subtitle_parity.py [--count N] [--detail N] @@ -133,10 +133,10 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityFont', 'VanillaSubtitleOracle'))], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSubtitleOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'subtitle_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('subtitle_fixture.exe' if os.name == 'nt' else 'subtitle_fixture') - run([binary, resources, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'subtitle_fixture',resources, inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text(encoding='utf-8').splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text(encoding='utf-8').splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_suffocation_parity.py b/tools/test_suffocation_parity.py index c9d8d37ec..ffe80b31f 100644 --- a/tools/test_suffocation_parity.py +++ b/tools/test_suffocation_parity.py @@ -42,7 +42,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/suffocation_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/suffocation_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -72,10 +72,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'suffocation_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('suffocation_fixture.exe' if os.name=='nt' else 'suffocation_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'suffocation_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_swimming_parity.py b/tools/test_swimming_parity.py index d63ce66e1..574b72e5b 100644 --- a/tools/test_swimming_parity.py +++ b/tools/test_swimming_parity.py @@ -40,7 +40,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSwimmingOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/swimming_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/swimming_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -51,10 +51,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSwimmingOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','swimming_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('swimming_fixture.exe' if os.name=='nt' else 'swimming_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'swimming_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_bytes_parity.py b/tools/test_synced_bytes_parity.py index cc0024a1c..a6659bf21 100644 --- a/tools/test_synced_bytes_parity.py +++ b/tools/test_synced_bytes_parity.py @@ -46,7 +46,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedBytesOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_bytes_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_bytes_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -57,10 +57,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedBytesOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_bytes_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_bytes_fixture.exe' if os.name=='nt' else 'synced_bytes_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_bytes_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_synced_floats_parity.py b/tools/test_synced_floats_parity.py index 768192ea2..fa7ca7132 100644 --- a/tools/test_synced_floats_parity.py +++ b/tools/test_synced_floats_parity.py @@ -50,7 +50,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSyncedFloatsOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/synced_floats_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/synced_floats_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -61,10 +61,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaSyncedFloatsOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','synced_floats_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('synced_floats_fixture.exe' if os.name=='nt' else 'synced_floats_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'synced_floats_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py index cdf32df65..9b3c65605 100644 --- a/tools/test_tab_list_parity.py +++ b/tools/test_tab_list_parity.py @@ -10,12 +10,12 @@ them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the case's teams (colour, prefix, suffix), `list` objective (integer or hearts, number formats) and scores, with the header, footer, row background option and Hud ticks. It records every fill, text (as styled runs), sprite and -face blit. `examples/tab_list_fixture` lays out the same frames with +face blit. `examples/probe/tab_list_fixture` lays out the same frames with `horizon_client::tab_list`; the ordered call lists must agree. Downloaded skin images are compared too: VanillaSkinImageOracle decodes PNGs as NativeImage does and runs SkinTextureDownloader.processLegacySkin; -`examples/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. +`examples/probe/skin_image_fixture` runs `horizon_client::skins`. Pixels must agree. test_tab_list_parity.py [--count N] [--detail N] """ @@ -241,13 +241,13 @@ def main(): *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle', 'VanillaSkinImageOracle'))], 'compile-java') run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--', - resources, inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'tab_list_fixture', resources, inputs, build / 'rust.jsonl'], 'rust') images = build / 'skins.txt'; images.write_text(''.join(i + '\n' for i in skin_images(args.images))) run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSkinImageOracle', images, build / 'vanilla-skins.txt'], 'vanilla-skins') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'skin_image_fixture', '--', - images, build / 'rust-skins.txt'], 'rust-skins') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'skin_image_fixture', images, build / 'rust-skins.txt'], 'rust-skins') vanilla_skins = (build / 'vanilla-skins.txt').read_text().splitlines() rust_skins = (build / 'rust-skins.txt').read_text().splitlines() assert len(vanilla_skins) == len(rust_skins) == args.images diff --git a/tools/test_team_rules_parity.py b/tools/test_team_rules_parity.py index af73aad10..5eb0c7d9d 100644 --- a/tools/test_team_rules_parity.py +++ b/tools/test_team_rules_parity.py @@ -9,7 +9,7 @@ EntitySelector.pushableBy predicate (collision rules), Entity.isInvisibleTo (name tag visibility, with a stand-in client for the viewer, camera and F1) on stand-in entities, for every combination of two teams' options, the three entities' teams (none, either team) and the flags involved. -`examples/team_rules_fixture` answers from `horizon_client::scoreboard`. +`examples/probe/team_rules_fixture` answers from `horizon_client::scoreboard`. test_team_rules_parity.py [--count N] """ @@ -84,10 +84,10 @@ def main(): PARITY / 'VanillaTeamRulesOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTeamRulesOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'team_rules_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples' / ('team_rules_fixture.exe' if os.name == 'nt' else 'team_rules_fixture') - run([binary, inputs, build / 'rust.jsonl'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples' / ('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'team_rules_fixture',inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) == len(chosen) diff --git a/tools/test_teleport_consume_parity.py b/tools/test_teleport_consume_parity.py index c24dda3a1..8f51361f8 100644 --- a/tools/test_teleport_consume_parity.py +++ b/tools/test_teleport_consume_parity.py @@ -43,7 +43,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTeleportConsumeOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/teleport_consume_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/teleport_consume_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -54,10 +54,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaTeleportConsumeOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','teleport_consume_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('teleport_consume_fixture.exe' if os.name=='nt' else 'teleport_consume_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'teleport_consume_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_terrain_parity.py b/tools/test_terrain_parity.py index 3bd4dbcc6..a818dcabb 100644 --- a/tools/test_terrain_parity.py +++ b/tools/test_terrain_parity.py @@ -75,7 +75,7 @@ def main(): exporter=oracle.with_name("VanillaHeightmapOracle.java") sources=[oracle,exporter,Path(__file__),lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock", lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/terrain_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/terrain_fixture.rs"] tested_sources=base.source_hashes(sources) classes=build/"classes";classes.mkdir(exist_ok=True) def run(command,name): @@ -99,10 +99,10 @@ def main(): (build/"registries.json").write_text(json.dumps(bundle,separators=(",",":")),encoding="utf-8") fixture_paths=[inputs,build/"registries.json",build/"facts-client.json",build/"facts-server.json"] tested_fixtures=base.source_hashes(fixture_paths) - run(["cargo","build","--release","-p","horizon-world","--example","terrain_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("terrain_fixture.exe" if os.name=="nt" else "terrain_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"terrain_fixture",build],"rust") references=[] for side,jar in jars.items(): java(side,side,build) diff --git a/tools/test_tick_parity.py b/tools/test_tick_parity.py index 4efcc93e9..47dd842d0 100644 --- a/tools/test_tick_parity.py +++ b/tools/test_tick_parity.py @@ -145,7 +145,7 @@ def main(): inputs.write_text("\n".join(commands) + "\n", encoding="utf-8") oracle = lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTickOracle.java" data_oracle = oracle.with_name("VanillaTickDataOracle.java") - sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/tick_fixture.rs"] + sources = [oracle, data_oracle, Path(__file__).resolve(), lab.ROOT / "tools/test_rust_parity.py", lab.ROOT / "Cargo.toml", lab.ROOT / "Cargo.lock", lab.ROOT / "crates/horizon-core/Cargo.toml", lab.ROOT / "crates/horizon-world/Cargo.toml", *sorted((lab.ROOT / "crates/horizon-core/src").rglob("*.rs")), *sorted((lab.ROOT / "crates/horizon-world/src").rglob("*.rs")), lab.ROOT / "crates/horizon-world/examples/probe/tick_fixture.rs"] tested_sources = test_rust_parity.source_hashes(sources) classes = base / "classes" classes.mkdir() @@ -163,9 +163,9 @@ def main(): completed.check_returncode() return completed.stdout data_java("server", "generate") - test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "tick_fixture"]) - fixture = Path(metadata["target_directory"]) / "release/examples" / ("tick_fixture.exe" if os.name == "nt" else "tick_fixture") - test_rust_parity.run([str(fixture), str(base)]) + test_rust_parity.run(["cargo", "build", "--release", "-p", "horizon-world", "--example", "probe"]) + fixture = Path(metadata["target_directory"]) / "release/examples" / ("probe.exe" if os.name=="nt" else "probe") + test_rust_parity.run([str(fixture), "tick_fixture", str(base)]) references = [] for side, jar in jars.items(): reference = base / f"vanilla-{side}.txt" diff --git a/tools/test_trading_parity.py b/tools/test_trading_parity.py index 13ef60880..c26c449fb 100644 --- a/tools/test_trading_parity.py +++ b/tools/test_trading_parity.py @@ -184,7 +184,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTradingOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/trading_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/trading_fixture.rs', lab.ROOT / 'crates/horizon-client/src/merchant.rs', lab.ROOT / 'crates/horizon-client/src/menu.rs'] tested = base.source_hashes([s for s in sources if s.exists()]) inputs = build / 'inputs.txt' @@ -219,9 +219,9 @@ def main(): if args.java_only: print(f'{len(vanilla)} oracle lines') return - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'trading_fixture'], 'compile-rust') - binary = lab.cargo_target() / 'release/examples/trading_fixture' - run([binary, resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') + binary = lab.cargo_target() / 'release/examples/probe' + run([binary, 'trading_fixture', resources, inputs, build / 'server.txt', build / 'rust.txt'], 'rust') rust = (build / 'rust.txt').read_text().splitlines() bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] if bad or len(vanilla) != len(rust): diff --git a/tools/test_translucency_parity.py b/tools/test_translucency_parity.py index fcf8d3842..fff0390eb 100644 --- a/tools/test_translucency_parity.py +++ b/tools/test_translucency_parity.py @@ -52,7 +52,7 @@ def main(): lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java') vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl' run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla') - run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'translucency_fixture', '--', inputs, rust], 'rust') + run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'probe', '--', 'translucency_fixture', inputs, rust], 'rust') expected = [json.loads(line) for line in vanilla.read_text().splitlines()] actual = [json.loads(line) for line in rust.read_text().splitlines()] assert len(expected) == len(actual), 'case count differs' diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 66f7a6eb7..b3f9ace68 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -109,7 +109,7 @@ def main(): oracle=parity/'VanillaTreeFeatureOracle.java';exporter=parity/'VanillaSimpleBlockOracle.java' helpers=[parity/(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] sources=[oracle,exporter,*helpers,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', - *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/tree_feature_fixture.rs'] + *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/tree_feature_fixture.rs'] tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=7200,stdout=log,stderr=subprocess.STDOUT) @@ -135,10 +135,10 @@ def main(): output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) print(f'Prepared {count:,} feature fixtures',flush=True) - run(['cargo','build','--release','-p','horizon-world','--example','tree_feature_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('tree_feature_fixture.exe' if os.name=='nt' else 'tree_feature_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'tree_feature_fixture',build],'rust');references=[] for side,jar in jars.items(): java('VanillaTreeFeatureOracle',side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} tree/ore output lines match Rust',flush=True) references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index 6fb79d9e1..bd6d69ac2 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -194,7 +194,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.RESOURCES oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', @@ -214,10 +214,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_use_flag_reaction_parity.py b/tools/test_use_flag_reaction_parity.py index b52f0b868..de3b5fa20 100644 --- a/tools/test_use_flag_reaction_parity.py +++ b/tools/test_use_flag_reaction_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseFlagReactionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_flag_reaction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_flag_reaction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseFlagReactionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_flag_reaction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_flag_reaction_fixture.exe' if os.name=='nt' else 'use_flag_reaction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_flag_reaction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_use_remainder_parity.py b/tools/test_use_remainder_parity.py index 05b964325..853d12acb 100644 --- a/tools/test_use_remainder_parity.py +++ b/tools/test_use_remainder_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaUseRemainderOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/use_remainder_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/use_remainder_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaUseRemainderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','use_remainder_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('use_remainder_fixture.exe' if os.name=='nt' else 'use_remainder_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'use_remainder_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_value_provider_parity.py b/tools/test_value_provider_parity.py index f276e4f31..589a97632 100644 --- a/tools/test_value_provider_parity.py +++ b/tools/test_value_provider_parity.py @@ -66,7 +66,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaValueProviderOracle.java" sources=[oracle,Path(__file__),lab.ROOT/"tools/test_worldgen_parity.py",lab.ROOT/"tools/test_rust_parity.py",lab.ROOT/"tools/lab.py",lab.ROOT/"Cargo.toml",lab.ROOT/"Cargo.lock",lab.ROOT/"crates/horizon-core/Cargo.toml",lab.ROOT/"crates/horizon-world/Cargo.toml", - *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/value_provider_fixture.rs"] + *sorted((lab.ROOT/"crates/horizon-core/src").rglob("*.rs")),*sorted((lab.ROOT/"crates/horizon-world/src").rglob("*.rs")),lab.ROOT/"crates/horizon-world/examples/probe/value_provider_fixture.rs"] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/"inputs.txt";inputs.write_text("".join(json.dumps(f,separators=(",",":"))+"\n" for f in fixtures),encoding="utf-8") fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths);classes=build/"classes";classes.mkdir(exist_ok=True) @@ -74,10 +74,10 @@ def main(): with (build/(name+".log")).open("w",encoding="utf-8") as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(["javac","--release",lock["minecraft"]["java_major"],"-proc:none","-cp",str(jars["server"])+os.pathsep+dependency_path,"-d",classes,oracle],"compile-java") - run(["cargo","build","--release","-p","horizon-world","--example","value_provider_fixture"],"compile-rust") + run(["cargo","build","--release","-p","horizon-world","--example","probe"],"compile-rust") metadata=json.loads(subprocess.check_output(["cargo","metadata","--no-deps","--format-version","1"],cwd=lab.ROOT,text=True)) - binary=Path(metadata["target_directory"])/"release/examples"/("value_provider_fixture.exe" if os.name=="nt" else "value_provider_fixture") - run([binary,build],"rust") + binary=Path(metadata["target_directory"])/"release/examples"/("probe.exe" if os.name=="nt" else "probe") + run([binary,"value_provider_fixture",build],"rust") references=[] for side,jar in jars.items(): reference=build/f"{side}.txt" diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 7eeace526..73c41e197 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -173,7 +173,7 @@ def main(): lock, jars, libraries = base.verify_artifacts() resources = lab.LOCAL / 'horizon-client/26.3' oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' - sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/vault.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' @@ -190,10 +190,10 @@ def main(): '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') - run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' - run([binary, resources, inputs, build / 'rust.txt'], 'rust') + binary = Path(metadata['target_directory']) / 'release/examples/probe' + run([binary, 'natural_spawn_fixture', resources, inputs, build / 'rust.txt'], 'rust') vanilla = (build / 'server.txt').read_text().splitlines() errors = [l for l in vanilla if ' error ' in l] if errors: diff --git a/tools/test_view_direction_parity.py b/tools/test_view_direction_parity.py index 9dbb47de5..f2738dcff 100644 --- a/tools/test_view_direction_parity.py +++ b/tools/test_view_direction_parity.py @@ -47,7 +47,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaViewDirectionOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/view_direction_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/view_direction_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -58,10 +58,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaViewDirectionOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','view_direction_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('view_direction_fixture.exe' if os.name=='nt' else 'view_direction_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'view_direction_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_water_splash_parity.py b/tools/test_water_splash_parity.py index b746b31c0..84f89d360 100644 --- a/tools/test_water_splash_parity.py +++ b/tools/test_water_splash_parity.py @@ -48,7 +48,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWaterSplashOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/water_splash_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/water_splash_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -59,10 +59,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWaterSplashOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','water_splash_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('water_splash_fixture.exe' if os.name=='nt' else 'water_splash_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'water_splash_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_border_parity.py b/tools/test_world_border_parity.py index 62aa58ddf..618194978 100644 --- a/tools/test_world_border_parity.py +++ b/tools/test_world_border_parity.py @@ -59,7 +59,7 @@ def main(): lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldBorderOracle.java' helper=oracle.with_name('VanillaFaceSupportOracle.java') - sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_border_fixture.rs'] + sources=[oracle,helper,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_border_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -70,10 +70,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldBorderOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_border_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_border_fixture.exe' if os.name=='nt' else 'world_border_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_border_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_border_render_parity.py b/tools/test_world_border_render_parity.py index 1a04a0de4..f8c88b6a6 100644 --- a/tools/test_world_border_render_parity.py +++ b/tools/test_world_border_render_parity.py @@ -103,8 +103,8 @@ def main(): PARITY / 'VanillaWorldBorderRenderOracle.java'], 'compile-java') run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldBorderRenderOracle', inputs, build / 'vanilla.jsonl'], 'vanilla') - run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'world_border_render_fixture', '--', - inputs, build / 'rust.jsonl'], 'rust') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'probe', '--', + 'world_border_render_fixture', inputs, build / 'rust.jsonl'], 'rust') vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] assert len(vanilla) == len(rust) diff --git a/tools/test_world_collision_check_parity.py b/tools/test_world_collision_check_parity.py index d6f7e0bfb..3dae747d5 100644 --- a/tools/test_world_collision_check_parity.py +++ b/tools/test_world_collision_check_parity.py @@ -50,7 +50,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -80,10 +80,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_edge_backoff_parity.py b/tools/test_world_edge_backoff_parity.py index bf4c39c70..10cf1316f 100644 --- a/tools/test_world_edge_backoff_parity.py +++ b/tools/test_world_edge_backoff_parity.py @@ -51,7 +51,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -81,10 +81,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_movement_parity.py b/tools/test_world_movement_parity.py index e01a989f5..5a583ecb7 100644 --- a/tools/test_world_movement_parity.py +++ b/tools/test_world_movement_parity.py @@ -76,7 +76,7 @@ def main(): sources = [oracle, *helpers, Path(__file__), lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'tools/test_worldgen_parity.py', lab.ROOT/'tools/lab.py', lab.ROOT/'Cargo.toml', lab.ROOT/'Cargo.lock', - lab.ROOT/'crates/horizon-world/examples/registry_collision_scan_fixture.rs'] + lab.ROOT/'crates/horizon-world/examples/probe/registry_collision_scan_fixture.rs'] for crate in ['horizon-core', 'horizon-world']: sources += [lab.ROOT/'crates'/crate/'Cargo.toml', *sorted((lab.ROOT/'crates'/crate/'src').rglob('*.rs'))] @@ -106,10 +106,10 @@ def main(): fixture_paths = [build/name for name in ['inputs.txt', 'facts.json', 'definitions.json', 'block-registry.nbt', 'cached-collision.nbt', 'tags.json']] fixtures = base.source_hashes(fixture_paths) - run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'registry_collision_scan_fixture'], 'compile-rust') + run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'probe'], 'compile-rust') metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT)) - binary = Path(metadata['target_directory'])/'release/examples'/('registry_collision_scan_fixture.exe' if os.name=='nt' else 'registry_collision_scan_fixture') - run([binary, build], 'rust');references = [] + binary = Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary, 'registry_collision_scan_fixture', build], 'rust');references = [] for side, jar in jars.items(): java(side, side) matched = base.compare(build/(side+'.txt'), build/'rust.txt') diff --git a/tools/test_world_parity.py b/tools/test_world_parity.py index 802dc3884..e2781866e 100644 --- a/tools/test_world_parity.py +++ b/tools/test_world_parity.py @@ -51,12 +51,12 @@ def main(): print("Generating vanilla world-data fixtures...", flush=True) print(java("server", "generate").split("HORIZON_WORLD_GENERATED")[-1].strip(), flush=True) - run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "world_fixture"], base / "compile-rust.log") + run(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world", "--example", "probe"], base / "compile-rust.log") metadata = json.loads(run(["cargo", "metadata", "--no-deps", "--format-version", "1"])) target = Path(metadata["target_directory"]) / "release" suffix = ".exe" if os.name == "nt" else "" binary = target / ("horizon-world" + suffix) - run([target / "examples" / ("world_fixture" + suffix), base], base / "rust-fixture.log") + run([target / "examples" / ("probe" + suffix), "world_fixture", base], base / "rust-fixture.log") for network in [False, True]: kind = "network" if network else "nbt" output = base / "rust" / kind diff --git a/tools/test_world_ray_parity.py b/tools/test_world_ray_parity.py index 93f2dfcef..87189d611 100644 --- a/tools/test_world_ray_parity.py +++ b/tools/test_world_ray_parity.py @@ -49,7 +49,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldRayOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/world_ray_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/world_ray_fixture.rs'] tested_sources=base.source_hashes(sources) classes=build/'classes';classes.mkdir(exist_ok=True) def run(command,name): @@ -60,10 +60,10 @@ def main(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.VanillaWorldRayOracle',mode,path],side+'-'+mode) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(value,separators=(',',':'))+'\n' for value in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) - run(['cargo','build','--release','-p','horizon-world','--example','world_ray_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('world_ray_fixture.exe' if os.name=='nt' else 'world_ray_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'world_ray_fixture',build],'rust');references=[] for side,jar in jars.items(): java(side,side,build);reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt') references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(reference,'sha256'),'matched_output_lines':matched}) diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 4247a0ee7..f73da3a8c 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -79,7 +79,7 @@ def origins(build, classes, dependencies, all_seeds): vanilla_out = build / 'origins-vanilla.txt' oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle', vanilla_out, *all_seeds], build, 'origins-vanilla') - rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)], + rust = subprocess.run([target_dir() / 'examples/probe', 'spawn_origin', RESOURCES, *map(str, all_seeds)], capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout vanilla = vanilla_out.read_text() parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l} @@ -121,7 +121,7 @@ def main(): oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') - oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe') + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'probe'], build, 'compile-probe') all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() diff --git a/tools/test_worldgen_random_parity.py b/tools/test_worldgen_random_parity.py index 7b2d37a6f..29eedfa49 100644 --- a/tools/test_worldgen_random_parity.py +++ b/tools/test_worldgen_random_parity.py @@ -44,7 +44,7 @@ def main(): if args.prepare:lab.prepare() lock,jars,libraries=base.verify_artifacts() oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldgenRandomOracle.java' - sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/worldgen_random_fixture.rs'] + sources=[oracle,Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/lab.py',lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-core/Cargo.toml',lab.ROOT/'crates/horizon-world/Cargo.toml',*sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/probe/worldgen_random_fixture.rs'] tested_sources=base.source_hashes(sources) fixtures=list(corpus());inputs=build/'inputs.txt';inputs.write_text(''.join(json.dumps(f,separators=(',',':'))+'\n' for f in fixtures),encoding='utf-8') fixture_paths=[inputs];tested_fixtures=base.source_hashes(fixture_paths) @@ -53,10 +53,10 @@ def main(): with (build/(name+'.log')).open('w',encoding='utf-8') as log:base.run(list(map(str,command)),stdout=log,stderr=subprocess.STDOUT) dependency_path=os.pathsep.join(map(str,libraries)) run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-sourcepath',str(lab.ROOT/'mods/horizon/src/test/java'),'-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle],'compile-java') - run(['cargo','build','--release','-p','horizon-world','--example','worldgen_random_fixture'],'compile-rust') + run(['cargo','build','--release','-p','horizon-world','--example','probe'],'compile-rust') metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) - binary=Path(metadata['target_directory'])/'release/examples'/('worldgen_random_fixture.exe' if os.name=='nt' else 'worldgen_random_fixture') - run([binary,build],'rust');references=[] + binary=Path(metadata['target_directory'])/'release/examples'/('probe.exe' if os.name=='nt' else 'probe') + run([binary,'worldgen_random_fixture',build],'rust');references=[] for side,jar in jars.items(): run(['java','-Xmx512M','-cp',os.pathsep.join([str(classes),str(jar),dependency_path]),'dev.horizonlab.parity.VanillaWorldgenRandomOracle',side,build],side) reference=build/f'{side}.txt';matched=base.compare(reference,build/'rust.txt')