diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index eda89c2ad..e26dc5d3a 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -330,3 +330,56 @@ impl Experience { self.level > start } } +/// A painting (`Painting`, a `HangingEntity`): the block it hangs in, the +/// 2D data value of the direction it faces, and its variant. +#[derive(Clone, Debug)] +pub struct Painting { + pub id: u32, + pub pos: [i32; 3], + /// Direction.get2DDataValue: south 0, west 1, north 2, east 3. + pub facing: u8, + pub variant: std::sync::Arc, + pub width: i32, + pub height: i32, + /// BlockAttachedEntity.checkInterval. + pub check_interval: u32, +} +impl Painting { + pub fn step(&self) -> [i32; 3] { + [[0, 0, 1], [-1, 0, 0], [0, 0, -1], [1, 0, 0]][usize::from(self.facing & 3)] + } + /// Direction.getCounterClockWise (the painting's left as it faces out). + pub fn left(&self) -> [i32; 3] { + [[1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1]][usize::from(self.facing & 3)] + } + /// Painting.calculateBoundingBox: (min, max). + pub fn bounds(&self) -> ([f64; 3], [f64; 3]) { + let s = self.step().map(f64::from); + let l = self.left().map(f64::from); + let off = |n: i32| if n % 2 == 0 { 0.5 } else { 0.0 }; + let (h, v) = (off(self.width), off(self.height)); + let c = [ + f64::from(self.pos[0]) + 0.5 - s[0] * 0.46875 + l[0] * h, + f64::from(self.pos[1]) + 0.5 + v, + f64::from(self.pos[2]) + 0.5 - s[2] * 0.46875 + l[2] * h, + ]; + let along_x = s[0] != 0.0; + let size = [ + if along_x { + 0.0625 + } else { + f64::from(self.width) + }, + f64::from(self.height), + if along_x { + f64::from(self.width) + } else { + 0.0625 + }, + ]; + ( + 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 d63f5c5cf..3abdd6169 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}, + entities::{Arrow, ExperienceOrb, ItemEntity, Painting}, mobs::{Mob, MobType}, save::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, @@ -454,3 +454,34 @@ mod tests { assert_eq!(back[0].value, 7); } } +/// Painting.addAdditionalSaveData: `facing`, `variant` and `block_pos`. +pub fn painting_to_nbt(p: &Painting, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { + let (lo, hi) = p.bounds(); + let base = Base { + id: "minecraft:painting", + 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: [f32::from(p.facing) * 90.0, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "facing", Tag::Byte(p.facing as i8)); + put(&mut tag, "variant", string(&p.variant)); + put(&mut tag, "block_pos", Tag::IntArray(p.pos.to_vec())); + tag +} +/// The block position, facing and variant of a saved painting. +pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> { + let pos = match tag.get("block_pos") { + Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], + _ => return None, + }; + let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8; + Some((pos, facing, text(tag.get("variant"))?)) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a2e4d3041..a25ccdb0d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -14,6 +14,7 @@ mod machines; mod music; mod options; mod packs; +mod paintings; mod persist; mod postprocess; mod potions; @@ -516,6 +517,8 @@ struct Game<'a> { tick_chunks: HashSet<(i32, i32)>, level_events: Vec, falling: Vec, + paintings: Vec, + painting_variants: paintings::PaintingVariants, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, creative_screen: Creative, @@ -1467,6 +1470,11 @@ impl Game<'_> { if self.use_tool(&stack)? { return Ok(()); } + if let Some(hit) = self.pick() + && self.place_painting(&hit, &stack) + { + return Ok(()); + } if self.use_ender_eye(&stack)? { return Ok(()); } @@ -2034,6 +2042,7 @@ impl Game<'_> { self.tick_burning(); self.tick_using(); self.titles.tick(); + self.tick_paintings(); self.tick_mining()?; self.tick_items(); self.spawn_loaded_entities(); @@ -3491,6 +3500,7 @@ impl Game<'_> { } } self.tnt_geometry(camera, alpha, &mut out); + self.painting_geometry(camera, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; self.particles.render( @@ -3633,6 +3643,21 @@ impl Game<'_> { } /// Player.attack with the attack-strength charge, crits and knockback. fn attack(&mut self) -> bool { + // A painting nearer than the targeted block and mob breaks instead. + if let Some((i, d)) = self.painting_hit() + && self.mob_hit().is_none_or(|m| d < m.1) + && 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() + > d + }) + { + self.break_painting(i, true); + return true; + } let Some((index, distance)) = self.mob_hit() else { return false; }; @@ -6983,6 +7008,8 @@ pub fn run() -> Result<()> { tick_chunks: HashSet::new(), level_events: Vec::new(), falling: Vec::new(), + paintings: Vec::new(), + painting_variants: paintings::PaintingVariants::load(&root), tnts: Vec::new(), hoppers: HashMap::new(), creative_screen: Creative::load(&game_root)?, diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs new file mode 100644 index 000000000..2c078c11e --- /dev/null +++ b/crates/horizon-client/src/game/paintings.rs @@ -0,0 +1,369 @@ +//! Paintings: `HangingEntityItem.useOn` placement with `Painting.create`'s +//! variant choice, `HangingEntity.survives` checks every 100 ticks, +//! breaking by attack (`dropItem`), saving, and `PaintingRenderer` quads. +use super::{Game, Hit, view_vector}; +use horizon_client::{entities::Painting, items::ItemStack, mesher::Vertex}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; +use std::sync::Arc; + +/// A `painting_variant` and whether `#placeable` lists it (in tag order). +#[derive(Clone, Debug)] +pub(super) struct Variant { + pub id: Arc, + pub asset: String, + pub width: i32, + pub height: i32, +} +/// Variants by id plus the `#minecraft:placeable` list. +#[derive(Default)] +pub(super) struct PaintingVariants { + pub all: Vec, + pub placeable: Vec>, +} +impl PaintingVariants { + pub fn load(root: &std::path::Path) -> Self { + let data = root.join("data/minecraft"); + let mut all = Vec::new(); + if let Ok(entries) = std::fs::read_dir(data.join("painting_variant")) { + for e in entries.flatten() { + let path = e.path(); + let Some(name) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Ok(bytes) = std::fs::read(&path) else { + continue; + }; + let Ok(v) = serde_json::from_slice::(&bytes) else { + continue; + }; + all.push(Variant { + id: Arc::from(format!("minecraft:{name}")), + asset: v["asset_id"] + .as_str() + .unwrap_or(name) + .trim_start_matches("minecraft:") + .to_owned(), + width: v["width"].as_i64().unwrap_or(1) as i32, + height: v["height"].as_i64().unwrap_or(1) as i32, + }); + } + } + let placeable = std::fs::read(data.join("tags/painting_variant/placeable.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| v["values"].as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|v| v.as_str().map(Arc::from)) + .collect(); + Self { all, placeable } + } + pub fn get(&self, id: &str) -> Option<&Variant> { + self.all.iter().find(|v| &*v.id == id) + } +} +fn overlaps(a: ([f64; 3], [f64; 3]), b: ([f64; 3], [f64; 3])) -> bool { + (0..3).all(|i| a.0[i] < b.1[i] && b.0[i] < a.1[i]) +} +impl Game<'_> { + /// `HangingEntity.survives`: no block collision in the box, solid blocks + /// (or diodes) behind it and no other painting overlapping it. + pub(super) fn painting_survives(&self, p: &Painting) -> bool { + let (lo, hi) = p.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; + } + // calculateSupportBox: moved half a block into the wall, deflated. + let s = p.step().map(f64::from); + let (slo, shi) = ( + std::array::from_fn::(|i| lo[i] - s[i] * 0.5 + 1.0e-7), + std::array::from_fn::(|i| hi[i] - s[i] * 0.5 - 1.0e-7), + ); + for x in slo[0].floor() as i32..=shi[0].floor() as i32 { + for y in slo[1].floor() as i32..=shi[1].floor() as i32 { + for z in slo[2].floor() as i32..=shi[2].floor() as i32 { + let f = self.res.facts.get(self.world.block(x, y, z)); + if !(f.legacy_solid || f.has_class("DiodeBlock")) { + return false; + } + } + } + } + !self + .paintings + .iter() + .any(|o| o.id != p.id && overlaps(o.bounds(), (lo, hi))) + } + /// `HangingEntityItem.useOn` for a painting against `hit`'s face. + pub(super) fn place_painting(&mut self, hit: &Hit, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:painting" || hit.face[1] != 0 { + return false; + } + let facing = match hit.face { + [0, 0, 1] => 0, + [-1, 0, 0] => 1, + [0, 0, -1] => 2, + _ => 3, + }; + let pos = [ + hit.pos[0] + hit.face[0], + hit.pos[1], + hit.pos[2] + hit.face[2], + ]; + self.next_entity += 1; + let mut candidate = Painting { + id: self.next_entity, + pos, + facing, + variant: Arc::from(""), + width: 1, + height: 1, + check_interval: 0, + }; + // Painting.create: the largest placeable variants that survive, one at random. + let mut fitting: Vec = Vec::new(); + for id in self.painting_variants.placeable.clone() { + let Some(v) = self.painting_variants.get(&id).cloned() else { + continue; + }; + (candidate.width, candidate.height) = (v.width, v.height); + if self.painting_survives(&candidate) { + fitting.push(v); + } + } + let Some(largest) = fitting.iter().map(|v| v.width * v.height).max() else { + return false; + }; + fitting.retain(|v| v.width * v.height >= largest); + let pick = self + .world + .random + .next_int_bound(fitting.len() as i32) + .unwrap_or(0) as usize; + let v = &fitting[pick]; + (candidate.variant, candidate.width, candidate.height) = (v.id.clone(), v.width, v.height); + let (lo, hi) = candidate.bounds(); + let at = [ + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ]; + self.audio + .play("minecraft:entity.painting.place", Some(at), 1.0, 1.0); + self.paintings.push(candidate); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + if !self.creative { + self.consume_held(); + } + true + } + /// The painting under the crosshair within reach and its distance. + pub(super) fn painting_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, p) in self.paintings.iter().enumerate() { + let (lo, hi) = p.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 + } + /// `Painting.hurtServer` -> kill and `dropItem`. + pub(super) fn break_painting(&mut self, index: usize, by_player: bool) { + let p = self.paintings.remove(index); + let (lo, hi) = p.bounds(); + let at = [ + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ]; + self.world.modified.insert((p.pos[0] >> 4, p.pos[2] >> 4)); + if !self.ui.rules.bool("entity_drops") { + return; + } + self.audio + .play("minecraft:entity.painting.break", Some(at), 1.0, 1.0); + if by_player && self.creative { + return; + } + // HangingEntity.spawnAtLocation: 0.15 out from the wall. + let s = p.step().map(f64::from); + let stack = ItemStack { + item: Arc::from("minecraft:painting"), + count: 1, + damage: 0, + extra: None, + }; + self.spawn_item( + stack, + [at[0] + s[0] * 0.15, at[1], at[2] + s[2] * 0.15], + [0.0; 3], + 10, + ); + } + /// BlockAttachedEntity.tick: check survival every 100 ticks. + pub(super) fn tick_paintings(&mut self) { + let mut i = 0; + while i < self.paintings.len() { + self.paintings[i].check_interval += 1; + if self.paintings[i].check_interval >= 100 { + self.paintings[i].check_interval = 0; + let p = self.paintings[i].clone(); + if !self.painting_survives(&p) { + self.break_painting(i, false); + continue; + } + } + i += 1; + } + } + /// PaintingRenderer: the variant on the front, the back texture behind and + /// on the edges. + pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec) { + let sprites = &self.res.atlas.sprites; + let Some(back) = sprites.get("painting/back").copied() else { + return; + }; + for p in &self.paintings { + let Some(v) = self.painting_variants.get(&p.variant) else { + continue; + }; + let Some(front) = sprites.get(&format!("painting/{}", v.asset)).copied() else { + continue; + }; + let (lo, hi) = p.bounds(); + let c = glam::DVec3::new( + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ) - camera; + let s = p.step().map(f64::from); + let l = p.left().map(f64::from); + let out_dir = glam::DVec3::new(s[0], 0.0, s[2]); + // The viewer's right is the painting's left. + let right = glam::DVec3::new(l[0], 0.0, l[2]); + let up = glam::DVec3::Y; + let (hw, hh, d) = ( + f64::from(p.width) / 2.0, + f64::from(p.height) / 2.0, + 1.0 / 32.0, + ); + let light = self.world.light(p.pos[0], p.pos[1], p.pos[2]); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let mut quad = |corners: [glam::DVec3; 4], uv: [[f32; 2]; 4], shade: f32| { + let k = (255.0 * shade) as u32; + let color = 0xFF00_0000 | k << 16 | k << 8 | k; + for (p, uv) in corners.iter().zip(uv) { + out.push(Vertex { + pos: p.as_vec3().to_array(), + uv, + layer: 0, + color, + light: packed, + }); + } + }; + let full = |r: horizon_client::hud::Rect| { + [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]] + }; + let f = c + out_dir * d; + quad( + [ + f - right * hw - up * hh, + f + right * hw - up * hh, + f + right * hw + up * hh, + f - right * hw + up * hh, + ], + full(front), + 1.0, + ); + let b = c - out_dir * d; + quad( + [ + b + right * hw - up * hh, + b - right * hw - up * hh, + b - right * hw + up * hh, + b + right * hw + up * hh, + ], + full(back), + 0.8, + ); + // Edges: a one-pixel strip of the back texture. + let strip = [ + [back.u0, back.v0 + (back.v1 - back.v0) / 16.0], + [back.u1, back.v0 + (back.v1 - back.v0) / 16.0], + [back.u1, back.v0], + [back.u0, back.v0], + ]; + let (t, bt) = (up * hh, -up * hh); + quad( + [ + b + t + right * hw, + b + t - right * hw, + f + t - right * hw, + f + t + right * hw, + ], + strip, + 1.0, + ); + quad( + [ + f + bt + right * hw, + f + bt - right * hw, + b + bt - right * hw, + b + bt + right * hw, + ], + strip, + 0.5, + ); + quad( + [ + b - right * hw - up * hh, + f - right * hw - up * hh, + f - right * hw + up * hh, + b - right * hw + up * hh, + ], + strip, + 0.6, + ); + quad( + [ + f + right * hw - up * hh, + b + right * hw - up * hh, + b + right * hw + up * hh, + f + right * hw + up * hh, + ], + strip, + 0.6, + ); + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 96b260381..037dc1365 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -27,6 +27,14 @@ pub struct EntityMemory { unknown: HashMap<(i32, i32), Vec>, } +fn painting_center(p: &horizon_client::entities::Painting) -> Vec3 { + let (lo, hi) = p.bounds(); + Vec3::new( + (lo[0] + hi[0]) / 2.0, + (lo[1] + hi[1]) / 2.0, + (lo[2] + hi[2]) / 2.0, + ) +} fn chunk_of(p: Vec3) -> (i32, i32) { ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4) } @@ -122,6 +130,26 @@ impl Game<'_> { }); } } + "minecraft:painting" => { + if let Some((pos, facing, variant)) = entity_nbt::painting_from_nbt(&tag) + && let Some(v) = self.painting_variants.get(&variant).cloned() + { + self.next_entity += 1; + let id = self.next_entity; + self.remember(id, uuid, tag); + self.paintings.push(horizon_client::entities::Painting { + id, + pos, + facing, + variant: v.id, + width: v.width, + height: v.height, + check_interval: 0, + }); + } else { + self.persist.unknown.entry(key).or_default().push(tag); + } + } _ if self.res.mob_types.contains_key(&kind) => { self.next_entity += 1; if let Some(m) = @@ -239,6 +267,19 @@ impl Game<'_> { out.entry(chunk_of(f.position)).or_default().push(tag); } } + for p in &self.paintings { + let at = painting_center(p); + if keys.contains(&chunk_of(at)) { + let uuid = self + .persist + .uuids + .get(&p.id) + .copied() + .unwrap_or_else(random_uuid); + let tag = entity_nbt::painting_to_nbt(p, uuid, self.persist.raw.get(&p.id)); + out.entry(chunk_of(at)).or_default().push(tag); + } + } for key in keys { let unknown = if remove { self.persist.unknown.remove(key) @@ -252,6 +293,13 @@ impl Game<'_> { if remove { let gone = |p: Vec3| keys.contains(&chunk_of(p)); let mut removed: Vec = Vec::new(); + self.paintings.retain(|p| { + let keep = !gone(painting_center(p)); + if !keep { + removed.push(p.id); + } + keep + }); self.mobs.retain(|m| { let keep = !gone(m.position); if !keep { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index e4e6b6b49..e7d904b5d 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -75,6 +75,7 @@ impl HudAtlas { walk(&textures.join("font"), &mut files); walk(&textures.join("environment"), &mut files); walk(&textures.join("misc"), &mut files); + walk(&textures.join("painting"), &mut files); walk(&textures.join("entity"), &mut files); walk(&textures.join("particle"), &mut files); walk(&textures.join("mob_effect"), &mut files);