WIP: unfinished rendering-anim parity work, stopped for the night

Uncommitted changes the agent had in progress when it was stopped; may not
build or pass its harnesses yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 22:24:03 +02:00
parent 8ef3195457
commit 2012f8baad
5 changed files with 1453 additions and 0 deletions
@@ -0,0 +1,342 @@
//! Headless transport for the block-entity animation parity gate: replays each
//! scripted case (block, neighbourhood, entities, block events, game times)
//! through `horizon_client::block_entity_anim` and prints the same lines as
//! `VanillaBlockEntityAnimOracle`: the block entity's fields, the level calls
//! its tick made and the render state the renderer derives from `BlockAnim`.
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
block_entity_anim::{
Bell, BellEntity, BlockEntityAnims, Conduit, ConduitTarget, DIRECTIONS, PotWobble,
Shulker, ShulkerStatus, Skull, WobbleStyle, direction_index,
},
blocks::{BlockFacts, Fluid},
items::Items,
};
use horizon_core::random::LegacyRandom;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{
collections::HashMap,
fmt::Write as _,
fs,
io::{BufWriter, Write},
path::PathBuf,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn f(v: f32) -> String {
format!("{:08x}", v.to_bits())
}
fn d(v: f64) -> String {
format!("{:016x}", v.to_bits())
}
fn bx(b: [f64; 6]) -> String {
b.map(d).join(" ")
}
fn find_state(registry: &BlockRegistry, spec: &str) -> Option<u32> {
let (name, props) = match spec.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (spec, ""),
};
let wanted: Vec<(&str, &str)> = props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.collect();
let default = registry.state(registry.default_state(name)?)?.clone();
(0..registry.len() as u32).find(|&id| {
registry.state(BlockStateId(id)).is_some_and(|s| {
s.name == name
&& s.properties.iter().all(|(k, v)| {
wanted
.iter()
.find(|(wk, _)| wk == k)
.map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v)
})
})
})
}
fn prop<'a>(spec: &'a str, key: &str) -> Option<&'a str> {
let props = spec.split_once('[')?.1.trim_end_matches(']');
props
.split(',')
.filter_map(|p| p.split_once('='))
.find(|(k, _)| *k == key)
.map(|(_, v)| v)
}
fn offset(key: &str) -> [i32; 3] {
let mut it = key.split(',').map(|v| v.parse::<i32>().unwrap_or(0));
[
it.next().unwrap_or(0),
it.next().unwrap_or(0),
it.next().unwrap_or(0),
]
}
fn mob(e: &Value) -> BellEntity {
let p = |i: usize| e["pos"][i].as_f64().unwrap_or(0.0);
BellEntity {
position: [p(0), p(1), p(2)],
alive: e["alive"].as_bool().unwrap_or(true) && !e["removed"].as_bool().unwrap_or(false),
raider: e["raider"].as_bool().unwrap_or(false),
}
}
fn status(s: ShulkerStatus) -> &'static str {
match s {
ShulkerStatus::Closed => "CLOSED",
ShulkerStatus::Opening => "OPENING",
ShulkerStatus::Opened => "OPENED",
ShulkerStatus::Closing => "CLOSING",
}
}
fn main() -> Result<()> {
let args: Vec<PathBuf> = std::env::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());
};
let assets = Assets::load(root)?;
let registry = assets.registry;
let facts = BlockFacts::load(root, registry)?;
let tags = Items::tags_only(root)?;
let frames = tags
.block_tags
.get("minecraft:conduit_effect_block")
.cloned()
.unwrap_or_default();
let mut out = BufWriter::new(fs::File::create(output)?);
for line in fs::read_to_string(inputs)?
.lines()
.filter(|l| !l.is_empty())
{
let case: Value = serde_json::from_str(line)?;
writeln!(out, "case {}", case["name"].as_str().unwrap_or_default())?;
let block = case["block"].as_str().unwrap_or_default().to_owned();
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
let pos = [
int(&case["pos"][0]),
int(&case["pos"][1]),
int(&case["pos"][2]),
];
// The neighbourhood as block states (conduits).
let mut blocks: HashMap<[i32; 3], String> = HashMap::new();
blocks.insert(pos, block.clone());
let mut place = |blocks: &mut HashMap<[i32; 3], String>, set: &Value| {
for (k, v) in set.as_object().into_iter().flatten() {
let o = offset(k);
blocks.insert(
[pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]],
v.as_str().unwrap_or_default().to_owned(),
);
}
};
place(&mut blocks, &case["world"]);
let entities: Vec<BellEntity> = case["entities"]
.as_array()
.into_iter()
.flatten()
.map(mob)
.collect();
let target = case.get("target").map(|t| {
let e = mob(t);
ConduitTarget {
position: e.position,
eye_y: e.position[1] + f64::from(t["eye"].as_f64().unwrap_or(0.0) as f32),
width: t["width"].as_f64().unwrap_or(0.0) as f32,
height: t["height"].as_f64().unwrap_or(0.0) as f32,
}
});
let mut random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0));
let name = block.split('[').next().unwrap_or_default().to_owned();
let mut anims = BlockEntityAnims::default();
let facing = prop(&block, "facing").and_then(direction_index).unwrap_or(1);
let mut text = String::new();
for step in case["steps"].as_array().into_iter().flatten() {
let time = step["time"].as_i64().unwrap_or(0);
let partial = step["partial"].as_f64().unwrap_or(0.0) as f32;
let mut log = String::new();
place(&mut blocks, &step["set"]);
let event = step["event"].as_array().map(|e| (int(&e[0]), int(&e[1])));
text.clear();
if name.ends_with("shulker_box") {
let s = anims.shulkers.entry(pos).or_insert_with(Shulker::default);
if let Some((a, b)) = event {
let handled = s.trigger_event(a, b);
let _ = write!(log, " event {handled}");
}
let tick = s.tick(pos, facing);
for _ in 0..tick.neighbor_updates {
log.push_str(" neighbors");
}
if let Some(b) = tick.push {
let _ = write!(log, " push {}", bx(b));
}
let (count, st) = (s.open_count, s.status);
let a = anims.block_anim(pos, time, partial, Default::default());
// ShulkerBoxRenderer: getProgress(partial).
let (progress, old) = a.shulker;
let render = old + partial * (progress - old);
let s = &anims.shulkers[&pos];
let _ = write!(
text,
"{} {} {} {} render {}",
status(st),
count,
f(s.progress),
f(s.progress_old),
f(render)
);
} else if name == "minecraft:bell" {
let b = anims.bells.entry(pos).or_insert_with(Bell::default);
if let Some((e0, e1)) = event {
let handled = b.trigger_event(e0, e1, time, || {
let inflated = [
f64::from(pos[0]) - 48.0,
f64::from(pos[1]) - 48.0,
f64::from(pos[2]) - 48.0,
f64::from(pos[0]) + 1.0 + 48.0,
f64::from(pos[1]) + 1.0 + 48.0,
f64::from(pos[2]) + 1.0 + 48.0,
];
let _ = write!(log, " gather {}", bx(inflated));
(0..entities.len() as u64)
.filter(|&i| {
let p = entities[i as usize].position;
(0..3).all(|a| p[a] >= inflated[a] && p[a] < inflated[a + 3])
})
.collect()
});
let _ = write!(log, " event {handled}");
}
if !step["noTick"].as_bool().unwrap_or(false) {
let tick = b.tick(pos, |h| entities.get(h as usize).copied());
if tick.resonate {
log.push_str(" sound minecraft:block.bell.resonate");
}
if let Some((particles, _)) = tick.ended {
for (p, color) in particles {
let _ = write!(
log,
" particle minecraft:entity_effect {color} {} {} {} {} {} {}",
d(p[0]),
d(p[1]),
d(p[2]),
d(0.0),
d(0.0),
d(0.0)
);
}
}
}
let b = &anims.bells[&pos];
let a = anims.block_anim(pos, time, partial, Default::default());
let dir = |d: Option<&str>| d.map_or("null".to_owned(), str::to_owned);
let _ = write!(
text,
"{} {} {} {} {} {} render {} {}",
b.ticks,
b.shaking,
dir(b.click_direction.map(|d| DIRECTIONS[usize::from(d)])),
b.resonating,
b.resonation_ticks,
b.last_ring_timestamp,
f(a.bell_ticks as f32 + partial),
dir(a.bell_shake)
);
} else if name == "minecraft:conduit" {
let c = anims.conduits.entry(pos).or_insert_with(Conduit::default);
let state_of = |p: [i32; 3]| -> Option<u32> {
find_state(registry, blocks.get(&p).map_or("minecraft:air", String::as_str))
};
let is_water =
|p: [i32; 3]| state_of(p).is_some_and(|s| facts.get(s).fluid == Fluid::Water);
let is_frame = |p: [i32; 3]| {
let spec = blocks.get(&p).map_or("minecraft:air", String::as_str);
frames.contains(spec.split('[').next().unwrap_or_default())
};
let particles = c.client_tick(pos, time, is_water, is_frame, target, &mut random);
for (p, v) in particles {
let _ = write!(
log,
" particle minecraft:nautilus {} {} {} {} {} {}",
d(p[0]),
d(p[1]),
d(p[2]),
d(v[0]),
d(v[1]),
d(v[2])
);
}
let c = &anims.conduits[&pos];
let a = anims.block_anim(pos, time, partial, Default::default());
// ConduitRenderer.extractRenderState as block_entity_render derives it.
let (ticks, active, hunting, raw) = a.conduit;
let rotation = (raw + if active { partial } else { 0.0 }) * -0.0375;
let _ = write!(
text,
"{} {} {} {} {} render {} {} {} {} {}",
c.tick_count,
c.is_active,
c.is_hunting,
f(c.active_rotation),
c.effect_blocks.len(),
active,
f(rotation),
f(ticks as f32 + partial),
ticks / 66 % 3,
hunting
);
} else if name.ends_with("_head") || name.ends_with("_skull") {
let now = step["state"].as_str().unwrap_or(&block);
let s = anims.skulls.entry(pos).or_insert_with(Skull::default);
s.tick(prop(now, "powered") == Some("true"));
let s = anims.skulls[&pos];
let a = anims.block_anim(pos, time, partial, Default::default());
// block_entity_render: count + partial while animating.
let (animating, count) = a.skull;
let render = count as f32 + if animating { partial } else { 0.0 };
let _ = write!(
text,
"{} {} render {}",
s.animating,
s.tick_count,
f(render)
);
} else if name == "minecraft:decorated_pot" {
let w = anims.pots.entry(pos).or_insert_with(PotWobble::default);
if let Some((e0, e1)) = event {
let handled = w.trigger_event(e0, e1, time);
let _ = write!(log, " event {handled}");
}
let w = anims.pots[&pos];
let a = anims.block_anim(pos, time, partial, Default::default());
let (style, progress) = match a.wobble {
Some((true, p)) => ("POSITIVE", p),
Some((false, p)) => ("null", p),
None => ("null", 0.0),
};
let _ = write!(
text,
"{} {} render {} {}",
w.started_at,
match w.style {
Some(WobbleStyle::Positive) => "POSITIVE",
Some(WobbleStyle::Negative) => "NEGATIVE",
None => "null",
},
f(progress),
style
);
} else {
text = format!("unsupported {block}");
}
writeln!(out, "{text} |{log}")?;
}
}
Ok(())
}
@@ -0,0 +1,608 @@
//! Client-ticked block-entity animation state, as vanilla's block entities
//! keep it: `ShulkerBoxBlockEntity` (open count, animation status, progress),
//! `BellBlockEntity` (ring ticks, shake direction, resonation),
//! `ConduitBlockEntity.clientTick` (tick count, shape check, rotation,
//! hunting, nautilus particles), `SkullBlockEntity.animation` (powered dragon
//! and piglin heads) and `DecoratedPotBlockEntity` wobbles.
//!
//! [`BlockEntityAnims`] holds the state per position and turns it into the
//! renderer's [`BlockAnim`]. Its tick methods take what the level answers
//! (blocks, entities, game time) as closures, so the parity fixture can drive
//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`).
use crate::block_entity_render::BlockAnim;
use horizon_core::{
geometry::trig::Mth,
random::{LegacyRandom, RandomSource},
};
use std::collections::HashMap;
/// `Direction` names by `get3DDataValue`.
pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
fn step(direction: u8) -> [i32; 3] {
match direction {
0 => [0, -1, 0],
1 => [0, 1, 0],
2 => [0, 0, -1],
3 => [0, 0, 1],
4 => [-1, 0, 0],
_ => [1, 0, 0],
}
}
/// `Direction.from3DDataValue`: `BY_3D_DATA[Mth.abs(data % 6)]`.
pub fn from_3d_data_value(data: i32) -> u8 {
(data % 6).unsigned_abs() as u8
}
/// The 3D data value of a direction name.
pub fn direction_index(name: &str) -> Option<u8> {
DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8)
}
/// `ShulkerBoxBlockEntity.AnimationStatus`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ShulkerStatus {
#[default]
Closed,
Opening,
Opened,
Closing,
}
/// `ShulkerBoxBlockEntity` lid state.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Shulker {
pub open_count: i32,
pub status: ShulkerStatus,
pub progress: f32,
pub progress_old: f32,
}
/// Side effects of one [`Shulker::tick`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShulkerTick {
/// `doNeighborUpdates` calls (shape and neighbour updates around the box).
pub neighbor_updates: u32,
/// `moveCollidedEntities`: the swept lid box (min x, y, z, max x, y, z);
/// entities in it move out along the facing.
pub push: Option<[f64; 6]>,
}
/// `Shulker.getProgressDeltaAabb(size, direction, from, to, position)`.
pub fn progress_delta_aabb(
size: f32,
direction: u8,
from: f32,
to: f32,
position: [f64; 3],
) -> [f64; 6] {
let size_d = f64::from(size);
let mut b = [
-size_d * 0.5,
0.0,
-size_d * 0.5,
size_d * 0.5,
size_d,
size_d * 0.5,
];
let max = f64::from(from.max(to));
let min = f64::from(from.min(to));
let s = step(direction);
for axis in 0..3 {
// expandTowards
let a = f64::from(s[axis]) * max * size_d;
if a < 0.0 {
b[axis] += a;
} else if a > 0.0 {
b[axis + 3] += a;
}
}
for axis in 0..3 {
// contract
let a = -f64::from(s[axis]) * (1.0 + min) * size_d;
if a < 0.0 {
b[axis] -= a;
} else if a > 0.0 {
b[axis + 3] -= a;
}
}
// new AABB keeps min <= max; then move to the position.
let mut out = [0.0; 6];
for axis in 0..3 {
out[axis] = b[axis].min(b[axis + 3]) + position[axis];
out[axis + 3] = b[axis].max(b[axis + 3]) + position[axis];
}
out
}
impl Shulker {
/// `triggerEvent(1, openCount)`.
pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool {
if b0 != 1 {
return false;
}
self.open_count = b1;
if b1 == 0 {
self.status = ShulkerStatus::Closing;
}
if b1 == 1 {
self.status = ShulkerStatus::Opening;
}
true
}
/// `startOpen`/`stopOpen` for a non-spectator user: the new open count to
/// send as block event 1, and whether this was the first opener (open) or
/// the last closer (close), which play the sound and game event.
pub fn start_open(&mut self) -> (i32, bool) {
if self.open_count < 0 {
self.open_count = 0;
}
self.open_count += 1;
(self.open_count, self.open_count == 1)
}
pub fn stop_open(&mut self) -> (i32, bool) {
self.open_count -= 1;
(self.open_count, self.open_count <= 0)
}
/// `updateAnimation` (`ShulkerBoxBlockEntity.tick`); `facing` is the
/// block's facing as a 3D data value.
pub fn tick(&mut self, pos: [i32; 3], facing: u8) -> ShulkerTick {
let mut out = ShulkerTick::default();
self.progress_old = self.progress;
match self.status {
ShulkerStatus::Closed => self.progress = 0.0,
ShulkerStatus::Opening => {
self.progress += 0.1;
if self.progress_old == 0.0 {
out.neighbor_updates += 1;
}
if self.progress >= 1.0 {
self.status = ShulkerStatus::Opened;
self.progress = 1.0;
out.neighbor_updates += 1;
}
let bottom = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
out.push = Some(progress_delta_aabb(
1.0,
facing,
self.progress_old,
self.progress,
bottom,
));
}
ShulkerStatus::Opened => self.progress = 1.0,
ShulkerStatus::Closing => {
self.progress -= 0.1;
if self.progress_old == 1.0 {
out.neighbor_updates += 1;
}
if self.progress <= 0.0 {
self.status = ShulkerStatus::Closed;
self.progress = 0.0;
out.neighbor_updates += 1;
}
}
}
out
}
/// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`.
pub fn get_progress(&self, a: f32) -> f32 {
self.progress_old + a * (self.progress - self.progress_old)
}
/// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room
/// (`level.noCollision` of the half-block lid box, deflated by 1e-6).
pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] {
let bottom = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
let mut b = progress_delta_aabb(1.0, facing, 0.0, 0.5, bottom);
for axis in 0..3 {
b[axis] += 1.0e-6;
b[axis + 3] -= 1.0e-6;
}
b
}
}
/// What the bell's tick asks about an entity it gathered when rung.
#[derive(Clone, Copy, Debug)]
pub struct BellEntity {
pub position: [f64; 3],
/// `isAlive() && !isRemoved()`.
pub alive: bool,
/// In `EntityTypeTags.RAIDERS`.
pub raider: bool,
}
/// `BellBlockEntity`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Bell {
pub ticks: i32,
pub shaking: bool,
/// `clickDirection` as a 3D data value.
pub click_direction: Option<u8>,
pub last_ring_timestamp: i64,
/// `nearbyEntities`: the living entities around the bell when it was last
/// gathered, as caller-defined handles.
pub nearby: Option<Vec<u64>>,
pub resonating: bool,
pub resonation_ticks: i32,
}
/// Side effects of one [`Bell::tick`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BellTick {
/// Resonation started: `BELL_RESONATE` (played by the server).
pub resonate: bool,
/// Resonation ended (`ResonationEndAction`): the client's
/// `showBellParticles` entity-effect particles (position and colour) and
/// the server's `makeRaidersGlow` targets.
pub ended: Option<(Vec<([f64; 3], i32)>, Vec<u64>)>,
}
fn closer_to_center_than(pos: [i32; 3], p: [f64; 3], distance: f64) -> bool {
let dx = f64::from(pos[0]) + 0.5 - p[0];
let dy = f64::from(pos[1]) + 0.5 - p[1];
let dz = f64::from(pos[2]) + 0.5 - p[2];
dx * dx + dy * dy + dz * dz < distance * distance
}
impl Bell {
/// `triggerEvent(1, direction)`. `gather` lists the living entities whose
/// position is inside the bell's block box inflated by 48
/// (`updateEntities`, refreshed at most every 60 ticks).
pub fn trigger_event(
&mut self,
b0: i32,
b1: i32,
game_time: i64,
gather: impl FnOnce() -> Vec<u64>,
) -> bool {
if b0 != 1 {
return false;
}
if game_time > self.last_ring_timestamp + 60 || self.nearby.is_none() {
self.last_ring_timestamp = game_time;
self.nearby = Some(gather());
}
self.resonation_ticks = 0;
self.click_direction = Some(from_3d_data_value(b1));
self.ticks = 0;
self.shaking = true;
true
}
/// `BellBlockEntity.tick` with the client's resonation end action.
pub fn tick(&mut self, pos: [i32; 3], entity: impl Fn(u64) -> Option<BellEntity>) -> BellTick {
let mut out = BellTick::default();
if self.shaking {
self.ticks += 1;
}
if self.ticks >= 50 {
self.shaking = false;
self.ticks = 0;
}
let nearby = self.nearby.clone().unwrap_or_default();
let raider_in = |e: &BellEntity, distance: f64| {
e.alive && closer_to_center_than(pos, e.position, distance) && e.raider
};
if self.ticks >= 5
&& self.resonation_ticks == 0
&& nearby
.iter()
.filter_map(|&h| entity(h))
.any(|e| raider_in(&e, 32.0))
{
self.resonating = true;
out.resonate = true;
}
if self.resonating {
if self.resonation_ticks < 40 {
self.resonation_ticks += 1;
} else {
// showBellParticles / makeRaidersGlow.
let mut color = 16_700_985;
let views: Vec<(u64, BellEntity)> = nearby
.iter()
.filter_map(|&h| Some((h, entity(h)?)))
.collect();
let count = views
.iter()
.filter(|(_, e)| closer_to_center_than(pos, e.position, 48.0))
.count() as i32;
let per = ((count - 21) / -2).clamp(3, 15);
let mut particles = Vec::new();
let mut glow = Vec::new();
for (h, e) in &views {
if !raider_in(e, 48.0) {
continue;
}
glow.push(*h);
let (bx, bz) = (f64::from(pos[0]), f64::from(pos[2]));
let dist = ((e.position[0] - bx) * (e.position[0] - bx)
+ (e.position[2] - bz) * (e.position[2] - bz))
.sqrt();
let x3 = bx + f64::from(0.5f32) + 1.0 / dist * (e.position[0] - bx);
let z3 = bz + f64::from(0.5f32) + 1.0 / dist * (e.position[2] - bz);
for _ in 0..per {
color += 5;
particles.push(([x3, f64::from(pos[1]) + 0.5, z3], color));
}
}
out.ended = Some((particles, glow));
self.resonating = false;
}
}
out
}
}
/// The conduit's `destroyTarget` as the client sees it.
#[derive(Clone, Copy, Debug)]
pub struct ConduitTarget {
pub position: [f64; 3],
pub eye_y: f64,
pub width: f32,
pub height: f32,
}
/// `ConduitBlockEntity` (client side).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Conduit {
pub tick_count: i32,
pub active_rotation: f32,
pub is_active: bool,
pub is_hunting: bool,
pub effect_blocks: Vec<[i32; 3]>,
}
/// One nautilus particle: position and velocity.
pub type Particle = ([f64; 3], [f64; 3]);
impl Conduit {
/// `updateShape`: water all around, then the frame blocks
/// (`BlockTags.CONDUIT_EFFECT_BLOCK`) in the three 5x5 rings.
fn update_shape(
&mut self,
pos: [i32; 3],
is_water: &impl Fn([i32; 3]) -> bool,
is_frame: &impl Fn([i32; 3]) -> bool,
) -> bool {
self.effect_blocks.clear();
for ox in -1..=1 {
for oy in -1..=1 {
for oz in -1..=1 {
if !is_water([pos[0] + ox, pos[1] + oy, pos[2] + oz]) {
return false;
}
}
}
}
for ox in -2i32..=2 {
for oy in -2i32..=2 {
for oz in -2i32..=2 {
let (ax, ay, az) = (ox.abs(), oy.abs(), oz.abs());
if (ax > 1 || ay > 1 || az > 1)
&& (ox == 0 && (ay == 2 || az == 2)
|| oy == 0 && (ax == 2 || az == 2)
|| oz == 0 && (ax == 2 || ay == 2))
{
let p = [pos[0] + ox, pos[1] + oy, pos[2] + oz];
if is_frame(p) {
self.effect_blocks.push(p);
}
}
}
}
}
self.effect_blocks.len() >= 16
}
/// `ConduitBlockEntity.clientTick`: returns the nautilus particles of
/// `animationTick`, drawn from the client level's random.
pub fn client_tick(
&mut self,
pos: [i32; 3],
game_time: i64,
is_water: impl Fn([i32; 3]) -> bool,
is_frame: impl Fn([i32; 3]) -> bool,
target: Option<ConduitTarget>,
random: &mut impl RandomSource,
) -> Vec<Particle> {
self.tick_count += 1;
if game_time % 40 == 0 {
self.is_active = self.update_shape(pos, &is_water, &is_frame);
self.is_hunting = self.effect_blocks.len() >= 42;
}
let particles = self.animation_tick(pos, target, random);
if self.is_active {
self.active_rotation += 1.0;
}
particles
}
fn animation_tick(
&self,
pos: [i32; 3],
target: Option<ConduitTarget>,
random: &mut impl RandomSource,
) -> Vec<Particle> {
let mut out = Vec::new();
let hh = f64::from(((self.tick_count + 35) as f32 * 0.1).msin() / 2.0 + 0.5);
let hh = (hh * hh + hh) * f64::from(0.3f32);
let end = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 1.5 + hh,
f64::from(pos[2]) + 0.5,
];
for p in &self.effect_blocks {
if random.next_int_bound(50).unwrap_or(1) == 0 {
let dx = -0.5 + random.next_float() + (p[0] - pos[0]) as f32;
let dy = -2.0 + random.next_float() + (p[1] - pos[1]) as f32;
let dz = -0.5 + random.next_float() + (p[2] - pos[2]) as f32;
out.push((end, [f64::from(dx), f64::from(dy), f64::from(dz)]));
}
}
if let Some(t) = target {
let randx = (-0.5 + random.next_float()) * (3.0 + t.width);
let randy = -1.0 + random.next_float() * t.height;
let randz = (-0.5 + random.next_float()) * (3.0 + t.width);
out.push((
[t.position[0], t.eye_y, t.position[2]],
[f64::from(randx), f64::from(randy), f64::from(randz)],
));
}
out
}
}
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Skull {
pub animating: bool,
pub tick_count: i32,
}
impl Skull {
/// `SkullBlockEntity.animation`.
pub fn tick(&mut self, powered: bool) {
if powered {
self.animating = true;
self.tick_count += 1;
} else {
self.animating = false;
}
}
/// `getAnimation(a)`.
pub fn get_animation(&self, a: f32) -> f32 {
if self.animating {
self.tick_count as f32 + a
} else {
self.tick_count as f32
}
}
}
/// `DecoratedPotBlockEntity.WobbleStyle`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WobbleStyle {
Positive,
Negative,
}
impl WobbleStyle {
pub fn duration(self) -> i32 {
match self {
Self::Positive => 7,
Self::Negative => 10,
}
}
}
/// `DecoratedPotBlockEntity` wobble fields.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PotWobble {
pub started_at: i64,
pub style: Option<WobbleStyle>,
}
impl PotWobble {
/// `triggerEvent(1, style)`.
pub fn trigger_event(&mut self, event: i32, data: i32, game_time: i64) -> bool {
if event == 1 && (0..2).contains(&data) {
self.started_at = game_time;
self.style = Some(if data == 0 {
WobbleStyle::Positive
} else {
WobbleStyle::Negative
});
true
} else {
false
}
}
/// `DecoratedPotRenderer.extractRenderState`'s `wobbleProgress`.
pub fn progress(&self, game_time: i64, partial: f32) -> f32 {
match self.style {
Some(style) => {
((game_time - self.started_at) as f32 + partial) / style.duration() as f32
}
None => 0.0,
}
}
}
/// The animated block entities of a level, by position.
#[derive(Clone, Debug)]
pub struct BlockEntityAnims {
pub shulkers: HashMap<[i32; 3], Shulker>,
pub bells: HashMap<[i32; 3], Bell>,
pub conduits: HashMap<[i32; 3], Conduit>,
pub skulls: HashMap<[i32; 3], Skull>,
pub pots: HashMap<[i32; 3], PotWobble>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
}
impl Default for BlockEntityAnims {
fn default() -> Self {
Self {
shulkers: HashMap::new(),
bells: HashMap::new(),
conduits: HashMap::new(),
skulls: HashMap::new(),
pots: HashMap::new(),
random: LegacyRandom::new(0x6c6576656c),
}
}
}
impl BlockEntityAnims {
/// Drops the state of positions whose block entity is gone.
pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) {
self.shulkers.retain(|p, _| keep(*p));
self.bells.retain(|p, _| keep(*p));
self.conduits.retain(|p, _| keep(*p));
self.skulls.retain(|p, _| keep(*p));
self.pots.retain(|p, _| keep(*p));
}
/// The renderer's view of the block entity at `pos`; `sherds` are the
/// pot's decorations (back, left, right, front), when it is a pot.
pub fn block_anim(
&self,
pos: [i32; 3],
game_time: i64,
partial: f32,
sherds: [Option<String>; 4],
) -> BlockAnim {
let mut anim = BlockAnim {
sherds,
..BlockAnim::default()
};
if let Some(s) = self.shulkers.get(&pos) {
anim.shulker = (s.progress, s.progress_old);
}
if let Some(b) = self.bells.get(&pos) {
anim.bell_ticks = b.ticks;
anim.bell_shake = b
.shaking
.then_some(b.click_direction)
.flatten()
.map(|d| DIRECTIONS[usize::from(d)]);
}
if let Some(c) = self.conduits.get(&pos) {
anim.conduit = (c.tick_count, c.is_active, c.is_hunting, c.active_rotation);
}
if let Some(s) = self.skulls.get(&pos) {
anim.skull = (s.animating, s.tick_count);
}
if let Some(w) = self.pots.get(&pos)
&& w.style.is_some()
{
// extractRenderState never copies lastWobbleStyle into the render
// state, so DecoratedPotRenderer.submit always takes the
// non-POSITIVE branch (with the style's own duration).
anim.wobble = Some((false, w.progress(game_time, partial)));
}
anim
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod attribute_updates;
pub mod audio;
pub mod banner;
pub mod biome;
pub mod block_entity_anim;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
@@ -0,0 +1,264 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.Predicate;
import net.minecraft.client.renderer.blockentity.*;
import net.minecraft.client.renderer.blockentity.state.*;
import net.minecraft.commands.arguments.blocks.BlockStateParser;
import net.minecraft.core.*;
import net.minecraft.core.particles.ColorParticleOption;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.*;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.entity.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.*;
/**
* Original oracle for the client-ticked animation state of shulker boxes,
* bells, conduits, skulls and decorated pots. Each case builds the real
* vanilla block entity on a stand-in client level (scripted blocks, entities,
* game time and a seeded LegacyRandomSource), then per step applies the
* scripted block event (triggerEvent), runs the block entity's own client
* ticker (ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick,
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none)
* and runs the real renderer's extractRenderState at the step's partial tick.
* It prints the block entity's fields, the level calls the tick made
* (neighbour updates, entity queries, sounds, particles) and the render state.
*
* Usage: VanillaBlockEntityAnimOracle inputs.jsonl output.txt
*/
public final class VanillaBlockEntityAnimOracle {
static Object unsafe;
static Method allocate, putObject, objectFieldOffset;
@SuppressWarnings("unchecked")
static <T> T make(Class<T> type) throws Exception { return (T) allocate.invoke(unsafe, type); }
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
long offset = (long) objectFieldOffset.invoke(unsafe, f);
putObject.invoke(unsafe, target, offset, value);
}
static Field field(Class<?> owner, String name) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f;
}
static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); }
static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); }
static String box(AABB b) { return d(b.minX) + " " + d(b.minY) + " " + d(b.minZ) + " " + d(b.maxX) + " " + d(b.maxY) + " " + d(b.maxZ); }
static BlockState parse(String s) throws Exception {
return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, s, false).blockState();
}
/** A living entity the case places: a Pillager whose type field says raider or not. */
static final class Mob extends net.minecraft.world.entity.monster.illager.Pillager {
boolean living;
Mob() { super(null, null); }
@Override public boolean isAlive() { return !this.isRemoved() && this.living; }
}
/** The stand-in client level. */
static final class World extends Level {
World() { super(null, null, null, null, false, false, 0L, 0); }
long time;
Map<BlockPos, BlockState> blocks = new HashMap<>();
List<Mob> mobs = new ArrayList<>();
RandomSource random;
StringBuilder log = new StringBuilder();
@Override public long getGameTime() { return time; }
@Override public boolean isClientSide() { return true; }
@Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); }
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
@Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; }
@Override public RandomSource getRandom() { return random; }
@Override public void updateNeighborsAt(BlockPos p, Block block) { log.append(" neighbors"); }
@Override public void neighborShapeChanged(Direction dir, BlockPos p, BlockPos from, BlockState state, int flags, int limit) {}
@Override public List<Entity> getEntities(Entity except, AABB bb) { log.append(" push ").append(box(bb)); return List.of(); }
@SuppressWarnings("unchecked")
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB bb, Predicate<? super T> selector) {
log.append(" gather ").append(box(bb));
List<T> out = new ArrayList<>();
for (Mob m : mobs) if (type.isInstance(m) && bb.contains(m.position())) out.add((T) m);
return out;
}
@Override public void playSound(Entity except, BlockPos p, SoundEvent s, SoundSource source, float volume, float pitch) {
log.append(" sound ").append(BuiltInRegistries.SOUND_EVENT.getKey(s));
}
@Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
log.append(" particle ").append(BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()));
if (o instanceof ColorParticleOption c) {
try { log.append(" ").append(field(ColorParticleOption.class, "color").getInt(c)); } catch (Exception e) { throw new RuntimeException(e); }
}
log.append(" ").append(d(x)).append(" ").append(d(y)).append(" ").append(d(z))
.append(" ").append(d(xd)).append(" ").append(d(yd)).append(" ").append(d(zd));
}
@Override public net.minecraft.world.clock.ClockManager clockManager(){throw new UnsupportedOperationException();}
@Override public void destroyBlockProgress(int p0,net.minecraft.core.BlockPos p1,int p2){throw new UnsupportedOperationException();}
@Override public java.util.Collection dragonParts(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){throw new UnsupportedOperationException();}
@Override public void explode(net.minecraft.world.entity.Entity p0,net.minecraft.world.damagesource.DamageSource p1,net.minecraft.world.level.ExplosionDamageCalculator p2,double p3,double p4,double p5,float p6,boolean p7,net.minecraft.world.level.Level.ExplosionInteraction p8,net.minecraft.core.particles.ParticleOptions p9,net.minecraft.core.particles.ParticleOptions p10,net.minecraft.util.random.WeightedList p11,net.minecraft.core.Holder p12){throw new UnsupportedOperationException();}
@Override public void gameEvent(net.minecraft.core.Holder p0,net.minecraft.world.phys.Vec3 p1,net.minecraft.world.level.gameevent.GameEvent.Context p2){throw new UnsupportedOperationException();}
@Override public java.lang.String gatherChunkSourceStats(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.ticks.LevelTickAccess getBlockTicks(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.chunk.ChunkSource getChunkSource(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.entity.LevelEntityGetter getEntities(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.entity.Entity getEntity(int p0){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.ticks.LevelTickAccess getFluidTicks(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId p0){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.scores.Scoreboard getScoreboard(){throw new UnsupportedOperationException();}
@Override public int getSeaLevel(){throw new UnsupportedOperationException();}
@Override public net.minecraft.core.Holder getUncachedNoiseBiome(int p0,int p1,int p2){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder(){throw new UnsupportedOperationException();}
@Override public void levelEvent(net.minecraft.world.entity.Entity p0,int p1,net.minecraft.core.BlockPos p2,int p3){throw new UnsupportedOperationException();}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,net.minecraft.world.entity.Entity p1,net.minecraft.core.Holder p2,net.minecraft.sounds.SoundSource p3,float p4,float p5,long p6){throw new UnsupportedOperationException();}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,double p1,double p2,double p3,net.minecraft.core.Holder p4,net.minecraft.sounds.SoundSource p5,float p6,float p7,long p8){throw new UnsupportedOperationException();}
@Override public java.util.List players(){throw new UnsupportedOperationException();}
@Override public net.minecraft.world.item.crafting.RecipeAccess recipeAccess(){throw new UnsupportedOperationException();}
@Override public void sendBlockUpdated(net.minecraft.core.BlockPos p0,net.minecraft.world.level.block.state.BlockState p1,net.minecraft.world.level.block.state.BlockState p2,int p3){throw new UnsupportedOperationException();}
@Override public void setRespawnData(net.minecraft.world.level.storage.LevelData.RespawnData p0){throw new UnsupportedOperationException();}
}
static Mob mob(JsonObject e, World world) throws Exception {
Mob m = make(Mob.class);
m.living = !e.has("alive") || e.get("alive").getAsBoolean();
put(m, Entity.class, "type", e.has("raider") && e.get("raider").getAsBoolean() ? EntityType.PILLAGER : EntityType.COW);
var p = e.getAsJsonArray("pos");
put(m, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble()));
if (e.has("removed") && e.get("removed").getAsBoolean()) put(m, Entity.class, "removalReason", Entity.RemovalReason.KILLED);
if (e.has("width")) {
put(m, Entity.class, "dimensions", EntityDimensions.scalable(e.get("width").getAsFloat(), e.get("height").getAsFloat()));
Field eye = field(Entity.class, "eyeHeight");
eye.setFloat(m, e.get("eye").getAsFloat());
}
return m;
}
static String run(JsonObject c) throws Exception {
World world = make(World.class);
world.blocks = new HashMap<>();
world.mobs = new ArrayList<>();
world.log = new StringBuilder();
world.random = RandomSource.create(c.has("seed") ? c.get("seed").getAsLong() : 0L);
var pa = c.getAsJsonArray("pos");
BlockPos pos = new BlockPos(pa.get(0).getAsInt(), pa.get(1).getAsInt(), pa.get(2).getAsInt());
BlockState state = parse(c.get("block").getAsString());
world.blocks.put(pos, state);
if (c.has("world")) {
for (var e : c.getAsJsonObject("world").entrySet()) {
String[] xyz = e.getKey().split(",");
world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString()));
}
}
if (c.has("entities")) for (var e : c.getAsJsonArray("entities")) world.mobs.add(mob(e.getAsJsonObject(), world));
var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
be.setLevel(world);
if (c.has("target") && be instanceof ConduitBlockEntity) {
put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world)));
}
StringBuilder out = new StringBuilder();
for (var stepElement : c.getAsJsonArray("steps")) {
var step = stepElement.getAsJsonObject();
world.time = step.get("time").getAsLong();
world.log.setLength(0);
if (step.has("set")) {
for (var e : step.getAsJsonObject("set").entrySet()) {
String[] xyz = e.getKey().split(",");
world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString()));
}
}
if (step.has("event")) {
var ev = step.getAsJsonArray("event");
boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt());
world.log.append(" event ").append(handled);
}
float partial = step.get("partial").getAsFloat();
String fields;
if (be instanceof ShulkerBoxBlockEntity s) {
ShulkerBoxBlockEntity.tick(world, pos, state, s);
var r = make(ShulkerBoxRenderer.class).createRenderState();
make(ShulkerBoxRenderer.class).extractRenderState(s, r, partial, Vec3.ZERO, null);
fields = s.getAnimationStatus() + " " + field(ShulkerBoxBlockEntity.class, "openCount").getInt(s)
+ " " + f(field(ShulkerBoxBlockEntity.class, "progress").getFloat(s))
+ " " + f(field(ShulkerBoxBlockEntity.class, "progressOld").getFloat(s))
+ " render " + f(r.progress);
} else if (be instanceof BellBlockEntity b) {
if (!step.has("noTick")) BellBlockEntity.clientTick(world, pos, state, b);
var r = make(BellRenderer.class).createRenderState();
make(BellRenderer.class).extractRenderState(b, r, partial, Vec3.ZERO, null);
fields = b.ticks + " " + b.shaking + " " + b.clickDirection
+ " " + field(BellBlockEntity.class, "resonating").getBoolean(b)
+ " " + field(BellBlockEntity.class, "resonationTicks").getInt(b)
+ " " + field(BellBlockEntity.class, "lastRingTimestamp").getLong(b)
+ " render " + f(r.ticks) + " " + r.shakeDirection;
} else if (be instanceof ConduitBlockEntity k) {
ConduitBlockEntity.clientTick(world, pos, state, k);
var r = make(ConduitRenderer.class).createRenderState();
make(ConduitRenderer.class).extractRenderState(k, r, partial, Vec3.ZERO, null);
@SuppressWarnings("unchecked")
var effect = (List<BlockPos>) field(ConduitBlockEntity.class, "effectBlocks").get(k);
fields = k.tickCount + " " + k.isActive() + " " + k.isHunting()
+ " " + f(field(ConduitBlockEntity.class, "activeRotation").getFloat(k)) + " " + effect.size()
+ " render " + r.isActive + " " + f(r.activeRotation) + " " + f(r.animTime) + " " + r.animationPhase + " " + r.isHunting;
} else if (be instanceof SkullBlockEntity k) {
BlockState now = step.has("state") ? parse(step.get("state").getAsString()) : state;
SkullBlockEntity.animation(world, pos, now, k);
fields = field(SkullBlockEntity.class, "isAnimating").getBoolean(k)
+ " " + field(SkullBlockEntity.class, "animationTickCount").getInt(k)
+ " render " + f(k.getAnimation(partial));
} else if (be instanceof DecoratedPotBlockEntity p) {
var r = make(DecoratedPotRenderer.class).createRenderState();
make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null);
fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle
+ " render " + f(r.wobbleProgress) + " " + r.wobbleStyle;
} else {
throw new IllegalArgumentException("no animation for " + be);
}
out.append(fields).append(" |").append(world.log).append('\n');
}
return out.toString();
}
public static void main(String[] args) throws Exception {
ParityData.init();
var allocator = Class.forName("sun.misc.Unsafe");
var theUnsafe = allocator.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = theUnsafe.get(null);
allocate = allocator.getMethod("allocateInstance", Class.class);
putObject = allocator.getMethod("putObject", Object.class, long.class, Object.class);
objectFieldOffset = allocator.getMethod("objectFieldOffset", Field.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
var lines = Files.lines(Path.of(args[0]))) {
for (String line : (Iterable<String>) lines::iterator) {
var c = JsonParser.parseString(line).getAsJsonObject();
String result;
try {
result = run(c);
} catch (Throwable t) {
result = "error " + t + "\n";
}
out.print("case " + c.get("name").getAsString() + "\n" + result);
}
}
}
}
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""Compare client-ticked block-entity animation with the vanilla 26.3 block entities.
The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla
block entity (shulker box, bell, conduit, dragon/piglin head, decorated pot)
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
`horizon_client::block_entity_anim` and derives the render state from the
`BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits).
test_block_entity_anim_parity.py [--filter SUBSTRING] [--detail N]
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
HORIZONTAL = ['north', 'south', 'west', 'east']
ALL = ['down', 'up'] + HORIZONTAL
FRAME = ['minecraft:prismarine', 'minecraft:prismarine_bricks', 'minecraft:sea_lantern', 'minecraft:dark_prismarine']
WATERY = ['minecraft:water', 'minecraft:water[level=3]', 'minecraft:bubble_column', 'minecraft:seagrass',
'minecraft:kelp_plant', 'minecraft:oak_slab[waterlogged=true]', 'minecraft:oak_stairs[waterlogged=true]']
DRY = ['minecraft:air', 'minecraft:stone', 'minecraft:lava', 'minecraft:oak_slab', 'minecraft:ice']
def frame_offsets():
out = []
for ox in range(-2, 3):
for oy in range(-2, 3):
for oz in range(-2, 3):
ax, ay, az = abs(ox), abs(oy), abs(oz)
if (ax > 1 or ay > 1 or az > 1) and (ox == 0 and (ay == 2 or az == 2) or oy == 0 and (ax == 2 or az == 2)
or oz == 0 and (ax == 2 or ay == 2)):
out.append((ox, oy, oz))
return out
def cases():
rng = random.Random(0x414e494d)
out = []
def pos():
return [rng.randint(-3000, 3000), rng.randint(-60, 300), rng.randint(-3000, 3000)]
def add(kind, block, steps, **extra):
case = {'name': f'{kind}-{len(out)}', 'block': block, 'pos': pos(), 'steps': steps}
case.update(extra)
out.append(case)
def times(n, start=None, gaps=(1,)):
t = rng.randint(-100, 10 ** 7) if start is None else start
result = []
for _ in range(n):
result.append(t)
t += rng.choice(gaps)
return result
# Shulker boxes: players open and close (open counts from startOpen/stopOpen), other events ignored.
for i in range(48):
color = rng.choice(['', 'white_', 'purple_', 'black_'])
block = f'minecraft:{color}shulker_box[facing={rng.choice(ALL)}]'
steps, count = [], 0
for t in times(rng.randint(20, 70)):
step = {'time': t, 'partial': round(rng.random(), 4)}
r = rng.random()
if r < 0.12:
count = max(count, 0) + 1
step['event'] = [1, count]
elif r < 0.22:
count -= 1
step['event'] = [1, count]
elif r < 0.25:
step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)]
steps.append(step)
add('shulker', block, steps)
# Bells: rings from any side (and odd data values), raiders and other mobs nearby.
for i in range(40):
attach = rng.choice(['floor', 'ceiling', 'single_wall', 'double_wall'])
block = f'minecraft:bell[attachment={attach},facing={rng.choice(HORIZONTAL)}]'
p = pos()
entities = []
for _ in range(rng.choice([0, 1, 2, 5, 12, 25])):
spread = rng.choice([10, 33, 50, 70])
entities.append({'pos': [p[k] + 0.5 + rng.uniform(-spread, spread) for k in range(3)],
'raider': rng.random() < 0.5, 'alive': rng.random() < 0.85, 'removed': rng.random() < 0.08})
steps = []
start = rng.randint(-50, 10 ** 6)
for k, t in enumerate(times(rng.randint(60, 180), start)):
step = {'time': t, 'partial': round(rng.random(), 4)}
if (k == 2 or rng.random() < 0.05) and k < 150:
step['event'] = [1 if rng.random() < 0.93 else 2, rng.choice([0, 1, 2, 3, 4, 5, 2, 3, 4, 5, 7, -3, 11])]
steps.append(step)
case = {'name': f'bell-{len(out)}', 'block': block, 'pos': p, 'steps': steps, 'entities': entities}
out.append(case)
# Conduits: water around, prismarine frames of various sizes, frames changing over time.
rings = frame_offsets()
for i in range(36):
world = {}
water = rng.random()
for ox in range(-1, 2):
for oy in range(-1, 2):
for oz in range(-1, 2):
if (ox, oy, oz) != (0, 0, 0):
world[f'{ox},{oy},{oz}'] = rng.choice(WATERY) if rng.random() < 0.97 or water < 0.5 else rng.choice(DRY)
size = rng.choice([0, 10, 15, 16, 20, 30, 41, 42, 42])
for o in rng.sample(rings, size):
world['%d,%d,%d' % o] = rng.choice(FRAME)
steps = []
for t in times(rng.randint(60, 140), gaps=(1, 1, 1, 2, 7)):
step = {'time': t, 'partial': round(rng.random(), 4)}
if rng.random() < 0.04:
o = rng.choice(rings)
step['set'] = {'%d,%d,%d' % o: rng.choice(FRAME + DRY)}
steps.append(step)
waterlogged = 'true' if rng.random() < 0.9 else 'false'
extra = {'world': world, 'seed': rng.randint(0, 2 ** 40)}
if rng.random() < 0.3:
extra['target'] = {'pos': [rng.uniform(-8, 8) for _ in range(3)], 'width': round(rng.uniform(0.3, 2), 3),
'height': round(rng.uniform(0.5, 3), 3), 'eye': round(rng.uniform(0.2, 2.5), 3)}
add('conduit', f'minecraft:conduit[waterlogged={waterlogged}]', steps, **extra)
# Dragon and piglin heads powered on and off.
for i in range(24):
head = rng.choice(['dragon', 'piglin'])
wall = rng.random() < 0.5
prop = f'facing={rng.choice(HORIZONTAL)}' if wall else f'rotation={rng.randint(0, 15)}'
name = f'minecraft:{head}_wall_head' if wall else f'minecraft:{head}_head'
powered = rng.random() < 0.5
steps = []
for t in times(rng.randint(20, 90)):
if rng.random() < 0.1:
powered = not powered
steps.append({'time': t, 'partial': round(rng.random(), 4),
'state': f'{name}[{prop},powered={str(powered).lower()}]'})
add('skull', f'{name}[{prop},powered=false]', steps)
# Decorated pots wobbling (insert: POSITIVE, fail: NEGATIVE) and invalid events.
for i in range(24):
steps = []
for t in times(rng.randint(20, 60), gaps=(0, 1, 1, 1, 3)):
step = {'time': t, 'partial': round(rng.random(), 4)}
if rng.random() < 0.15:
step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])]
steps.append(step)
add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps)
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--filter', default='')
parser.add_argument('--detail', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-block-entity-anim-parity'
build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
chosen = [c for c in cases() if args.filter in c['name']]
inputs = build / 'inputs.jsonl'
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
classes = build / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:])
sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(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')
def split(path):
result, current = {}, None
for line in path.read_text().splitlines():
if line.startswith('case '):
current = line[5:]
result[current] = []
else:
result[current].append(line)
return result
vanilla, rust = split(build / 'vanilla.txt'), split(build / 'rust.txt')
kinds, failures, errors, steps = {}, {}, {}, 0
for case in chosen:
name = case['name']
kind = name.split('-')[0]
v, r = vanilla.get(name, []), rust.get(name, [])
total = kinds.setdefault(kind, [0, 0])
total[1] += 1
if v and v[0].startswith('error'):
errors.setdefault(kind, v[0])
continue
steps += len(v)
bad = next((i for i, (a, b) in enumerate(zip(v, r)) if a != b), None)
if bad is None and len(v) != len(r):
bad = min(len(v), len(r))
if bad is None:
total[0] += 1
else:
failures.setdefault(kind, []).append((case, bad, v[bad] if bad < len(v) else None, r[bad] if bad < len(r) else None))
for kind, error in sorted(errors.items()):
print(f'ORACLE ERROR {kind}: {error[:600]}')
for kind, items in sorted(failures.items()):
print(f'MISMATCH {kind}: {len(items)} cases')
for case, step, a, b in items[:args.detail]:
print(f' {case["name"]} {case["block"]} step {step}: {json.dumps(case["steps"][step] if step < len(case["steps"]) else None)}')
print(f' vanilla: {(a or "")[:500]}')
print(f' horizon: {(b or "")[:500]}')
for kind, (ok, n) in sorted(kinds.items()):
print(f'{kind}: {ok}/{n} cases match')
passed = sum(ok for ok, _ in kinds.values())
print(f'{passed}/{len(chosen)} cases match ({steps} ticked steps)')
if failures or errors:
sys.exit(1)
print('block entity animation parity ok')
if __name__ == '__main__':
main()