From 95d1371daed6231b423baa4e2bb595bc11884192 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:40:00 +0200 Subject: [PATCH] WIP snapshot: unfinished render parity work (paused mid-task, may not build) Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/block_entity_render.rs | 103 ++++++++++ crates/horizon-client/src/containers.rs | 8 + crates/horizon-client/src/game.rs | 23 +++ crates/horizon-client/src/game/control.rs | 2 +- .../horizon-client/src/game/render_control.rs | 11 ++ crates/horizon-client/src/game/sign_edit.rs | 140 ++++++++++++++ crates/horizon-client/src/hud.rs | 4 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/save.rs | 2 + crates/horizon-client/src/signs.rs | 179 ++++++++++++++++++ 10 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/game/sign_edit.rs create mode 100644 crates/horizon-client/src/signs.rs diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index fc44dff25..70670e167 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -286,6 +286,12 @@ enum Kind { pose: &'static str, facing: &'static str, }, + /// Sign text (`StandingSignRenderer` / `HangingSignRenderer`); the boards are block models. + Sign { + hanging: bool, + wall: bool, + angle: f32, + }, } fn intern(facing: &str) -> &'static str { match facing { @@ -324,6 +330,15 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { double_with: other, } }; + if let Some(hanging) = crate::signs::sign_kind(name) { + let wall = name.contains("_wall_"); + let angle = if wall { + y_rot(facing()) + } else { + prop("rotation").and_then(|r| r.parse::().ok()).unwrap_or(0.0) * 22.5 + }; + return Kind::Sign { hanging, wall, angle }; + } let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); match unwaxed { "chest" => { @@ -581,6 +596,58 @@ fn frac(x: f32) -> f32 { x - x.floor() } +/// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text +/// full-bright with an 8x outline in the dark colour. +fn sign_text(scene: &Scene, data: &crate::signs::SignData, text: &crate::signs::SignText, m: Mat4, packed: u8, near: bool, out: &mut Vec) { + let line_height = data.line_height(); + let midpoint = (4.0 * line_height / 2.0).floor(); + let dark = text.dark_color(); + let (color, outline, light) = if text.glowing { + let c = text.text_color(); + (c, (c == 0 || near).then_some(dark), 240 | 240 << 8) + } else { + (dark, None, vertex_light(packed)) + }; + let width = |s: &str| s.chars().map(|c| (scene.glyph)(c).map_or(6.0, |g| g.1)).sum::(); + for (i, line) in text.lines.iter().enumerate() { + // Font.split(line, maxWidth).get(0): keep what fits. + let mut shown = String::new(); + for ch in line.chars() { + shown.push(ch); + if width(&shown) > data.max_line_width() { + shown.pop(); + break; + } + } + let x0 = -(width(&shown) as i32 / 2) as f32; + let y0 = i as f32 * line_height - midpoint; + let mut emit = |dx: f32, dy: f32, rgb: u32| { + let mut x = x0 + dx; + for ch in shown.chars() { + let Some((r, advance)) = (scene.glyph)(ch) else { + x += 6.0; + continue; + }; + if ch != ' ' { + let corners = [(x, y0 + dy + 8.0), (x + 8.0, y0 + dy + 8.0), (x + 8.0, y0 + dy), (x, y0 + dy)]; + let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; + let c = 0xFF00_0000 | (rgb & 255) << 16 | (rgb >> 8 & 255) << 8 | (rgb >> 16 & 255); + for ((cx, cy), uv) in corners.into_iter().zip(uvs) { + out.push(Vertex { pos: m.transform_point3(Vec3::new(cx, cy, 0.0)).to_array(), uv, layer: 0, color: c, light }); + } + } + x += advance; + } + }; + if let Some(o) = outline { + for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] { + emit(dx, dy, o); + } + } + emit(0.0, 0.0, color); + } +} + /// Inputs from the game for one frame of block-entity rendering. pub struct Scene<'a> { pub camera: DVec3, @@ -591,6 +658,10 @@ pub struct Scene<'a> { pub nether: bool, /// Chest lid openness (`ChestLidController.getOpenNess`) at a position. pub lid: &'a dyn Fn([i32; 3]) -> f32, + /// Sign block-entity data at a position. + pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Font glyph cell and advance. + pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, } pub struct BlockEntityRenderer { @@ -734,6 +805,38 @@ impl BlockEntityRenderer { let none = |_: &str, _: &mut [f32; 9]| {}; match kind { Kind::None => {} + Kind::Sign { hanging, wall, angle } => { + let Some(data) = (scene.sign)(pos) else { return }; + let s = Vec3::new(1.0, -1.0, 1.0); + for (front, text) in [(true, &data.front), (false, &data.back)] { + if text.is_empty() { + continue; + } + let mut m = base; + if *hanging { + // HangingSignRenderer.textTransformation. + m *= Mat4::from_translation(Vec3::new(0.5, 0.9375, 0.5)) + * Mat4::from_rotation_y((-angle).to_radians()) + * Mat4::from_translation(Vec3::new(0.0, -0.3125, 0.0)); + if !front { + m *= Mat4::from_rotation_y(PI); + } + m *= Mat4::from_translation(Vec3::new(0.0, -0.32, 0.073)) * Mat4::from_scale(s * 0.014_062_5); + } else { + // StandingSignRenderer.textTransformation. + m *= Mat4::from_translation(Vec3::splat(0.5)) * Mat4::from_rotation_y((-angle).to_radians()); + if *wall { + m *= Mat4::from_translation(Vec3::new(0.0, -0.3125, -0.4375)); + } + if !front { + m *= Mat4::from_rotation_y(PI); + } + m *= Mat4::from_translation(Vec3::new(0.0, 1.0 / 3.0, 0.046_666_667)) * Mat4::from_scale(s * 0.010_416_667); + } + let near = DVec3::new(f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5).distance_squared(scene.camera) < 256.0; + sign_text(scene, data, text, m, packed, near, out); + } + } Kind::Chest { texture, part, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 2eed1860c..d6045fe92 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -49,9 +49,14 @@ pub struct Furnace { pub enum BlockEntity { Chest(Vec>), Furnace(Furnace), + /// Signs and hanging signs (`SignBlockEntity`). + Sign(crate::signs::SignData), } impl BlockEntity { pub fn for_block(name: &str) -> Option { + if let Some(hanging) = crate::signs::sign_kind(name) { + return Some(Self::Sign(crate::signs::SignData { hanging, ..Default::default() })); + } if let Some(kind) = FurnaceKind::from_block(name) { return Some(Self::Furnace(Furnace { kind, @@ -77,18 +82,21 @@ impl BlockEntity { FurnaceKind::BlastFurnace => "minecraft:blast_furnace", FurnaceKind::Smoker => "minecraft:smoker", }, + Self::Sign(s) => s.id(), } } pub fn contents(&self) -> Vec { match self { Self::Chest(items) => items.iter().flatten().cloned().collect(), Self::Furnace(f) => f.items.iter().flatten().cloned().collect(), + Self::Sign(_) => Vec::new(), } } pub fn slots_mut(&mut self) -> &mut [Option] { match self { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, + Self::Sign(_) => &mut [], } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 956fde96c..fc246b17b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3,6 +3,7 @@ mod control; mod render_control; mod render_tick; +mod sign_edit; use horizon_client::{ Result, assets::Assets, @@ -345,6 +346,8 @@ struct Game<'a> { dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, + /// Sign text being edited (`SignEditScreen`). + sign_edit: Option, spawn_search: u32, mobs: Vec, arrows: Vec, @@ -1020,7 +1023,11 @@ impl Game<'_> { }; let target = [pos.x, pos.y, pos.z]; if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + let sign = matches!(entity, BlockEntity::Sign(_)); self.world.block_entities.insert((target[0], target[1], target[2]), entity); + if sign { + self.open_sign_editor((target[0], target[1], target[2]), true); + } } self.swing_arm(); let sounds = self.res.facts.get(state).sounds.clone(); @@ -1718,6 +1725,7 @@ impl Game<'_> { } Screen::Playing | Screen::Options => {} } + self.draw_sign_editor(&mut batch); batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { @@ -1733,6 +1741,7 @@ impl Game<'_> { match self.container_kind() { Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)), Some(BlockEntity::Furnace(_)) => v.extend(300..303), + Some(BlockEntity::Sign(_)) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); v.push(200); @@ -1844,6 +1853,7 @@ impl Game<'_> { part(batch, "gui/sprites/container/furnace/burn_progress", 0.0, 0.0, w, 16.0, ox + 79.0, oy + 34.0); } } + Some(BlockEntity::Sign(_)) => {} None => { let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" }; part(batch, texture, 0.0, 0.0, 176.0, 166.0, ox, oy); @@ -2141,6 +2151,11 @@ impl Game<'_> { sprites: &self.res.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, + sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { + Some(BlockEntity::Sign(sign)) => Some(sign), + _ => None, + }, + glyph: &|c| self.res.atlas.glyph(c), }; self.res.block_entity_render.render(&scene, r.block_entities(), &mut out); } @@ -4440,6 +4455,12 @@ impl ApplicationHandler for Game<'_> { } } WindowEvent::MouseInput { .. } if self.title.is_some() => {} + WindowEvent::MouseInput { state, button, .. } if self.sign_edit.is_some() => { + if state == ElementState::Pressed && button == MouseButton::Left { + let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); + self.sign_edit_click(size); + } + } WindowEvent::MouseInput { state, button, .. } => { let pressed = state == ElementState::Pressed; match self.screen { @@ -4483,6 +4504,7 @@ impl ApplicationHandler for Game<'_> { _ => {} } } + WindowEvent::KeyboardInput { event, .. } if self.sign_edit.is_some() => self.sign_edit_key(&event), WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => @@ -4753,6 +4775,7 @@ pub fn run() -> Result<()> { dropped: Vec::new(), next_entity: 0, particles, + sign_edit: None, spawn_search: 0, mobs: Vec::new(), arrows: Vec::new(), diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 1f46c678b..a358cb3e6 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -66,7 +66,7 @@ impl Game<'_> { let ok = || Ok(Some(json!({ "ok": true }))); match words[0] { "help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::render_control::HELP).collect::>() }))), - "setblock" | "fill" | "particle" => self.render_command(&words), + "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index dc198971d..c5a70aea6 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -10,6 +10,7 @@ pub const HELP: &[&str] = &[ "setblock X Y Z STATE set a block state (name[prop=value,...]) without updates", "fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates", "particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)", + "signedit X Y Z [front|back] open the sign editor for the sign at X Y Z", ]; impl Game<'_> { @@ -102,6 +103,16 @@ impl Game<'_> { } Ok(Some(json!({ "ok": true, "live": self.particles.len() }))) } + "signedit" => { + let key = (int(1)?, int(2)?, int(3)?); + let name = self.res.facts.get(self.world.block(key.0, key.1, key.2)).name.clone(); + let entity = horizon_client::containers::BlockEntity::for_block(&name) + .filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_))) + .ok_or("no sign there")?; + self.world.block_entities.entry(key).or_insert(entity); + self.open_sign_editor(key, words.get(4) != Some(&"back")); + Ok(Some(json!({ "ok": true }))) + } other => Err(format!("unknown render command {other}").into()), } } diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs new file mode 100644 index 000000000..795b29457 --- /dev/null +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -0,0 +1,140 @@ +//! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`): +//! opened when a sign is placed, four lines limited to the sign's line +//! width, Up/Down/Enter move between lines, Escape or Done closes. +use super::Game; +use horizon_client::{ + containers::BlockEntity, + hud::{HudBatch, rgba}, + signs::{SignData, wood_type}, +}; +use std::time::Instant; +use winit::{ + event::{ElementState, KeyEvent}, + keyboard::{KeyCode, PhysicalKey}, +}; + +pub(super) struct SignEditor { + pub pos: (i32, i32, i32), + pub front: bool, + pub line: usize, + pub opened: Instant, +} + +impl Game<'_> { + fn edited_sign(&mut self) -> Option<&mut SignData> { + let key = self.sign_edit.as_ref()?.pos; + match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Sign(sign)) => Some(sign), + _ => None, + } + } + /// `SignBlock.openTextEdit` for the front side after placement. + pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { + self.sign_edit = Some(SignEditor { pos, front, line: 0, opened: Instant::now() }); + self.keys.clear(); + self.right = false; + self.capture(false); + } + fn close_sign_editor(&mut self) { + if let Some(edit) = self.sign_edit.take() { + self.world.modified.insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + } + self.capture(true); + } + pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) { + if event.state != ElementState::Pressed { + return; + } + let Some(edit) = self.sign_edit.as_mut() else { return }; + let front = edit.front; + match event.physical_key { + PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(), + PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3, + PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => edit.line = (edit.line + 1) & 3, + PhysicalKey::Code(KeyCode::Backspace) => { + let line = edit.line; + if let Some(sign) = self.edited_sign() { + let text = if front { &mut sign.front } else { &mut sign.back }; + text.lines[line].pop(); + } + } + _ => { + let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else { return }; + let line = edit.line; + let atlas = &self.res.atlas; + let width = |s: &str| HudBatch::text_width(atlas, s); + let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return }; + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) { + let max = sign.max_line_width(); + let text = if front { &mut sign.front } else { &mut sign.back }; + for ch in typed.chars().filter(|c| !c.is_control()) { + let mut next = text.lines[line].clone(); + next.push(ch); + // TextFieldHelper filter: font.width(s) <= maxTextLineWidth. + if width(&next) <= max { + text.lines[line] = next; + } + } + } + } + } + } + /// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20). + pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) { + let b = HudBatch::new(size); + let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0); + let (mx, my) = self.cursor; + if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 { + self.close_sign_editor(); + } + } + pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) { + let Some(edit) = &self.sign_edit else { return }; + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return }; + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); + let title = if sign.hanging { "Edit Hanging Sign Message" } else { "Edit Sign Message" }; + let tw = HudBatch::text_width(atlas, title); + batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); + let name = self.res.facts.get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)).name.clone(); + let wood = wood_type(&name); + let cx = w / 2.0; + let y = if sign.hanging { + // HangingSignEditScreen: 16x16 texture scaled 4.5 at (0, -13). + let s = 4.5; + batch.sprite_scaled(atlas, &format!("gui/hanging_signs/{wood}"), cx - 8.0 * s, 125.0 - 13.0 - 8.0 * s, 16.0 * s, 16.0 * s, u32::MAX); + 125.0 + } else { + // SignEditScreen: 24x26 texture scaled 3.9 at (0, 27); wall signs show 12 rows. + let s = 3.9; + let wall = name.contains("_wall_"); + let rows = if wall { 12.0 } else { 26.0 }; + if let Some(mut r) = atlas.sprites.get(&format!("gui/signs/{wood}")).copied() { + r.v1 = r.v0 + (r.v1 - r.v0) * rows / 26.0; + batch.rect_uv(cx - 12.0 * s, 90.0 + 27.0 - 13.0 * s, 24.0 * s, rows * s, r, u32::MAX); + } + 90.0 + }; + let text = if edit.front { &sign.front } else { &sign.back }; + let color = if text.glowing { text.text_color() } else { text.dark_color() }; + let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255); + let line_height = sign.line_height(); + let midpoint = (4.0 * line_height / 2.0).floor(); + let blink = (edit.opened.elapsed().as_millis() / 300) % 2 == 0; + for (i, line) in text.lines.iter().enumerate() { + let lw = HudBatch::text_width(atlas, line); + let x = cx - (lw as i32 / 2) as f32; + let ly = y + i as f32 * line_height - midpoint; + batch.text(atlas, line, x, ly, color, false); + if i == edit.line && blink { + // TextCursorUtils.extractAppendCursor: an underscore after the text. + batch.text(atlas, "_", x + lw, ly, color, false); + } + } + let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0); + batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX); + let tw = HudBatch::text_width(atlas, "Done"); + batch.text(atlas, "Done", bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); + } +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index fa6a0f20e..204b0e047 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -61,6 +61,10 @@ fn walk(dir: &Path, out: &mut Vec) { } } impl HudAtlas { + /// A font glyph's atlas cell (8x8 GUI pixels) and advance. + pub fn glyph(&self, ch: char) -> Option<(Rect, f32)> { + self.glyphs.get(&ch).map(|g| (g.rect, g.advance)) + } pub fn build(root: &Path) -> Result { let textures = root.join("assets/minecraft/textures"); let mut files = Vec::new(); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 61d6648b4..f1282a34f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -36,6 +36,7 @@ pub mod save; pub mod screen_effects; pub mod settings; pub mod shadows; +pub mod signs; pub mod sprint; pub mod sprites; pub mod streaming; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6997be4f8..5fd23e9c6 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -110,6 +110,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity) - entries.push(("cooking_time_spent", Tag::Short(f.cooking_timer as i16))); entries.push(("cooking_total_time", Tag::Short(f.cooking_total as i16))); } + BlockEntity::Sign(sign) => entries.extend(sign.encode()), } Tag::compound(entries) } @@ -134,6 +135,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: f.cooking_timer = int("cooking_time_spent").unwrap_or(0); f.cooking_total = int("cooking_total_time").unwrap_or(200); } + BlockEntity::Sign(sign) => sign.decode(tag), } Some((pos, entity)) } diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs new file mode 100644 index 000000000..2d40391f9 --- /dev/null +++ b/crates/horizon-client/src/signs.rs @@ -0,0 +1,179 @@ +//! Sign block entities (`SignBlockEntity`, `SignText`): two four-line text +//! sides with a dye colour and glow, saved in vanilla's `front_text` / +//! `back_text` NBT layout. +use horizon_world::nbt::Tag; + +/// `DyeColor` names and `getTextColor` values by id. +pub const DYE_TEXT: [(&str, u32); 16] = [ + ("white", 0xFFFFFF), + ("orange", 0xFF681F), + ("magenta", 0xFF00FF), + ("light_blue", 0x9AC0CD), + ("yellow", 0xFFFF00), + ("lime", 0xBFFF00), + ("pink", 0xFF69B4), + ("gray", 0x808080), + ("light_gray", 0xD3D3D3), + ("cyan", 0x00FFFF), + ("purple", 0xA020F0), + ("blue", 0x0000FF), + ("brown", 0x8B4513), + ("green", 0x00FF00), + ("red", 0xFF0000), + ("black", 0x000000), +]; +const BLACK: u8 = 15; + +/// One sign side (`SignText`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SignText { + pub lines: [String; 4], + /// `DyeColor` id. + pub color: u8, + pub glowing: bool, +} +impl Default for SignText { + fn default() -> Self { + Self { lines: Default::default(), color: BLACK, glowing: false } + } +} +impl SignText { + pub fn is_empty(&self) -> bool { + self.lines.iter().all(String::is_empty) + } + /// `DyeColor.getTextColor` of this side. + pub fn text_color(&self) -> u32 { + DYE_TEXT[usize::from(self.color.min(15))].1 + } + /// `AbstractSignRenderer.getDarkColor`. + pub fn dark_color(&self) -> u32 { + let c = self.text_color(); + if c == 0 && self.glowing { + 0xF0EBCC + } else { + let s = |shift: u32| ((((c >> shift) & 255) as f32 * 0.4) as u32) << shift; + s(16) | s(8) | s(0) + } + } +} + +/// `SignBlockEntity` / `HangingSignBlockEntity` data. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SignData { + pub hanging: bool, + pub front: SignText, + pub back: SignText, + pub waxed: bool, +} +impl SignData { + pub fn id(&self) -> &'static str { + if self.hanging { "minecraft:hanging_sign" } else { "minecraft:sign" } + } + /// `SignBlockEntity.getMaxTextLineWidth`. + pub fn max_line_width(&self) -> f32 { + if self.hanging { 60.0 } else { 90.0 } + } + /// `SignBlockEntity.getTextLineHeight`. + pub fn line_height(&self) -> f32 { + if self.hanging { 9.0 } else { 10.0 } + } + /// NBT entries after the common block-entity header. + pub fn encode(&self) -> Vec<(&'static str, Tag)> { + let side = |t: &SignText| { + Tag::compound([ + ("messages", Tag::List(t.lines.iter().map(|l| Tag::String(l.as_str().into())).collect())), + ("color", Tag::String(DYE_TEXT[usize::from(t.color.min(15))].0.into())), + ("has_glowing_text", Tag::Byte(i8::from(t.glowing))), + ]) + }; + vec![("front_text", side(&self.front)), ("back_text", side(&self.back)), ("is_waxed", Tag::Byte(i8::from(self.waxed)))] + } + pub fn decode(&mut self, tag: &Tag) { + let side = |t: Option<&Tag>| -> SignText { + let mut out = SignText::default(); + let Some(t) = t else { return out }; + if let Some(Tag::List(messages)) = t.get("messages") { + for (line, m) in out.lines.iter_mut().zip(messages) { + *line = component_text(m); + } + } + if let Some(Tag::String(c)) = t.get("color") { + let name = c.to_string_lossy(); + if let Some(i) = DYE_TEXT.iter().position(|(n, _)| *n == name) { + out.color = i as u8; + } + } + out.glowing = matches!(t.get("has_glowing_text"), Some(Tag::Byte(b)) if *b != 0); + out + }; + self.front = side(tag.get("front_text")); + self.back = side(tag.get("back_text")); + self.waxed = matches!(tag.get("is_waxed"), Some(Tag::Byte(b)) if *b != 0); + } +} +/// Plain text of a stored text component (string, `{text: ...}` or JSON string). +fn component_text(tag: &Tag) -> String { + match tag { + Tag::String(s) => { + let s = s.to_string_lossy(); + match serde_json::from_str::(&s) { + Ok(serde_json::Value::String(text)) => text, + Ok(v) if v.get("text").is_some() => v["text"].as_str().unwrap_or_default().to_owned(), + _ => s, + } + } + Tag::Compound(_) => match tag.get("text") { + Some(Tag::String(t)) => t.to_string_lossy(), + _ => String::new(), + }, + _ => String::new(), + } +} +/// Whether a block name is a sign (standing, wall, hanging or wall hanging). +pub fn sign_kind(name: &str) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + if name == "hanging_sign" || name.ends_with("_hanging_sign") { + Some(true) + } else if name == "sign" || name.ends_with("_sign") { + Some(false) + } else { + None + } +} +/// Wood type of a sign block (`SignBlock.getWoodType`), for the editor texture. +pub fn wood_type(name: &str) -> &str { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + for suffix in ["_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign"] { + if let Some(wood) = name.strip_suffix(suffix) { + return wood; + } + } + "oak" +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn round_trips_nbt() { + let mut data = SignData { hanging: false, ..SignData::default() }; + data.front.lines[0] = "Hello".into(); + data.front.color = 14; + data.back.glowing = true; + let tag = Tag::compound(data.encode()); + let mut decoded = SignData::default(); + decoded.decode(&tag); + assert_eq!(decoded, data); + } + #[test] + fn names_and_colors() { + assert_eq!(sign_kind("minecraft:oak_wall_hanging_sign"), Some(true)); + assert_eq!(sign_kind("minecraft:sign"), Some(false)); + assert_eq!(sign_kind("minecraft:spruce_wall_sign"), Some(false)); + assert_eq!(sign_kind("minecraft:stone"), None); + assert_eq!(wood_type("minecraft:dark_oak_wall_sign"), "dark_oak"); + assert_eq!(SignText::default().dark_color(), 0); + let red = SignText { color: 14, ..SignText::default() }; + assert_eq!(red.dark_color(), 0x660000); + } +}