diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/block_entity_anim_fixture.rs index 21a74a413..3347a8104 100644 --- a/crates/horizon-client/examples/block_entity_anim_fixture.rs +++ b/crates/horizon-client/examples/block_entity_anim_fixture.rs @@ -7,9 +7,10 @@ use horizon_client::{ assets::Assets, block_entity_anim::{ - Bell, BellEntity, BlockEntityAnims, Conduit, ConduitTarget, DIRECTIONS, PotWobble, Shulker, - ShulkerStatus, Skull, WobbleStyle, direction_index, + Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS, + PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index, }, + block_entity_render::BlockEntityRenderer, blocks::{BlockFacts, Fluid}, items::Items, }; @@ -86,6 +87,27 @@ fn mob(e: &Value) -> BellEntity { } } +fn lid_text(l: Option<&ChestLid>) -> String { + l.map_or("-".to_owned(), |l| { + format!("{} {} {}", l.should_be_open, f(l.openness), f(l.o_openness)) + }) +} + +/// The case's players: feet positions and whether each is a spectator. +fn players(v: &Value) -> Vec<([f64; 3], bool)> { + v.as_array() + .into_iter() + .flatten() + .map(|p| { + let c = |i: usize| p["pos"][i].as_f64().unwrap_or(0.0); + ( + [c(0), c(1), c(2)], + p["spectator"].as_bool().unwrap_or(false), + ) + }) + .collect() +} + fn status(s: ShulkerStatus) -> &'static str { match s { ShulkerStatus::Closed => "CLOSED", @@ -103,6 +125,7 @@ fn main() -> Result<()> { let assets = Assets::load(root)?; let registry = assets.registry; let facts = BlockFacts::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; let tags = Items::tags_only(root)?; let frames = tags .block_tags @@ -154,6 +177,14 @@ fn main() -> Result<()> { 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 partner = case["partner"].as_str().map(|k| { + let o = offset(k); + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]] + }); + let mut gamers = players(&case["players"]); + if name == "minecraft:enchanting_table" { + anims.book_random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + } let facing = prop(&block, "facing") .and_then(direction_index) .unwrap_or(1); @@ -165,7 +196,83 @@ fn main() -> Result<()> { 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") { + if step.get("players").is_some() { + gamers = players(&step["players"]); + } + if name.ends_with("chest") { + let lid = anims.chests.entry(pos).or_default(); + if let Some((a, b)) = event { + let handled = lid.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + if let Some(other) = partner { + let lid = anims.chests.entry(other).or_default(); + if let Some(e) = step["partnerEvent"].as_array() { + let handled = lid.trigger_event(int(&e[0]), int(&e[1])); + let _ = write!(log, " partner event {handled}"); + } + } + // lidAnimateTick: this chest, then the other half. + if let Some(l) = anims.chests.get_mut(&pos) { + l.tick(); + } + if let Some(l) = partner.and_then(|p| anims.chests.get_mut(&p)) { + l.tick(); + } + let state_at = |p: [i32; 3]| { + find_state( + registry, + blocks.get(&p).map_or("minecraft:air", String::as_str), + ) + .unwrap_or(0) + }; + let (open, _) = renderer + .chest_openness_of(pos, state_at(pos), &state_at, &|p| anims.lid(p, partial)); + let _ = write!( + text, + "{} partner {} render {} {}", + lid_text(anims.chests.get(&pos)), + partner.map_or("none".to_owned(), |p| lid_text(anims.chests.get(&p))), + f(open), + f(chest_lid_x_rot(open)) + ); + } else if name == "minecraft:enchanting_table" { + let feet: Vec<[f64; 3]> = gamers + .iter() + .filter(|(_, spectator)| !spectator) + .map(|(p, _)| *p) + .collect(); + let BlockEntityAnims { + books, book_random, .. + } = &mut anims; + books.entry(pos).or_default().tick(pos, &feet, book_random); + let b = anims.books[&pos]; + let r = anims + .block_anim(pos, time, partial, Default::default()) + .book + .render(partial); + let _ = write!( + text, + "{} {} {} {} {} {} {} {} {} {} render {} {} {} {} book {} {} {}", + b.time, + f(b.flip), + f(b.o_flip), + f(b.flip_t), + f(b.flip_a), + f(b.open), + f(b.o_open), + f(b.rot), + f(b.o_rot), + f(b.t_rot), + f(r.flip), + f(r.open), + f(r.time), + f(r.y_rot), + f(r.openness), + f(r.page_flip1), + f(r.page_flip2) + ); + } else 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); diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index f29cebc0c..bed599b14 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -7,6 +7,7 @@ use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_client::{ assets::Assets, banner::{self, Banners}, + block_entity_anim::EnchantingBook, block_entity_render::{BlockAnim, BlockEntityRenderer, Scene, TextCall}, chunk::{Chunk, Light}, hud::{HudAtlas, Rect}, @@ -113,7 +114,7 @@ fn main() -> Result<()> { }; let assets = Assets::load(root)?; let registry = assets.registry; - let mut renderer = BlockEntityRenderer::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; let atlas = HudAtlas::build(root)?; let banners = Banners::load(root); let (sprites, names, grid) = fake_sprites(textures)?; @@ -196,13 +197,22 @@ fn main() -> Result<()> { world.chunks.insert((cx, cz), Arc::new(chunk)); } } - if let Some(book) = case.get("book") { - renderer.set_book( - pos, - int(&book["time"]), - ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])), - ); - } + let book = case + .get("book") + .map_or_else(EnchantingBook::default, |book| { + let [flip, o_flip, open, o_open, rot, o_rot] = + ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])); + EnchantingBook { + time: int(&book["time"]), + flip, + o_flip, + open, + o_open, + rot, + o_rot, + ..EnchantingBook::default() + } + }); let sign = case.get("sign").map(|s| { let mut data = SignData { hanging: block.contains("hanging"), @@ -246,6 +256,7 @@ fn main() -> Result<()> { wobble: case["wobble"] .as_array() .map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))), + book, }; let open = float(&case["open"]); let near = case["sign"]["near"].as_bool().unwrap_or(false); diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index fa74ac4d9..7d11fb201 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -1,5 +1,7 @@ //! Client-ticked block-entity animation state, as vanilla's block entities -//! keep it: `ShulkerBoxBlockEntity` (open count, animation status, progress), +//! keep it: `ChestLidController` (chests, trapped and copper chests, ender +//! chests), `EnchantingTableBlockEntity.bookAnimationTick`, +//! `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 @@ -11,7 +13,7 @@ //! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). use crate::block_entity_render::BlockAnim; use horizon_core::{ - geometry::trig::Mth, + geometry::trig::{self, Mth}, random::{LegacyRandom, RandomSource}, }; use std::collections::HashMap; @@ -40,6 +42,196 @@ pub fn direction_index(name: &str) -> Option { DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8) } +/// `ChestLidController`, shared by `ChestBlockEntity` (chests, trapped and +/// copper chests) and `EnderChestBlockEntity`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ChestLid { + pub should_be_open: bool, + pub openness: f32, + pub o_openness: f32, +} + +impl ChestLid { + /// `triggerEvent(1, openCount)`: the lid opens while anyone has it open. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 == 1 { + self.should_be_open = b1 > 0; + true + } else { + false + } + } + /// `tickLid` (the client ticker `lidAnimateTick`). + pub fn tick(&mut self) { + self.o_openness = self.openness; + if !self.should_be_open && self.openness > 0.0 { + self.openness = (self.openness - 0.1).max(0.0); + } else if self.should_be_open && self.openness < 1.0 { + self.openness = (self.openness + 0.1).min(1.0); + } + } + /// `getOpenness(a)`: `Mth.lerp(a, oOpenness, openness)`. + pub fn get_openness(&self, a: f32) -> f32 { + self.o_openness + a * (self.openness - self.o_openness) + } +} + +/// `ChestBlock.opennessCombiner`: a double chest opens as far as its more +/// open half (`Math.max(first, second)`, first being the `right` half). +pub fn combined_openness(first: f32, second: Option) -> f32 { + match second { + Some(second) => java_max(first, second), + None => first, + } +} + +/// `Math.max(float, float)`. +fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() { + a + } else if a == 0.0 && b == 0.0 && a.to_bits() != b.to_bits() { + 0.0 + } else if a >= b { + a + } else { + b + } +} + +/// `ChestRenderer.submit` and `ChestModel.setupAnim`: the lid and lock +/// `xRot` for a render-state openness. +pub fn chest_lid_x_rot(open: f32) -> f32 { + let open = 1.0 - open; + let open = 1.0 - open * open * open; + -(open * std::f32::consts::FRAC_PI_2) +} + +/// `EnchantingTableBlockEntity` book fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct EnchantingBook { + pub time: i32, + pub flip: f32, + pub o_flip: f32, + pub flip_t: f32, + pub flip_a: f32, + pub open: f32, + pub o_open: f32, + pub rot: f32, + pub o_rot: f32, + pub t_rot: f32, +} + +/// The `while (a >= PI) a -= 2PI; while (a < -PI) a += 2PI` loops. +fn wrap_pi(mut a: f32) -> f32 { + use std::f32::consts::PI; + while a >= PI { + a -= 2.0 * PI; + } + while a < -PI { + a += 2.0 * PI; + } + a +} + +/// `Mth.floor(float)`. +fn mth_floor(v: f32) -> i32 { + let i = v as i32; + if v < i as f32 { i - 1 } else { i } +} + +/// `Mth.frac(float)`. +pub fn mth_frac(v: f32) -> f32 { + v - mth_floor(v) as f32 +} + +/// `EnchantTableRenderState` (`EnchantTableRenderer.extractRenderState`) and +/// the `BookModel.State` its `submit` builds. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BookRender { + pub flip: f32, + pub open: f32, + pub time: f32, + pub y_rot: f32, + /// `BookModel.State.forAnimation`: openness, pageFlip1, pageFlip2. + pub openness: f32, + pub page_flip1: f32, + pub page_flip2: f32, +} + +impl EnchantingBook { + /// `bookAnimationTick`. `players` are the feet positions of the level's + /// non-spectator players (`getNearestPlayer(centre, 3.0, false)`); + /// `random` is the block entity class's shared static `RANDOM`. + pub fn tick(&mut self, pos: [i32; 3], players: &[[f64; 3]], random: &mut impl RandomSource) { + self.o_open = self.open; + self.o_rot = self.rot; + let c = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + let mut best = -1.0; + let mut nearest = None; + for p in players { + let (dx, dy, dz) = (p[0] - c[0], p[1] - c[1], p[2] - c[2]); + let dist = dx * dx + dy * dy + dz * dz; + if dist < 9.0 && (best == -1.0 || dist < best) { + best = dist; + nearest = Some(*p); + } + } + if let Some(p) = nearest { + let xd = p[0] - c[0]; + let zd = p[2] - c[2]; + self.t_rot = trig::atan2(zd, xd) as f32; + self.open += 0.1; + if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { + let old = self.flip_t; + loop { + let a = random.next_int_bound(4).unwrap_or(0); + let b = random.next_int_bound(4).unwrap_or(0); + self.flip_t += (a - b) as f32; + if old != self.flip_t { + break; + } + } + } + } else { + self.t_rot += 0.02; + self.open -= 0.1; + } + self.rot = wrap_pi(self.rot); + self.t_rot = wrap_pi(self.t_rot); + let dir = wrap_pi(self.t_rot - self.rot); + self.rot += dir * 0.4; + self.open = self.open.clamp(0.0, 1.0); + self.time += 1; + self.o_flip = self.flip; + let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); + self.flip_a += (diff - self.flip_a) * 0.9; + self.flip += self.flip_a; + } + /// `EnchantTableRenderer.extractRenderState` and the book state of its + /// `submit`. + pub fn render(&self, a: f32) -> BookRender { + let flip = self.o_flip + a * (self.flip - self.o_flip); + let open = self.o_open + a * (self.open - self.o_open); + let time = self.time as f32 + a; + let y_rot = self.o_rot + wrap_pi(self.rot - self.o_rot) * a; + let ff1 = mth_frac(flip + 0.25) * 1.6 - 0.3; + let ff2 = mth_frac(flip + 0.75) * 1.6 - 0.3; + BookRender { + flip, + open, + time, + y_rot, + openness: ((time * 0.02).msin() * 0.1 + 1.25) * open, + page_flip1: ff1.clamp(0.0, 1.0), + page_flip2: ff2.clamp(0.0, 1.0), + } + } +} + /// `ShulkerBoxBlockEntity.AnimationStatus`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ShulkerStatus { @@ -533,9 +725,65 @@ impl PotWobble { } } +/// The client ticker a block entity runs (`getTicker` on a client level), +/// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ticker { + /// `ChestBlockEntity` / `EnderChestBlockEntity.lidAnimateTick`. + Lid, + /// `EnchantingTableBlockEntity.bookAnimationTick`. + Book, + /// `ShulkerBoxBlockEntity.tick`, with the box's facing. + Shulker { + facing: u8, + }, + /// `BellBlockEntity.clientTick`. + Bell, + /// `ConduitBlockEntity.clientTick`. + Conduit, + /// `SkullBlockEntity.animation` (dragon and piglin heads only). + Skull { + powered: bool, + }, + Pot, +} + +/// The [`Ticker`] of a block state, by block name and property lookup. +pub fn ticker(name: &str, prop: impl Fn(&str) -> Option) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); + Some(match unwaxed { + "chest" + | "trapped_chest" + | "ender_chest" + | "copper_chest" + | "exposed_copper_chest" + | "weathered_copper_chest" + | "oxidized_copper_chest" => Ticker::Lid, + "enchanting_table" => Ticker::Book, + "bell" => Ticker::Bell, + "conduit" => Ticker::Conduit, + "decorated_pot" => Ticker::Pot, + "dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull { + powered: prop("powered").as_deref() == Some("true"), + }, + n if n.ends_with("shulker_box") => Ticker::Shulker { + facing: prop("facing") + .as_deref() + .and_then(direction_index) + .unwrap_or(1), + }, + _ => return None, + }) +} + /// The animated block entities of a level, by position. #[derive(Clone, Debug)] pub struct BlockEntityAnims { + pub chests: HashMap<[i32; 3], ChestLid>, + pub books: HashMap<[i32; 3], EnchantingBook>, + /// `EnchantingTableBlockEntity.RANDOM`, shared by every table. + pub book_random: LegacyRandom, pub shulkers: HashMap<[i32; 3], Shulker>, pub bells: HashMap<[i32; 3], Bell>, pub conduits: HashMap<[i32; 3], Conduit>, @@ -543,28 +791,71 @@ pub struct BlockEntityAnims { pub pots: HashMap<[i32; 3], PotWobble>, /// The client level's random (conduit particles). pub random: LegacyRandom, + /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). + pub kinds: Vec>, } impl Default for BlockEntityAnims { fn default() -> Self { Self { + chests: HashMap::new(), + books: HashMap::new(), + book_random: LegacyRandom::new(0x626f6f6b), shulkers: HashMap::new(), bells: HashMap::new(), conduits: HashMap::new(), skulls: HashMap::new(), pots: HashMap::new(), random: LegacyRandom::new(0x6c6576656c), + kinds: Vec::new(), } } } impl BlockEntityAnims { + /// Fills [`Self::kinds`] for every state of the registry. + pub fn classify(&mut self, registry: &horizon_world::registry::BlockRegistry) { + self.kinds = (0..registry.len() as u32) + .map(|id| { + registry + .state(horizon_world::registry::BlockStateId(id)) + .and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned())) + }) + .collect(); + } + /// The ticker of a block state. + pub fn ticker(&self, state: u32) -> Option { + self.kinds.get(state as usize).copied().flatten() + } + /// Drops the state of block entities that are gone or changed kind: + /// `present` maps the loaded block entities to their tickers. + pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) { + let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f); + self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid)); + self.books.retain(|p, _| is(p, |t| *t == Ticker::Book)); + self.shulkers + .retain(|p, _| is(p, |t| matches!(t, Ticker::Shulker { .. }))); + self.bells.retain(|p, _| is(p, |t| *t == Ticker::Bell)); + self.conduits + .retain(|p, _| is(p, |t| *t == Ticker::Conduit)); + self.skulls + .retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. }))); + self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot)); + } /// Drops the state of positions whose block entity is gone. pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) { + self.chests.retain(|p, _| keep(*p)); + self.books.retain(|p, _| keep(*p)); 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)); } + /// `getOpenNess(partial)` of the chest or ender chest at `pos`. + pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.chests + .get(&pos) + .map_or(0.0, |l| l.get_openness(partial)) + } /// 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( @@ -578,6 +869,9 @@ impl BlockEntityAnims { sherds, ..BlockAnim::default() }; + if let Some(b) = self.books.get(&pos) { + anim.book = *b; + } if let Some(s) = self.shulkers.get(&pos) { anim.shulker = (s.progress, s.progress_old); } diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index f3638865b..ae9d4ddf9 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -7,10 +7,7 @@ //! the block plus `minecraft_mix_light` with the level's two diffuse lights. use crate::{hud::Rect, mesher::Vertex, world::World}; use glam::{DVec3, Mat4, Quat, Vec3}; -use horizon_core::{ - geometry::trig::Mth, - random::{LegacyRandom, RandomSource}, -}; +use horizon_core::geometry::trig::Mth; use horizon_world::registry::{BlockRegistry, BlockStateId}; use serde_json::Value; use std::{collections::HashMap, f32::consts::PI, path::Path}; @@ -256,6 +253,8 @@ enum SkullType { enum Kind { None, Chest { + /// The block (`neighbourState.is(state.getBlock())`). + block: String, texture: &'static str, part: ChestPart, y_rot: f32, @@ -323,6 +322,7 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { ChestPart::Right => Some(step(opposite(clockwise(facing)))), }; Kind::Chest { + block: name.to_owned(), texture: match part { ChestPart::Single => texture, ChestPart::Left => left, @@ -512,72 +512,6 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { Kind::None } -/// `EnchantingTableBlockEntity` book animation state. -#[derive(Clone, Copy, Default)] -struct Book { - time: i32, - flip: f32, - o_flip: f32, - flip_t: f32, - flip_a: f32, - open: f32, - o_open: f32, - rot: f32, - o_rot: f32, - t_rot: f32, -} -fn wrap(mut a: f32) -> f32 { - while a >= PI { - a -= 2.0 * PI; - } - while a < -PI { - a += 2.0 * PI; - } - a -} -impl Book { - /// `EnchantingTableBlockEntity.bookAnimationTick`. - fn tick(&mut self, pos: [i32; 3], player: Option<[f64; 3]>, random: &mut LegacyRandom) { - self.o_open = self.open; - self.o_rot = self.rot; - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - let near = player.filter(|p| { - (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) < 9.0 - }); - if let Some(p) = near { - self.t_rot = (p[2] - c[2]).atan2(p[0] - c[0]) as f32; - self.open += 0.1; - if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { - let old = self.flip_t; - loop { - let a = random.next_int_bound(4).unwrap_or(0); - let b = random.next_int_bound(4).unwrap_or(0); - self.flip_t += (a - b) as f32; - if old != self.flip_t { - break; - } - } - } - } else { - self.t_rot += 0.02; - self.open -= 0.1; - } - self.rot = wrap(self.rot); - self.t_rot = wrap(self.t_rot); - let dir = wrap(self.t_rot - self.rot); - self.rot += dir * 0.4; - self.open = self.open.clamp(0.0, 1.0); - self.time += 1; - self.o_flip = self.flip; - let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); - self.flip_a += (diff - self.flip_a) * 0.9; - self.flip += self.flip_a; - } -} /// `BookModel.setupAnim` for `BookModel.State(openness, pageFlip1, pageFlip2)`. fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) { move |name, p| match name { @@ -737,6 +671,8 @@ pub struct BlockAnim { pub sherds: [Option; 4], /// `DecoratedPotRenderState` wobble style (positive) and progress. pub wobble: Option<(bool, f32)>, + /// `EnchantingTableBlockEntity` book fields. + pub book: crate::block_entity_anim::EnchantingBook, } /// One `submitText` call (`AbstractSignRenderer.submitSignText`). @@ -781,8 +717,6 @@ pub struct Scene<'a> { pub struct BlockEntityRenderer { models: HashMap<&'static str, ModelPart>, kinds: Vec, - books: HashMap<[i32; 3], Book>, - random: LegacyRandom, /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, } @@ -871,8 +805,6 @@ impl BlockEntityRenderer { Self { models, kinds, - books: HashMap::new(), - random: LegacyRandom::new(0x5EED_B00C), pot_patterns: HashMap::new(), } } @@ -886,24 +818,6 @@ impl BlockEntityRenderer { fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } - /// Client-side block-entity ticks (enchanting-table books). - pub fn tick<'a>( - &mut self, - blocks: impl Iterator, - player: Option<[f64; 3]>, - ) { - let mut seen = Vec::new(); - for (pos, state) in blocks { - if matches!(self.kind(*state), Kind::EnchantingTable) { - seen.push(*pos); - } - } - self.books.retain(|p, _| seen.contains(p)); - for pos in seen { - let book = self.books.entry(pos).or_default(); - book.tick(pos, player, &mut self.random); - } - } pub fn render<'a>( &self, scene: &Scene, @@ -951,21 +865,65 @@ impl BlockEntityRenderer { pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } - /// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`): - /// time, flip, oFlip, open, oOpen, rot, oRot. - pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) { - let [flip, o_flip, open, o_open, rot, o_rot] = fields; - let book = self.books.entry(pos).or_default(); - *book = Book { - time, - flip, - o_flip, - open, - o_open, - rot, - o_rot, - ..*book + /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` + /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) + /// pairs a double half with its neighbour only when that is the same + /// block, the other half and faces the same way; `opennessCombiner` then + /// takes the more open of both. Also returns the paired half's position. + /// `lid` is `getOpenNess(partial)` at a position; non-chests give 0. + pub fn chest_openness_of( + &self, + pos: [i32; 3], + state: u32, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + self.chest_openness(pos, self.kind(state), block_at, lid) + } + fn chest_openness( + &self, + pos: [i32; 3], + kind: &Kind, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + let Kind::Chest { + block, + part, + y_rot, + double_with, + .. + } = kind + else { + return (0.0, None); }; + let open = lid(pos); + let Some(d) = double_with else { + return (open, None); + }; + let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + match self.kind(block_at(other)) { + Kind::Chest { + block: other_block, + part: other_part, + y_rot: other_y_rot, + .. + } if other_block == block + && *other_part != ChestPart::Single + && other_part != part + && other_y_rot == y_rot => + { + let other_open = lid(other); + // The right half is the first. + let open = if *part == ChestPart::Right { + crate::block_entity_anim::combined_openness(open, Some(other_open)) + } else { + crate::block_entity_anim::combined_openness(other_open, Some(open)) + }; + (open, Some(other)) + } + _ => (open, None), + } } /// One block entity of `state` drawn under `base` (minecart contents). pub fn render_state( @@ -1060,7 +1018,7 @@ impl BlockEntityRenderer { texture, part, y_rot, - double_with, + .. } => { let model = match part { ChestPart::Single => "chest", @@ -1070,22 +1028,24 @@ impl BlockEntityRenderer { let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { return; }; - // ChestBlock.opennessCombiner / BrightnessCombiner: both halves. - let mut open = (scene.lid)(pos); + let (open, other) = self.chest_openness( + pos, + kind, + &|p| scene.world.block(p[0], p[1], p[2]).0, + scene.lid, + ); + // BrightnessCombiner: the brighter of both halves, per channel. let mut packed = packed; - if let Some(d) = double_with { - let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; - open = open.max((scene.lid)(other)); + if let Some(other) = other { let l = scene.world.light(other[0], other[1], other[2]); packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); } - let open = 1.0 - (1.0 - open).powi(3); let m = base * around( Mat4::from_rotation_y((-y_rot).to_radians()), Vec3::new(0.5, 0.0, 0.5), ); - let lid = -(open * PI / 2.0); + let lid = crate::block_entity_anim::chest_lid_x_rot(open); let adjust = move |name: &str, p: &mut [f32; 9]| { if name == "lid" || name == "lock" { p[3] = lid; @@ -1363,21 +1323,18 @@ impl BlockEntityRenderer { ) else { return; }; - let b = self.books.get(&pos).copied().unwrap_or_default(); - let a = scene.partial; - let flip = b.o_flip + (b.flip - b.o_flip) * a; - let open = b.o_open + (b.open - b.o_open) * a; - let time = b.time as f32 + a; - let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a; + // EnchantTableRenderer.extractRenderState and submit. + let b = (scene.anim)(pos).book.render(scene.partial); let m = base * Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5)) - * Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0)) - * Mat4::from_rotation_y(-y_rot) + * Mat4::from_translation(Vec3::new( + 0.0, + 0.1 + (b.time * 0.1).msin() * 0.01, + 0.0, + )) + * Mat4::from_rotation_y(-b.y_rot) * Mat4::from_rotation_z(80f32.to_radians()); - let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0); - let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0); - // BookModel.State.forAnimation. - let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open; + let (openness, ff1, ff2) = (b.openness, b.page_flip1, b.page_flip2); draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out); } Kind::Lectern { y_rot } => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 667e7d911..f482568e6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6,6 +6,7 @@ mod allays; mod armor_stands; mod banners; mod beacon; +mod block_entity_anims; mod blockctl; mod boats; mod books; @@ -611,7 +612,8 @@ struct Game<'a> { raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, - chest_open: HashMap<(i32, i32, i32), (f32, f32)>, + /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). + be_anims: horizon_client::block_entity_anim::BlockEntityAnims, /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, /// Camera.oldFovModifier / fovModifier. @@ -1568,6 +1570,9 @@ impl Game<'_> { state, kind: "shrieker_respond", } => self.shrieker_block_event(pos, state), + LevelEvent::BlockEntityEvent { pos, a, b, .. } => { + self.block_entity_event([pos.x, pos.y, pos.z], a, b) + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} @@ -1592,6 +1597,7 @@ impl Game<'_> { self.craft_size = 3; } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); + self.container_opener_event(key, true); let at = [ f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, @@ -1607,6 +1613,7 @@ impl Game<'_> { } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); + self.container_opener_event(key, true); self.post_block_game_event( "minecraft:container_open", [key.0, key.1, key.2], @@ -1848,6 +1855,7 @@ impl Game<'_> { let name = facts.name.clone(); self.release_contents(pos, entity, &name); if self.container == Some((pos[0], pos[1], pos[2])) { + self.container_opener_event((pos[0], pos[1], pos[2]), false); self.container = None; self.screen = Screen::Playing; } @@ -2737,16 +2745,8 @@ impl Game<'_> { self.tick_sculk()?; self.tick_brewing_stands()?; } - if let Some(r) = &self.renderer { - let eye = self.player.as_ref().map(|p| { - [ - p.position.x, - p.position.y + f64::from(self.eye), - p.position.z, - ] - }); - self.res.block_entity_render.tick(r.block_entities(), eye); - } + // ClientLevel.tickBlockEntities: chest lids, books, shulker boxes, bells... + self.tick_block_entity_anims(); if running { self.tick_particles(); } @@ -3458,6 +3458,7 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { + self.container_opener_event(key, false); self.post_block_game_event( "minecraft:container_close", [key.0, key.1, key.2], @@ -4103,14 +4104,8 @@ impl Game<'_> { } // Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls... if let Some(r) = &self.renderer { - let lid = |p: [i32; 3]| { - let (prev, cur) = self - .chest_open - .get(&(p[0], p[1], p[2])) - .copied() - .unwrap_or((0.0, 0.0)); - prev + (cur - prev) * alpha as f32 - }; + let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32); + let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32); let (view_yaw, view_pitch) = if self.camera_type == perspective::CameraType::ThirdPersonFront { (self.yaw + 180.0, -self.pitch) @@ -4126,7 +4121,7 @@ impl Game<'_> { -view_pitch.to_radians(), 0.0, ), - anim: &|_| horizon_client::block_entity_render::BlockAnim::default(), + anim: &anim, texts: None, partial: alpha as f32, game_time: self.world.game_time, @@ -4591,20 +4586,6 @@ impl Game<'_> { self.tick_jukeboxes(); self.tick_beacons(); self.tick_creaking_hearts()?; - // ChestLidController: 0.1 per tick towards open/closed. - if let Some(key) = self.container { - self.chest_open.entry(key).or_insert((0.0, 0.0)); - } - let open = self.container; - self.chest_open.retain(|k, (prev, cur)| { - *prev = *cur; - *cur = if Some(*k) == open { - (*cur + 0.1).min(1.0) - } else { - (*cur - 0.1).max(0.0) - }; - *cur > 0.0 || *prev > 0.0 - }); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -4989,6 +4970,11 @@ impl Game<'_> { self.restore_effects(); self.mining = None; self.container = None; + let kinds = std::mem::take(&mut self.be_anims.kinds); + self.be_anims = horizon_client::block_entity_anim::BlockEntityAnims { + kinds, + ..Default::default() + }; self.carried = None; self.using = None; self.screen = Screen::Playing; @@ -8023,7 +8009,11 @@ pub fn run() -> Result<()> { raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), - chest_open: HashMap::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry_owner.registry); + anims + }, using: None, view: Default::default(), limiter: horizon_client::window::FramerateLimiter::new(0), diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs new file mode 100644 index 000000000..349e4724d --- /dev/null +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -0,0 +1,269 @@ +//! The client side of animated block entities (`horizon_client::block_entity_anim`): +//! their client tickers (`Level.tickBlockEntities` on the client level) and +//! the block events that drive them (`ClientboundBlockEventPacket` reaching +//! `BlockEntity.triggerEvent`). The renderer reads the resulting state through +//! [`Game::block_anim`] and [`Game::chest_lid`]. +use super::Game; +use horizon_client::{ + block_entity_anim::{BellEntity, Ticker}, + block_entity_render::BlockAnim, + particles::{ParticleOptions, ParticleType}, +}; +use std::collections::HashMap; + +/// The handle of the local player among a bell's gathered entities. +const PLAYER: u64 = u64::MAX; + +impl Game<'_> { + /// `BlockEntity.triggerEvent(a, b)` on the client copy of the block entity at `pos`. + pub(super) fn block_entity_event(&mut self, pos: [i32; 3], a: i32, b: i32) { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + let time = self.world.game_time; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + self.be_anims + .chests + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Shulker { .. }) => { + self.be_anims + .shulkers + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Bell) => { + let gathered = self.bell_gather(pos); + self.be_anims + .bells + .entry(pos) + .or_default() + .trigger_event(a, b, time, || gathered); + } + Some(Ticker::Pot) => { + self.be_anims + .pots + .entry(pos) + .or_default() + .trigger_event(a, b, time); + } + _ => {} + } + } + /// A player opened (`open`) or closed the container at `key`: the opener + /// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity` + /// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes, + /// on both halves of a double chest (`CompoundContainer`). + pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) { + // Spectators never count as openers. + if self.spectator() { + return; + } + let pos = [key.0, key.1, key.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + let count = i32::from(open); + self.block_entity_event(pos, 1, count); + if let Some(other) = self.chest_other_half(key) { + self.block_entity_event([other.0, other.1, other.2], 1, count); + } + } + Some(Ticker::Shulker { .. }) => { + let shulker = self.be_anims.shulkers.entry(pos).or_default(); + let (count, _) = if open { + shulker.start_open() + } else { + shulker.stop_open() + }; + self.block_entity_event(pos, 1, count); + } + _ => {} + } + } + /// `BellBlockEntity.updateEntities`: the living entities whose bounding + /// box meets the bell's block box inflated by 48. + fn bell_gather(&self, pos: [i32; 3]) -> Vec { + let lo = [ + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + ]; + let hi = [ + lo[0] + 49.0 + 48.0, + lo[1] + 49.0 + 48.0, + lo[2] + 49.0 + 48.0, + ]; + let meets = |p: [f64; 3], width: f64, height: f64| { + let (bl, bh) = ( + [p[0] - width / 2.0, p[1], p[2] - width / 2.0], + [p[0] + width / 2.0, p[1] + height, p[2] + width / 2.0], + ); + (0..3).all(|a| bl[a] < hi[a] && bh[a] > lo[a]) + }; + let mut out = Vec::new(); + if let Some(p) = &self.player + && meets([p.position.x, p.position.y, p.position.z], 0.6, 1.8) + { + out.push(PLAYER); + } + for m in &self.mobs { + let p = [m.position.x, m.position.y, m.position.z]; + if meets(p, m.kind.width, m.kind.height) { + out.push(u64::from(m.id)); + } + } + out + } + /// The client tickers of the loaded animated block entities, once per + /// client tick (`ClientLevel.tickBlockEntities`). + pub(super) fn tick_block_entity_anims(&mut self) { + let Some(r) = &self.renderer else { + return; + }; + let present: HashMap<[i32; 3], Ticker> = r + .block_entities() + .filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) + .collect(); + self.be_anims.retain_present(&present); + let players: Vec<[f64; 3]> = match &self.player { + Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]], + _ => Vec::new(), + }; + let raiders = self + .res + .stations + .enchantments + .entity_tags + .get("minecraft:raiders") + .cloned() + .unwrap_or_default(); + let frames = self + .res + .items + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect(); + positions.sort_unstable_by_key(|(p, _)| *p); + for (pos, ticker) in positions { + match ticker { + Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(), + Ticker::Book => { + let anims = &mut self.be_anims; + anims + .books + .entry(pos) + .or_default() + .tick(pos, &players, &mut anims.book_random); + } + Ticker::Shulker { facing } => { + // The lid's push of entities in its way (moveCollidedEntities) + // and the neighbour updates are left to the level. + self.be_anims + .shulkers + .entry(pos) + .or_default() + .tick(pos, facing); + } + Ticker::Skull { powered } => { + self.be_anims.skulls.entry(pos).or_default().tick(powered); + } + Ticker::Bell => { + let player = self.player.as_ref().map(|p| BellEntity { + position: [p.position.x, p.position.y, p.position.z], + alive: true, + raider: false, + }); + let mobs = &self.mobs; + let entity = |h: u64| { + if h == PLAYER { + return player; + } + let m = mobs.iter().find(|m| u64::from(m.id) == h)?; + Some(BellEntity { + position: [m.position.x, m.position.y, m.position.z], + alive: m.health > 0.0, + raider: raiders.contains(&m.kind.id), + }) + }; + let tick = self + .be_anims + .bells + .entry(pos) + .or_default() + .tick(pos, entity); + let centre = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + if tick.resonate { + // The server's copy plays the resonance for everyone. + self.audio + .play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0); + } + if let Some((particles, glow)) = tick.ended { + for (p, color) in particles { + // ColorParticleOption.create(ENTITY_EFFECT, color): ARGB. + let c = color as u32; + let channel = |shift: u32| ((c >> shift) & 255) as f32 / 255.0; + let options = ParticleOptions { + color: [channel(16), channel(8), channel(0), channel(24)], + ..ParticleOptions::simple(ParticleType::EntityEffect) + }; + self.particles.add(&options, p, [0.0; 3]); + } + // makeRaidersGlow. + for m in self.mobs.iter_mut() { + if glow.contains(&u64::from(m.id)) { + m.add_effect("minecraft:glowing", 60, 0); + } + } + } + } + Ticker::Conduit => { + let world = &self.world; + let facts = &self.res.facts; + let registry = self.res.assets.registry; + let is_water = |p: [i32; 3]| { + facts.get(world.block(p[0], p[1], p[2])).fluid + == horizon_client::blocks::Fluid::Water + }; + let is_frame = |p: [i32; 3]| { + registry + .state(world.block(p[0], p[1], p[2])) + .is_some_and(|s| frames.contains(&s.name)) + }; + let time = world.game_time; + let anims = &mut self.be_anims; + let particles = anims.conduits.entry(pos).or_default().client_tick( + pos, + time, + is_water, + is_frame, + None, + self.particles.random(), + ); + let nautilus = ParticleOptions::simple(ParticleType::Nautilus); + for (p, v) in particles { + self.particles.add(&nautilus, p, v); + } + } + Ticker::Pot => {} + } + } + } + /// The renderer's view of the block entity at `pos`. + pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { + self.be_anims + .block_anim(pos, self.world.game_time, partial, Default::default()) + } + /// `ChestLidController.getOpenness(partial)` at `pos`. + pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.be_anims.lid(pos, partial) + } +} diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 9590c90bb..6d0fd2680 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -367,6 +367,8 @@ fn main() -> Result<(), Box> { LevelEvent::BlockEvent { kind, .. } => { let _ = writeln!(result, "X {kind}"); } + // The client copy of a bell's ring: no level change. + LevelEvent::BlockEntityEvent { .. } => {} LevelEvent::GrowTree { .. } => { let _ = writeln!(result, "X grow_tree"); } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 166483709..639c9b459 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -259,6 +259,16 @@ pub enum LevelEvent { state: BlockStateId, kind: &'static str, }, + /// A queued block event that reached a block entity + /// (`BaseEntityBlock.triggerEvent`): the client's copy runs + /// `BlockEntity.triggerEvent(a, b)` (`ClientboundBlockEventPacket`), as + /// for a bell's ring (event 1, the struck direction). + BlockEntityEvent { + pos: BlockPos, + state: BlockStateId, + a: i32, + b: i32, + }, /// A player-side effect of [`Behaviours::use_without_item`]. Player { pos: BlockPos, diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 299959e0b..fa5b7989c 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -114,6 +114,13 @@ impl Sim<'_, L> { } else if data.is(super::classes::Class::Note) { self.note_trigger_event(pos, state); true + } else if data.is(super::classes::Class::Bell) { + // BellBlockEntity.triggerEvent handles event 1; the server + // broadcasts handled events to the clients. + if a == 1 { + self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); + } + a == 1 } else { false } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java index f9a09e9d4..5c8c899db 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java @@ -6,6 +6,8 @@ import java.lang.reflect.*; import java.nio.file.*; import java.util.*; import java.util.function.Predicate; +import net.minecraft.client.model.object.book.BookModel; +import net.minecraft.client.model.object.chest.ChestModel; import net.minecraft.client.renderer.blockentity.*; import net.minecraft.client.renderer.blockentity.state.*; import net.minecraft.commands.arguments.blocks.BlockStateParser; @@ -18,7 +20,9 @@ import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; +import net.minecraft.util.Mth; import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.*; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.entity.*; @@ -27,12 +31,14 @@ 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 + * Original oracle for the client-ticked animation state of chests and ender + * chests (ChestLidController), enchanting table books, 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, + * ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM + * reseeded, 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 @@ -74,12 +80,30 @@ public final class VanillaBlockEntityAnimOracle { @Override public boolean isAlive() { return !this.isRemoved() && this.living; } } + /** A player the case places: position and game mode (spectators are skipped). */ + static final class Gamer extends Player { + GameType mode; + Gamer() { super(null, null); } + @Override public GameType gameMode() { return mode; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return null; } + } + + static Gamer gamer(JsonObject e) throws Exception { + Gamer g = make(Gamer.class); + g.mode = e.has("spectator") && e.get("spectator").getAsBoolean() ? GameType.SPECTATOR : GameType.SURVIVAL; + var p = e.getAsJsonArray("pos"); + put(g, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble())); + return g; + } + /** The stand-in client level. */ static final class World extends Level { World() { super(null, null, null, null, false, false, 0L, 0); } long time; Map blocks = new HashMap<>(); List mobs = new ArrayList<>(); + List gamers = new ArrayList<>(); + Map entities = new HashMap<>(); RandomSource random; StringBuilder log = new StringBuilder(); @@ -89,6 +113,7 @@ public final class VanillaBlockEntityAnimOracle { @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 BlockEntity getBlockEntity(BlockPos p) { return entities.get(p.immutable()); } @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 getEntities(Entity except, AABB bb) { log.append(" push ").append(box(bb)); return List.of(); } @@ -132,7 +157,7 @@ public final class VanillaBlockEntityAnimOracle { @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 java.util.List players(){return gamers;} @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();} @@ -154,10 +179,28 @@ public final class VanillaBlockEntityAnimOracle { return m; } + static ChestModel CHEST_MODEL; + + static void tickLid(World world, BlockEntity e) { + if (e instanceof ChestBlockEntity c) ChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c); + else if (e instanceof EnderChestBlockEntity c) EnderChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c); + } + + static String lid(BlockEntity e) throws Exception { + if (!(e instanceof ChestBlockEntity) && !(e instanceof EnderChestBlockEntity)) return "-"; + Class owner = e instanceof ChestBlockEntity ? ChestBlockEntity.class : EnderChestBlockEntity.class; + Object lid = field(owner, "chestLidController").get(e); + return field(ChestLidController.class, "shouldBeOpen").getBoolean(lid) + + " " + f(field(ChestLidController.class, "openness").getFloat(lid)) + + " " + f(field(ChestLidController.class, "oOpenness").getFloat(lid)); + } + static String run(JsonObject c) throws Exception { World world = make(World.class); world.blocks = new HashMap<>(); world.mobs = new ArrayList<>(); + world.gamers = new ArrayList<>(); + world.entities = new HashMap<>(); world.log = new StringBuilder(); world.random = RandomSource.create(c.has("seed") ? c.get("seed").getAsLong() : 0L); var pa = c.getAsJsonArray("pos"); @@ -173,6 +216,23 @@ public final class VanillaBlockEntityAnimOracle { 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); + world.entities.put(pos, be); + // The other half of a double chest (or whatever block sits there). + BlockEntity partner = null; + if (c.has("partner")) { + String[] xyz = c.get("partner").getAsString().split(","); + BlockPos at = pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])); + BlockState there = world.getBlockState(at); + if (there.getBlock() instanceof EntityBlock eb) { + partner = eb.newBlockEntity(at, there); + partner.setLevel(world); + world.entities.put(at, partner); + } + } + if (c.has("players")) for (var e : c.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject())); + if (be instanceof EnchantingTableBlockEntity) { + ((RandomSource) field(EnchantingTableBlockEntity.class, "RANDOM").get(null)).setSeed(c.get("seed").getAsLong()); + } if (c.has("target") && be instanceof ConduitBlockEntity) { put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world))); } @@ -187,14 +247,50 @@ public final class VanillaBlockEntityAnimOracle { world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString())); } } + if (step.has("players")) { + world.gamers.clear(); + for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject())); + } 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); } + if (step.has("partnerEvent") && partner != null) { + var ev = step.getAsJsonArray("partnerEvent"); + boolean handled = partner.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt()); + world.log.append(" partner event ").append(handled); + } float partial = step.get("partial").getAsFloat(); String fields; - if (be instanceof ShulkerBoxBlockEntity s) { + if (be instanceof ChestBlockEntity || be instanceof EnderChestBlockEntity) { + tickLid(world, be); + if (partner != null) tickLid(world, partner); + ChestRenderer renderer = make(ChestRenderer.class); + var r = new net.minecraft.client.renderer.blockentity.state.ChestRenderState(); + @SuppressWarnings({"unchecked", "rawtypes"}) + ChestRenderer raw = renderer; + raw.extractRenderState(be, r, partial, Vec3.ZERO, null); + float open = r.open; + // ChestRenderer.submit, then ChestModel.setupAnim. + open = 1.0F - open; + open = 1.0F - open * open * open; + CHEST_MODEL.setupAnim(open); + fields = lid(be) + " partner " + (partner == null ? "none" : lid(partner)) + + " render " + f(r.open) + " " + f(((net.minecraft.client.model.geom.ModelPart) field(ChestModel.class, "lid").get(CHEST_MODEL)).xRot); + } else if (be instanceof EnchantingTableBlockEntity t) { + EnchantingTableBlockEntity.bookAnimationTick(world, pos, state, t); + var r = new net.minecraft.client.renderer.blockentity.state.EnchantTableRenderState(); + make(EnchantTableRenderer.class).extractRenderState(t, r, partial, Vec3.ZERO, null); + // EnchantTableRenderer.submit's book state. + float ff1 = Mth.frac(r.flip + 0.25F) * 1.6F - 0.3F; + float ff2 = Mth.frac(r.flip + 0.75F) * 1.6F - 0.3F; + var book = BookModel.State.forAnimation(r.time, Mth.clamp(ff1, 0.0F, 1.0F), Mth.clamp(ff2, 0.0F, 1.0F), r.open); + fields = t.time + " " + f(t.flip) + " " + f(t.oFlip) + " " + f(t.flipT) + " " + f(t.flipA) + + " " + f(t.open) + " " + f(t.oOpen) + " " + f(t.rot) + " " + f(t.oRot) + " " + f(t.tRot) + + " render " + f(r.flip) + " " + f(r.open) + " " + f(r.time) + " " + f(r.yRot) + + " book " + f(book.openness()) + " " + f(book.pageFlip1()) + " " + f(book.pageFlip2()); + } else 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); @@ -248,6 +344,7 @@ public final class VanillaBlockEntityAnimOracle { allocate = allocator.getMethod("allocateInstance", Class.class); putObject = allocator.getMethod("putObject", Object.class, long.class, Object.class); objectFieldOffset = allocator.getMethod("objectFieldOffset", Field.class); + CHEST_MODEL = new ChestModel(ChestModel.createSingleBodyLayer().bakeRoot()); try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); var lines = Files.lines(Path.of(args[0]))) { for (String line : (Iterable) lines::iterator) { diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py index 8f4950255..0e85d978a 100755 --- a/tools/test_block_entity_anim_parity.py +++ b/tools/test_block_entity_anim_parity.py @@ -2,7 +2,9 @@ """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) +block entity (chest, trapped/copper chest and the other half of a double chest, +ender chest, enchanting table, 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 @@ -31,6 +33,9 @@ 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]'] +CHESTS = ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'waxed_oxidized_copper_chest'] +CLOCKWISE = {'north': 'east', 'east': 'south', 'south': 'west', 'west': 'north'} +STEP = {'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)} DRY = ['minecraft:air', 'minecraft:stone', 'minecraft:lava', 'minecraft:oak_slab', 'minecraft:ice'] @@ -157,6 +162,78 @@ def cases(): 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) + # Chests and ender chests: open counts from block event 1 (both halves of + # a double chest), other events ignored; the neighbour a double half + # connects to may be its other half or not (wrong block, type, facing). + for i in range(48): + facing = rng.choice(HORIZONTAL) + partner = None + world = {} + if rng.random() < 0.2: + block = f'minecraft:ender_chest[facing={facing}]' + else: + name = rng.choice(CHESTS) + kind = rng.choice(['single', 'left', 'right', 'left', 'right']) + block = f'minecraft:{name}[facing={facing},type={kind}]' + if kind != 'single': + connected = CLOCKWISE[facing] if kind == 'left' else [d for d, c in CLOCKWISE.items() if c == facing][0] + other_kind = 'right' if kind == 'left' else 'left' + other_name, other_facing, r = name, facing, rng.random() + if r < 0.1: + other_kind = kind + elif r < 0.2: + other_facing = rng.choice([d for d in HORIZONTAL if d != facing]) + elif r < 0.3: + other_name = rng.choice([c for c in CHESTS if c != name]) + elif r < 0.35: + other_kind = 'single' + if r < 0.95: + partner = '%d,%d,%d' % STEP[connected] + world[partner] = f'minecraft:{other_name}[facing={other_facing},type={other_kind}]' + steps, count, other = [], 0, 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)] + if partner and rng.random() < 0.15: + other = other + 1 if rng.random() < 0.55 else other - 1 + step['partnerEvent'] = [1, other] + steps.append(step) + extra = {'world': world} + if partner: + extra['partner'] = partner + add('chest', block, steps, **extra) + + # Enchanting tables: players (and spectators) walking in and out of the + # 3-block reach; the class's shared RANDOM seeded per case. + for i in range(36): + p = pos() + centre = [p[0] + 0.5, p[1] + 0.5, p[2] + 0.5] + + def players(): + out = [] + for _ in range(rng.choice([0, 1, 1, 1, 2, 3])): + spread = rng.choice([1.5, 3, 5]) + out.append({'pos': [centre[k] + round(rng.uniform(-spread, spread) * 1024) / 1024 for k in range(3)], + 'spectator': rng.random() < 0.15}) + return out + steps = [] + for t in times(rng.randint(40, 160)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.08: + step['players'] = players() + steps.append(step) + case = {'name': f'book-{len(out)}', 'block': 'minecraft:enchanting_table', 'pos': p, 'steps': steps, + 'players': players(), 'seed': rng.randint(0, 2 ** 40)} + out.append(case) + return out