diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index e26dc5d3a..a0f828cec 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -383,3 +383,48 @@ impl Painting { ) } } +/// An item frame or glow item frame (`ItemFrame`). +#[derive(Clone, Debug)] +pub struct ItemFrame { + pub id: u32, + pub pos: [i32; 3], + /// Direction.get3DDataValue: down 0, up 1, north 2, south 3, west 4, east 5. + pub facing: u8, + pub glow: bool, + pub item: Option, + /// 0..8, in 45 degree steps. + pub rotation: u8, + pub drop_chance: f32, + pub fixed: bool, + pub invisible: bool, + pub check_interval: u32, +} +impl ItemFrame { + pub fn step(&self) -> [i32; 3] { + [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ][usize::from(self.facing.min(5))] + } + pub fn kind(&self) -> &'static str { + if self.glow { + "minecraft:glow_item_frame" + } else { + "minecraft:item_frame" + } + } + /// ItemFrame.createBoundingBox (without a framed map): (min, max). + pub fn bounds(&self) -> ([f64; 3], [f64; 3]) { + let s = self.step().map(f64::from); + let c: [f64; 3] = std::array::from_fn(|i| f64::from(self.pos[i]) + 0.5 - s[i] * 0.46875); + let size: [f64; 3] = std::array::from_fn(|i| if s[i] != 0.0 { 0.0625 } else { 0.75 }); + ( + std::array::from_fn(|i| c[i] - size[i] / 2.0), + std::array::from_fn(|i| c[i] + size[i] / 2.0), + ) + } +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 3abdd6169..29912acd6 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -5,7 +5,7 @@ //! Horizon does not model (variants, attributes, equipment, custom names) //! survive a Horizon save. use crate::{ - entities::{Arrow, ExperienceOrb, ItemEntity, Painting}, + entities::{Arrow, ExperienceOrb, ItemEntity, ItemFrame, Painting}, mobs::{Mob, MobType}, save::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, @@ -485,3 +485,56 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> { let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8; Some((pos, facing, text(tag.get("variant"))?)) } +/// ItemFrame.addAdditionalSaveData. +pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { + let (lo, hi) = f.bounds(); + let base = Base { + id: f.kind(), + uuid, + position: Vec3::new( + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ), + motion: Vec3::ZERO, + rotation: [0.0, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "Facing", Tag::Byte(f.facing as i8)); + put(&mut tag, "block_pos", Tag::IntArray(f.pos.to_vec())); + put(&mut tag, "ItemRotation", Tag::Byte(f.rotation as i8)); + put( + &mut tag, + "ItemDropChance", + Tag::Float(f.drop_chance.to_bits()), + ); + put(&mut tag, "Invisible", Tag::Byte(i8::from(f.invisible))); + put(&mut tag, "Fixed", Tag::Byte(i8::from(f.fixed))); + if let Tag::Compound(map) = &mut tag { + map.remove(&horizon_world::nbt::JavaString::from("Item")); + } + if let Some(item) = &f.item { + put(&mut tag, "Item", item_to_nbt(item)); + } + tag +} +pub fn item_frame_from_nbt(tag: &Tag, id: u32) -> Option { + let pos = match tag.get("block_pos") { + Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], + _ => return None, + }; + Some(ItemFrame { + id, + pos, + facing: number(tag.get("Facing")).unwrap_or(2).clamp(0, 5) as u8, + glow: kind(tag).as_deref() == Some("minecraft:glow_item_frame"), + item: tag.get("Item").and_then(item_from_nbt), + rotation: (number(tag.get("ItemRotation")).unwrap_or(0) & 7) as u8, + drop_chance: float(tag.get("ItemDropChance")).map_or(1.0, |v| v as f32), + fixed: flag(tag, "Fixed"), + invisible: flag(tag, "Invisible"), + check_interval: 0, + }) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25ccdb0d..5f2fe7f3d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9,6 +9,7 @@ mod enchant_effects; mod end; mod explosion; mod fov; +mod frames; mod growth; mod machines; mod music; @@ -519,6 +520,9 @@ struct Game<'a> { falling: Vec, paintings: Vec, painting_variants: paintings::PaintingVariants, + item_frames: Vec, + frame_model: frames::FrameModel, + glow_frame_model: frames::FrameModel, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, creative_screen: Creative, @@ -1387,7 +1391,7 @@ impl Game<'_> { Ok(()) } fn use_item(&mut self) -> Result<()> { - if self.interact_mob()? { + if self.interact_frame() || self.interact_mob()? { return Ok(()); } let sneaking = self.keys.contains(&KeyCode::ShiftLeft); @@ -1471,7 +1475,7 @@ impl Game<'_> { return Ok(()); } if let Some(hit) = self.pick() - && self.place_painting(&hit, &stack) + && (self.place_painting(&hit, &stack) || self.place_item_frame(&hit, &stack)) { return Ok(()); } @@ -2043,6 +2047,7 @@ impl Game<'_> { self.tick_using(); self.titles.tick(); self.tick_paintings(); + self.tick_item_frames(); self.tick_mining()?; self.tick_items(); self.spawn_loaded_entities(); @@ -3501,6 +3506,7 @@ impl Game<'_> { } self.tnt_geometry(camera, alpha, &mut out); self.painting_geometry(camera, &mut out); + self.frame_geometry(camera, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; self.particles.render( @@ -3658,6 +3664,9 @@ impl Game<'_> { self.break_painting(i, true); return true; } + if self.attack_frame() { + return true; + } let Some((index, distance)) = self.mob_hit() else { return false; }; @@ -7010,6 +7019,9 @@ pub fn run() -> Result<()> { falling: Vec::new(), paintings: Vec::new(), painting_variants: paintings::PaintingVariants::load(&root), + item_frames: Vec::new(), + frame_model: frames::bake_frame(&root, "item_frame"), + glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), tnts: Vec::new(), hoppers: HashMap::new(), creative_screen: Creative::load(&game_root)?, diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs new file mode 100644 index 000000000..0631d812a --- /dev/null +++ b/crates/horizon-client/src/game/frames.rs @@ -0,0 +1,461 @@ +//! Item frames and glow item frames: `ItemFrameItem` placement on any face, +//! `ItemFrame.survives`, `interact` (put an item in, then rotate it), +//! `hurtServer` (take the item out, then break the frame) and +//! `ItemFrameRenderer` (the frame model and the item at a 45 degree step). +use super::{Game, Hit, Icon, view_vector}; +use horizon_assets::{bake::bake_model, model::CuboidModel, resolve::ModelLibrary}; +use horizon_client::{entities::ItemFrame, items::ItemStack, mesher::Vertex}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; +use std::sync::Arc; + +/// A baked frame model: (corners in block units, unit UVs, sprite) per quad. +pub(super) type FrameModel = Vec<([[f32; 3]; 4], [[f32; 2]; 4], String)>; + +/// Bake `block/` (item_frame / glow_item_frame) from the resources. +pub(super) fn bake_frame(root: &std::path::Path, name: &str) -> FrameModel { + let mut models = std::collections::BTreeMap::new(); + let mut pending = vec![format!("minecraft:block/{name}")]; + while let Some(model) = pending.pop() { + let Some((ns, path)) = model.split_once(':') else { + continue; + }; + let Ok(text) = + std::fs::read_to_string(root.join(format!("assets/{ns}/models/{path}.json"))) + else { + continue; + }; + let Ok(m) = CuboidModel::from_json(&text) else { + continue; + }; + if let Some(parent) = &m.parent { + pending.push(parent.clone()); + } + models.insert(model, m); + } + let Ok(library) = ModelLibrary::new(models) else { + return Vec::new(); + }; + let Ok(resolved) = library.resolve(&format!("minecraft:block/{name}")) else { + return Vec::new(); + }; + let Ok(quads) = bake_model(&resolved) else { + return Vec::new(); + }; + let unit = if quads + .iter() + .flat_map(|q| q.positions) + .any(|p| p.iter().any(|v| *v > 1.5)) + { + 16.0 + } else { + 1.0 + }; + quads + .into_iter() + .map(|q| { + ( + q.positions.map(|p| p.map(|v| v / unit)), + q.uv, + q.material + .sprite + .trim_start_matches("minecraft:") + .to_owned(), + ) + }) + .collect() +} +fn facing_of(face: [i32; 3]) -> u8 { + match face { + [0, -1, 0] => 0, + [0, 1, 0] => 1, + [0, 0, -1] => 2, + [0, 0, 1] => 3, + [-1, 0, 0] => 4, + _ => 5, + } +} +fn sound(f: &ItemFrame, what: &str) -> String { + let prefix = if f.glow { + "glow_item_frame" + } else { + "item_frame" + }; + format!("minecraft:entity.{prefix}.{what}") +} +fn center(f: &ItemFrame) -> [f64; 3] { + let (lo, hi) = f.bounds(); + std::array::from_fn(|i| (lo[i] + hi[i]) / 2.0) +} +impl Game<'_> { + /// `ItemFrame.survives` (not fixed): no collision, a solid block behind + /// (or a diode for wall frames), no overlapping hanging entity. + fn frame_survives(&self, f: &ItemFrame) -> bool { + if f.fixed { + return true; + } + let (lo, hi) = f.bounds(); + let bounds = Aabb::new( + Vec3::new(lo[0], lo[1], lo[2]), + Vec3::new(hi[0], hi[1], hi[2]), + ); + let mut scene = horizon_client::collisions::SceneCollisions { + world: &self.world, + binding: self.collision, + }; + if !scene.unobstructed(bounds).unwrap_or(false) { + return false; + } + let s = f.step(); + let behind = self.res.facts.get(self.world.block( + f.pos[0] - s[0], + f.pos[1] - s[1], + f.pos[2] - s[2], + )); + let supported = behind.legacy_solid || (s[1] == 0 && behind.has_class("DiodeBlock")); + // canCoexist(true): only hanging entities facing the same way block it. + let overlaps = |o: ([f64; 3], [f64; 3])| (0..3).all(|i| o.0[i] < hi[i] && lo[i] < o.1[i]); + supported + && !self + .item_frames + .iter() + .any(|o| o.id != f.id && o.facing == f.facing && overlaps(o.bounds())) + } + /// `ItemFrameItem.useOn`. + pub(super) fn place_item_frame(&mut self, hit: &Hit, stack: &ItemStack) -> bool { + let glow = match &*stack.item { + "minecraft:item_frame" => false, + "minecraft:glow_item_frame" => true, + _ => return false, + }; + let pos = std::array::from_fn(|i| hit.pos[i] + hit.face[i]); + let frame = ItemFrame { + id: self.next_entity + 1, + pos, + facing: facing_of(hit.face), + glow, + item: None, + rotation: 0, + drop_chance: 1.0, + fixed: false, + invisible: false, + check_interval: 0, + }; + if !self.frame_survives(&frame) { + return false; + } + self.next_entity += 1; + self.audio + .play(&sound(&frame, "place"), Some(center(&frame)), 1.0, 1.0); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.item_frames.push(frame); + if !self.creative { + self.consume_held(); + } + true + } + /// The frame under the crosshair within reach and its distance. + pub(super) fn frame_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + let mut best: Option<(usize, f64)> = None; + for (i, f) in self.item_frames.iter().enumerate() { + let (lo, hi) = f.bounds(); + let (mut t0, mut t1) = (0.0f64, reach); + let mut hit = true; + for a in 0..3 { + if dir[a].abs() < 1e-9 { + hit &= eye[a] >= lo[a] && eye[a] <= hi[a]; + continue; + } + let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]); + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + t0 = t0.max(ta); + t1 = t1.min(tb); + } + if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) { + best = Some((i, t0)); + } + } + best + } + /// Nearer than the targeted block? + pub(super) fn before_block(&self, distance: f64) -> bool { + self.pick().is_none_or(|h| { + let eye = self.eye_position().unwrap_or_default(); + (0..3) + .map(|a| (h.point[a] - eye[a]).powi(2)) + .sum::() + .sqrt() + > distance + }) + } + /// `ItemFrame.interact` for the frame under the crosshair. + pub(super) fn interact_frame(&mut self) -> bool { + let Some((i, d)) = self.frame_hit() else { + return false; + }; + if !self.before_block(d) || self.item_frames[i].fixed { + return false; + } + let at = center(&self.item_frames[i]); + if self.item_frames[i].item.is_none() { + let Some(held) = self.held().cloned() else { + return false; + }; + self.item_frames[i].item = Some(ItemStack { count: 1, ..held }); + self.audio + .play(&sound(&self.item_frames[i], "add_item"), Some(at), 1.0, 1.0); + if !self.creative { + self.consume_held(); + } + } else { + let f = &mut self.item_frames[i]; + f.rotation = (f.rotation + 1) % 8; + let s = sound(f, "rotate_item"); + self.audio.play(&s, Some(at), 1.0, 1.0); + } + let p = self.item_frames[i].pos; + self.world.modified.insert((p[0] >> 4, p[2] >> 4)); + self.swing_arm(); + true + } + /// `ItemFrame.hurtServer` from the player: the item comes out first. + pub(super) fn attack_frame(&mut self) -> bool { + let Some((i, d)) = self.frame_hit() else { + return false; + }; + if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { + return false; + } + if self.item_frames[i].fixed { + return true; + } + let with_frame = self.item_frames[i].item.is_none(); + let at = center(&self.item_frames[i]); + let f = if with_frame { + self.item_frames.remove(i) + } else { + self.item_frames[i].clone() + }; + self.audio.play( + &sound(&f, if with_frame { "break" } else { "remove_item" }), + Some(at), + 1.0, + 1.0, + ); + if !with_frame { + self.item_frames[i].item = None; + } + self.drop_frame_items(&f, with_frame, true); + self.world.modified.insert((f.pos[0] >> 4, f.pos[2] >> 4)); + true + } + /// `ItemFrame.dropItem`: the frame (when breaking) and the held item. + fn drop_frame_items(&mut self, f: &ItemFrame, with_frame: bool, by_player: bool) { + if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) { + return; + } + let s = f.step().map(f64::from); + let c = center(f); + let at = [c[0] + s[0] * 0.15, c[1], c[2] + s[2] * 0.15]; + if with_frame { + let frame = ItemStack { + item: Arc::from(f.kind()), + count: 1, + damage: 0, + extra: None, + }; + self.spawn_item(frame, at, [0.0; 3], 10); + } + if let Some(item) = f.item.clone() + && self.world.random.next_float() < f.drop_chance + { + self.spawn_item(item, at, [0.0; 3], 10); + } + } + /// BlockAttachedEntity.tick for frames. + pub(super) fn tick_item_frames(&mut self) { + let mut i = 0; + while i < self.item_frames.len() { + self.item_frames[i].check_interval += 1; + if self.item_frames[i].check_interval >= 100 { + self.item_frames[i].check_interval = 0; + let f = self.item_frames[i].clone(); + if !self.frame_survives(&f) { + self.item_frames.remove(i); + self.audio + .play(&sound(&f, "break"), Some(center(&f)), 1.0, 1.0); + self.drop_frame_items(&f, true, false); + continue; + } + } + i += 1; + } + } + /// ItemFrameRenderer: the frame model, then the item half size on its face. + pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { + let icons: Vec> = (0..self.item_frames.len()) + .map(|i| { + self.item_frames[i] + .item + .clone() + .and_then(|s| self.icon(&s.item)) + }) + .collect(); + let sprites = &self.res.atlas.sprites; + for (f, icon) in self.item_frames.iter().zip(icons) { + let s = f.step(); + // Pose: to the block centre, then X/Y rotation by facing. + let (x_rot, y_rot) = if s[1] == 0 { + let to_y = match f.facing { + 3 => 0.0, + 4 => 90.0, + 2 => 180.0, + _ => 270.0, + }; + (0.0f64, 180.0f64 - to_y) + } else { + (-90.0 * f64::from(s[1]), 180.0) + }; + let pose = glam::DMat4::from_translation( + glam::DVec3::new( + f64::from(f.pos[0]) + 0.5, + f64::from(f.pos[1]) + 0.5, + f64::from(f.pos[2]) + 0.5, + ) - camera, + ) * glam::DMat4::from_rotation_x(x_rot.to_radians()) + * glam::DMat4::from_rotation_y(y_rot.to_radians()); + let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let mut quad = + |m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| { + for (c, uv) in corners.iter().zip(uv) { + let p = m.transform_point3(glam::DVec3::from_array(*c)); + out.push(Vertex { + pos: p.as_vec3().to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light, + }); + } + }; + let map_uv = |r: &horizon_client::hud::Rect, uv: [[f32; 2]; 4]| { + uv.map(|[u, v]| [r.u0 + u * (r.u1 - r.u0), r.v0 + v * (r.v1 - r.v0)]) + }; + if !f.invisible { + let model = if f.glow { + &self.glow_frame_model + } else { + &self.frame_model + }; + for (corners, uv, sprite) in model { + let Some(r) = sprites.get(sprite) else { + continue; + }; + quad( + &pose, + corners.map(|c| { + [ + f64::from(c[0]) - 0.5, + f64::from(c[1]) - 0.5, + f64::from(c[2]) - 0.5, + ] + }), + map_uv(r, *uv), + packed, + ); + } + } + let Some(icon) = icon else { continue }; + // GlowItemFrame items render full bright. + let item_light = if f.glow { 240 | 240 << 8 } else { packed }; + let depth = if f.invisible { 0.5 } else { 0.4375 }; + let m = pose + * glam::DMat4::from_translation(glam::DVec3::new(0.0, 0.0, depth)) + * glam::DMat4::from_rotation_z((f64::from(f.rotation) * 45.0).to_radians()) + * glam::DMat4::from_scale(glam::DVec3::splat(0.5)); + let full = |r: &horizon_client::hud::Rect| { + [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]] + }; + match icon { + // A flat item faces out of the frame (towards -z here). + Icon::Flat(sprite) => { + if let Some(r) = sprites.get(&sprite) { + let z = -0.03125; + quad( + &m, + [ + [0.5, -0.5, z], + [-0.5, -0.5, z], + [-0.5, 0.5, z], + [0.5, 0.5, z], + ], + full(r), + item_light, + ); + } + } + Icon::Cube { + top, left, right, .. + } => { + let h = 0.25; + let face = |name: &str| sprites.get(name).copied(); + if let (Some(t), Some(l), Some(r)) = (face(&top), face(&left), face(&right)) { + let c = |x: f64, y: f64, z: f64| [x * h, y * h, z * h - h]; + quad( + &m, + [ + c(-1., 1., -1.), + c(1., 1., -1.), + c(1., 1., 1.), + c(-1., 1., 1.), + ], + full(&t), + item_light, + ); + quad( + &m, + [ + c(1., -1., -1.), + c(-1., -1., -1.), + c(-1., 1., -1.), + c(1., 1., -1.), + ], + full(&l), + item_light, + ); + quad( + &m, + [ + c(-1., -1., -1.), + c(-1., -1., 1.), + c(-1., 1., 1.), + c(-1., 1., -1.), + ], + full(&r), + item_light, + ); + quad( + &m, + [ + c(1., -1., 1.), + c(1., -1., -1.), + c(1., 1., -1.), + c(1., 1., 1.), + ], + full(&r), + item_light, + ); + } + } + } + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 037dc1365..ad9696c1a 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -130,6 +130,13 @@ impl Game<'_> { }); } } + "minecraft:item_frame" | "minecraft:glow_item_frame" => { + self.next_entity += 1; + if let Some(f) = entity_nbt::item_frame_from_nbt(&tag, self.next_entity) { + self.remember(f.id, uuid, tag); + self.item_frames.push(f); + } + } "minecraft:painting" => { if let Some((pos, facing, variant)) = entity_nbt::painting_from_nbt(&tag) && let Some(v) = self.painting_variants.get(&variant).cloned() @@ -267,6 +274,24 @@ impl Game<'_> { out.entry(chunk_of(f.position)).or_default().push(tag); } } + for f in &self.item_frames { + let (lo, hi) = f.bounds(); + let at = Vec3::new( + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ); + if keys.contains(&chunk_of(at)) { + let uuid = self + .persist + .uuids + .get(&f.id) + .copied() + .unwrap_or_else(random_uuid); + let tag = entity_nbt::item_frame_to_nbt(f, uuid, self.persist.raw.get(&f.id)); + out.entry(chunk_of(at)).or_default().push(tag); + } + } for p in &self.paintings { let at = painting_center(p); if keys.contains(&chunk_of(at)) { @@ -293,6 +318,18 @@ impl Game<'_> { if remove { let gone = |p: Vec3| keys.contains(&chunk_of(p)); let mut removed: Vec = Vec::new(); + self.item_frames.retain(|f| { + let (lo, hi) = f.bounds(); + let keep = !gone(Vec3::new( + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + )); + if !keep { + removed.push(f.id); + } + keep + }); self.paintings.retain(|p| { let keep = !gone(painting_center(p)); if !keep {