diff --git a/crates/horizon-client/examples/scoreboard_fixture.rs b/crates/horizon-client/examples/scoreboard_fixture.rs index e46a470ea..1fe5bab91 100644 --- a/crates/horizon-client/examples/scoreboard_fixture.rs +++ b/crates/horizon-client/examples/scoreboard_fixture.rs @@ -32,6 +32,7 @@ fn canon(tag: &Tag) -> Value { Tag::Long(v) => Value::String(format!("{v}L")), Tag::Float(v) => Value::String(format!("f:{v:x}")), Tag::Double(v) => Value::String(format!("d:{v:x}")), + Tag::IntArray(v) => json!({ "I;": v }), other => Value::String(format!("?{other:?}")), } } diff --git a/crates/horizon-client/examples/subtitle_fixture.rs b/crates/horizon-client/examples/subtitle_fixture.rs index b18405ec3..ac8e8d4d8 100644 --- a/crates/horizon-client/examples/subtitle_fixture.rs +++ b/crates/horizon-client/examples/subtitle_fixture.rs @@ -7,8 +7,9 @@ //! usage: subtitle_fixture RESOURCES INPUTS OUTPUT use horizon_client::{ hud::HudAtlas, + hud_layout::{GuiDraw, IDENTITY, background_color, pose_apply}, + hud_overlays::{SubtitleFrame, SubtitleOverlay}, lang, - subtitles::{Draw, Frame, SubtitleOverlay, background_color}, }; use serde_json::{Value, json}; use std::{fs, io::Write, path::PathBuf}; @@ -16,8 +17,8 @@ use std::{fs, io::Write, path::PathBuf}; fn vec3(v: &Value) -> [f64; 3] { std::array::from_fn(|i| v[i].as_f64().unwrap_or(0.0)) } -fn pose(t: [f32; 2]) -> Value { - json!([1.0, 0.0, 0.0, 1.0, t[0], t[1]]) +fn pose(m: [f32; 6]) -> Value { + json!(m) } fn main() -> Result<(), Box> { @@ -53,48 +54,62 @@ fn main() -> Result<(), Box> { } } "frame" => { - let frame = Frame { + let frame = SubtitleFrame { show: op["show"].as_bool().unwrap_or(false), position: vec3(&op["pos"]), forward: vec3(&op["forward"]), up: vec3(&op["up"]), multiplier: op["mult"].as_f64().unwrap_or(1.0), background: background_color( - 0.8, - op["opacity"].as_f64().unwrap_or(0.5) as f32, op["chat_only"].as_bool().unwrap_or(true), + op["opacity"].as_f64().unwrap_or(0.5), + 0.8, ), width: op["w"].as_i64().unwrap_or(0) as i32, height: op["h"].as_i64().unwrap_or(0) as i32, }; - let draws: Vec = overlay - .extract(&frame, &atlas.font, now) - .into_iter() - .map(|d| match d { - Draw::Stratum => json!({"type": "stratum"}), - Draw::Fill { + let mut stack = vec![IDENTITY]; + let mut draws = Vec::new(); + let calls = overlay.extract(&frame, &atlas.font, now); + if !calls.is_empty() { + draws.push(json!({"type": "stratum"})); + } + for d in calls { + let m = *stack.last().unwrap_or(&IDENTITY); + match d { + GuiDraw::Push(ops) => { + let mut top = m; + for op in ops { + pose_apply(&mut top, op); + } + stack.push(top); + } + GuiDraw::Pop => { + stack.pop(); + } + GuiDraw::Fill { x0, y0, x1, y1, color, - translate, - } => json!({ + } => draws.push(json!({ "type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, - "color": format!("{color:x}"), "pose": pose(translate), - }), - Draw::Text { + "color": format!("{color:x}"), "pose": pose(m), + })), + GuiDraw::Text { text, x, y, color, - translate, - } => json!({ + shadow, + } => draws.push(json!({ "type": "text", "text": text.plain(), "x": x, "y": y, - "color": format!("{color:x}"), "shadow": true, "pose": pose(translate), - }), - }) - .collect(); + "color": format!("{color:x}"), "shadow": shadow, "pose": pose(m), + })), + other => return Err(format!("unexpected draw {other:?}").into()), + } + } frames.push(Value::Array(draws)); } other => return Err(format!("op {other}").into()), diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs index 1f7f1ceaf..94b0d3c86 100644 --- a/crates/horizon-client/src/game/subtitle_hud.rs +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -4,8 +4,9 @@ //! option says). use super::Game; use horizon_client::{ - hud::{HudBatch, rgba}, - subtitles::{self, Draw, Frame, SubtitleOverlay}, + hud::HudBatch, + hud_layout, + hud_overlays::{SubtitleFrame, SubtitleOverlay, now_ms}, }; use std::cell::RefCell; @@ -24,7 +25,7 @@ impl Game<'_> { if !listening { return; } - let now = subtitles::now_ms(); + let now = now_ms(); for h in heard { let at = h.at.unwrap_or(self.audio.listener); overlay.on_play(Some(&h.subtitle), at, h.range, h.looping, now); @@ -36,67 +37,22 @@ impl Game<'_> { return; } let v = &self.view; - let frame = Frame { + let frame = SubtitleFrame { show: self.settings.show_subtitles, position: v.position, forward: v.forwards.map(f64::from), up: v.up.map(f64::from), multiplier: f64::from(self.settings.notification_display_time), - background: subtitles::background_color( - 0.8, - self.settings.text_background_opacity, - self.settings.file.bool("backgroundForChatOnly"), - ), + background: self.settings.text_background(0.8), width: batch.width as i32, height: batch.height as i32, }; let atlas = &self.res.atlas; - let draws = - self.subtitles - .overlay - .borrow_mut() - .extract(&frame, &atlas.font, subtitles::now_ms()); - let argb = |c: u32| { - let [a, r, g, b] = c.to_be_bytes(); - rgba(r, g, b, a) - }; - for d in draws { - match d { - Draw::Stratum => (), - Draw::Fill { - x0, - y0, - x1, - y1, - color, - translate: [tx, ty], - } => { - batch.fill( - atlas, - tx + x0 as f32, - ty + y0 as f32, - (x1 - x0) as f32, - (y1 - y0) as f32, - argb(color), - ); - } - Draw::Text { - text, - x, - y, - color, - translate: [tx, ty], - } => { - batch.text_styled( - atlas, - &text, - tx + x as f32, - ty + y as f32, - argb(color), - true, - ); - } - } - } + let draws = self + .subtitles + .overlay + .borrow_mut() + .extract(&frame, &atlas.font, now_ms()); + hud_layout::paint(batch, atlas, &draws); } } diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index 5982ea23d..8468735c3 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -4,8 +4,8 @@ //! timers of `Hud.tick`), the selected item name (`extractSelectedItemName` //! and its `toolHighlightTimer`), boss bars (`BossHealthOverlay`), the jump //! bar (`JumpableVehicleBar`), the scoreboard sidebar, item decorations -//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays and the -//! sleep overlay. +//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays, the +//! sleep overlay and the subtitles (`SubtitleOverlay`). use crate::{ font::Font, hud_layout::{ @@ -897,3 +897,328 @@ pub fn sleep_overlay(w: i32, h: i32, sleep_timer: i32) -> Vec { let color = (((220.0 * amount) as i32) << 24) as u32 | 0x10_1020; vec![fill(0, 0, w, h, color)] } + +// ---- subtitles (`SubtitleOverlay`) ------------------------------------------ +// +// Closed captions for the sounds the player could hear, with direction arrows +// and a fade over the notification display time. Like vanilla, the overlay +// listens to the sound engine only from the frame that renders it with the +// "Show Subtitles" option on until a frame renders with it off; turning it +// off keeps the captions it has (they show again if the option comes back +// before they expire). + +/// `SubtitleOverlay.DISPLAY_TIME` (milliseconds). +const DISPLAY_TIME: i64 = 3000; +/// `LOOPING_DISPLAY_FULL_BRIGHTNESS_TIME`: looping sounds stay at full brightness this long. +const LOOPING_FULL_BRIGHTNESS: i64 = 500; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct PlayedAt { + location: [f64; 3], + time: i64, +} +#[derive(Clone, Debug)] +struct Subtitle { + /// The translation key of the sound event's subtitle (`Component.translatable`). + key: String, + range: f32, + played: Vec, + looping: bool, +} +fn distance_sqr(a: [f64; 3], b: [f64; 3]) -> f64 { + let (dx, dy, dz) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]); + dx * dx + dy * dy + dz * dz +} +/// `Vec3.closerThan(pos, distance)`. +fn closer_than(a: [f64; 3], b: [f64; 3], range: f32) -> bool { + let r = f64::from(range); + distance_sqr(a, b) < r * r +} +/// `Vec3.equals`: `Double.compare` on each axis. +fn same_location(a: [f64; 3], b: [f64; 3]) -> bool { + let bits = |v: f64| { + if v.is_nan() { + f64::NAN.to_bits() + } else { + v.to_bits() + } + }; + (0..3).all(|i| bits(a[i]) == bits(b[i])) +} +impl Subtitle { + /// `getBestSubtitleCandidate`: the only play, else the latest in range + /// (the farthest of equally recent ones; the first among full ties). + fn best_candidate(&self, position: [f64; 3]) -> Option { + match self.played.as_slice() { + [] => None, + [only] => Some(*only), + many => many + .iter() + .filter(|p| closer_than(p.location, position, self.range)) + .fold(None, |best: Option, p| match best { + Some(b) + if b.time > p.time + || b.time == p.time + && distance_sqr(b.location, position).sqrt() + >= distance_sqr(p.location, position).sqrt() => + { + Some(b) + } + _ => Some(*p), + }), + } + } + fn refresh(&mut self, location: [f64; 3], now: i64) { + self.played.retain(|p| !same_location(location, p.location)); + self.played.push(PlayedAt { + location, + time: now, + }); + } + fn audible_from(&self, camera: [f64; 3]) -> bool { + if self.range.is_infinite() { + return true; + } + self.best_candidate(camera) + .is_some_and(|p| closer_than(camera, p.location, self.range)) + } + fn purge_old_instances(&mut self, max_age: f64, now: i64) { + self.played.retain(|p| ((now - p.time) as f64) <= max_age); + } + /// `getBrightness`: fades from 255 to 75 over the display time. + fn brightness(&self, at: PlayedAt, multiplier: f64, now: i64) -> i32 { + let full = if self.looping { + LOOPING_FULL_BRIGHTNESS + } else { + 0 + }; + let age = (now - at.time - full).max(0) as f32; + let t = age / (((DISPLAY_TIME - full) as f64) * multiplier) as f32; + let v = if t < 0.0 { + 255.0 + } else if t > 1.0 { + 75.0 + } else { + 255.0 + t * (75.0 - 255.0_f32) + }; + v.floor() as i32 + } +} + +/// What a frame needs to render the overlay: the sound listener, the +/// accessibility options and the GUI size. +#[derive(Clone, Copy, Debug)] +pub struct SubtitleFrame { + /// `options.showSubtitles`. + pub show: bool, + /// `SoundManager.getListenerTransform`: position, forward and up. + pub position: [f64; 3], + pub forward: [f64; 3], + pub up: [f64; 3], + /// `options.notificationDisplayTime`. + pub multiplier: f64, + /// `options.getBackgroundColor(0.8F)` (ARGB, `Settings::text_background`). + pub background: u32, + pub width: i32, + pub height: i32, +} +/// Milliseconds on a monotonic clock (`Util.getMillis`). +pub fn now_ms() -> i64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START + .get_or_init(std::time::Instant::now) + .elapsed() + .as_millis() as i64 +} +#[derive(Default)] +pub struct SubtitleOverlay { + subtitles: Vec, + listening: bool, +} +impl SubtitleOverlay { + /// Whether the overlay is one of the sound engine's listeners. + pub fn listening(&self) -> bool { + self.listening + } + /// `onPlaySound` for a sound the engine played while the overlay listens: + /// a subtitle already listed (by its text) refreshes its location. + pub fn on_play( + &mut self, + subtitle: Option<&str>, + location: [f64; 3], + range: f32, + looping: bool, + now: i64, + ) { + let Some(key) = subtitle else { + return; + }; + if let Some(s) = self.subtitles.iter_mut().find(|s| s.key == key) { + s.refresh(location, now); + return; + } + self.subtitles.push(Subtitle { + key: key.to_owned(), + range, + played: vec![PlayedAt { + location, + time: now, + }], + looping, + }); + } + /// `extractRenderState`: starts or stops listening as the option says, + /// forgets old plays and lays out the boxes at the bottom right. + pub fn extract(&mut self, frame: &SubtitleFrame, font: &Font, now: i64) -> Vec { + let mut out = Vec::new(); + if self.listening != frame.show { + self.listening = frame.show; + } + if !self.listening { + return out; + } + let position = frame.position; + let (f, u) = (frame.forward, frame.up); + // ListenerTransform.right: forward x up. + let right = [ + f[1] * u[2] - f[2] * u[1], + f[2] * u[0] - f[0] * u[2], + f[0] * u[1] - f[1] * u[0], + ]; + let width_of = |t: &Text| width(font, t); + let mut audible = Vec::new(); + let mut width = 0; + for (i, s) in self.subtitles.iter_mut().enumerate() { + if !s.played.is_empty() { + s.purge_old_instances(3000.0 * frame.multiplier, now); + } + if s.audible_from(position) && !s.played.is_empty() { + width = width.max(width_of(&Text::translate(&s.key, &[]))); + audible.push(i); + } + } + if audible.is_empty() { + return out; + } + let w = |s: &str| font.width(s) as i32; + width += w("<") + w(" ") + w(">") + w(" "); + let mut row = 0; + for i in audible { + let s = &self.subtitles[i]; + let text_value = Text::translate(&s.key, &[]); + let Some(closest) = s.best_candidate(position) else { + continue; + }; + let mut delta = [ + closest.location[0] - position[0], + closest.location[1] - position[1], + closest.location[2] - position[2], + ]; + // Vec3.normalize. + let length = distance_sqr(delta, [0.0; 3]).sqrt(); + delta = if length < f64::from(1.0e-5_f32) { + [0.0; 3] + } else { + delta.map(|v| v / length) + }; + let dot = |a: [f64; 3]| a[0] * delta[0] + a[1] * delta[1] + a[2] * delta[2]; + let (rightness, forwardness) = (dot(right), dot(f)); + let in_view = forwardness > 0.5; + let half_width = width / 2; + let height = 9; + let half_height = height / 2; + let text_width = width_of(&text_value); + let brightness = s.brightness(closest, frame.multiplier, now); + out.push(GuiDraw::Push(vec![ + PoseOp::Translate( + frame.width as f32 - half_width as f32 * 1.0 - 2.0, + (frame.height - 35) as f32 - (row * (height + 1)) as f32 * 1.0, + ), + PoseOp::Scale(1.0, 1.0), + ])); + out.push(fill( + -half_width - 1, + -half_height - 1, + half_width + 1, + half_height + 1, + frame.background, + )); + let b = brightness as u32 & 0xFF; + let color = 0xFF00_0000 | b << 16 | b << 8 | b; + if !in_view { + if rightness > 0.0 { + text( + &mut out, + Text::literal(">"), + half_width - w(">"), + -half_height, + color, + true, + ); + } else if rightness < 0.0 { + text( + &mut out, + Text::literal("<"), + -half_width, + -half_height, + color, + true, + ); + } + } + text( + &mut out, + text_value, + -text_width / 2, + -half_height, + color, + true, + ); + out.push(GuiDraw::Pop); + row += 1; + } + out + } +} + +#[cfg(test)] +mod subtitle_tests { + use super::*; + + #[test] + fn candidates_and_brightness() { + let mut s = Subtitle { + key: "a".into(), + range: 16.0, + played: vec![PlayedAt { + location: [0.0, 0.0, 3.0], + time: 1000, + }], + looping: false, + }; + assert_eq!(s.brightness(s.played[0], 1.0, 1000), 255); + assert_eq!(s.brightness(s.played[0], 1.0, 2500), 165); + assert_eq!(s.brightness(s.played[0], 2.0, 2500), 210); + assert_eq!(s.brightness(s.played[0], 1.0, 9000), 75); + // Equally recent plays: the farthest in range wins. + s.refresh([0.0, 0.0, 5.0], 1000); + s.refresh([0.0, 0.0, 40.0], 1000); + let best = s.best_candidate([0.0; 3]).unwrap(); + assert_eq!(best.location, [0.0, 0.0, 5.0]); + s.purge_old_instances(3000.0, 4001); + assert!(s.played.is_empty()); + assert!(!s.audible_from([0.0; 3])); + } + + #[test] + fn listening_follows_the_option() { + let mut o = SubtitleOverlay::default(); + o.on_play(Some("a"), [0.0; 3], 16.0, false, 0); + assert_eq!(o.subtitles.len(), 1); + o.on_play(None, [0.0; 3], 16.0, false, 0); + o.on_play(Some("a"), [1.0; 3], 16.0, false, 5); + assert_eq!(o.subtitles.len(), 1); + assert_eq!(o.subtitles[0].played.len(), 2); + assert!(!o.listening()); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index c3b63dca8..65d2f2667 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -100,7 +100,6 @@ pub mod stations; pub mod stopwatches; pub mod streaming; pub mod structure_blocks; -pub mod subtitles; pub mod testgen; pub mod text; pub mod title; diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client/src/scoreboard.rs index 17ea69d72..6afba19ad 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client/src/scoreboard.rs @@ -169,7 +169,9 @@ impl NumberFormat { } } pub fn to_tag(&self) -> Tag { - json_to_tag(&self.to_json()) + let mut tag = json_to_tag(&self.to_json()); + entity_uuids(&mut tag); + tag } pub fn from_tag(t: &Tag) -> Option { Self::from_json(&tag_to_json(t)) @@ -1243,7 +1245,41 @@ impl Scoreboard { /// A component as `ComponentSerialization.CODEC` writes it to NBT. pub fn component_tag(c: &Comp) -> Tag { - json_to_tag(&canonical_component(c)) + let mut tag = json_to_tag(&canonical_component(c)); + entity_uuids(&mut tag); + tag +} +/// `HoverEvent.ShowEntity` writes its UUID with `UUIDUtil.CODEC`: an int array. +fn entity_uuids(tag: &mut Tag) { + match tag { + Tag::Compound(c) => { + let show_entity = matches!(c.get(&"action".into()), Some(Tag::String(a)) if a.to_string_lossy() == "show_entity"); + for (k, v) in c.iter_mut() { + if show_entity && k.to_string_lossy() == "uuid" { + let ints = match v { + Tag::List(l) => l + .iter() + .map(|t| match t { + Tag::Int(i) => Some(*i), + _ => None, + }) + .collect::>>(), + Tag::String(s) => { + crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from) + } + _ => None, + }; + if let Some(ints) = ints.filter(|i| i.len() == 4) { + *v = Tag::IntArray(ints); + } + } else { + entity_uuids(v); + } + } + } + Tag::List(l) => l.iter_mut().for_each(entity_uuids), + _ => {} + } } /// A style object as `Style.Serializer.MAP_CODEC` re-encodes it. diff --git a/crates/horizon-client/src/subtitles.rs b/crates/horizon-client/src/subtitles.rs deleted file mode 100644 index 1b0c9284b..000000000 --- a/crates/horizon-client/src/subtitles.rs +++ /dev/null @@ -1,357 +0,0 @@ -//! The subtitle overlay (`SubtitleOverlay`): closed captions for the sounds -//! the player could hear, with direction arrows and a fade over the -//! notification display time. -//! -//! Like vanilla, the overlay listens to the sound engine only from the frame -//! that renders it with the "Show Subtitles" option on until a frame renders -//! with it off; turning it off keeps the captions it has (they show again if -//! the option comes back before they expire). -use crate::{font::Font, text::Text}; - -/// `SubtitleOverlay.DISPLAY_TIME` (milliseconds). -const DISPLAY_TIME: i64 = 3000; -/// `LOOPING_DISPLAY_FULL_BRIGHTNESS_TIME`: looping sounds stay at full brightness this long. -const LOOPING_FULL_BRIGHTNESS: i64 = 500; - -#[derive(Clone, Copy, Debug, PartialEq)] -struct PlayedAt { - location: [f64; 3], - time: i64, -} -#[derive(Clone, Debug)] -struct Subtitle { - /// The translation key of the sound event's subtitle (`Component.translatable`). - key: String, - range: f32, - played: Vec, - looping: bool, -} -fn distance_sqr(a: [f64; 3], b: [f64; 3]) -> f64 { - let (dx, dy, dz) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]); - dx * dx + dy * dy + dz * dz -} -/// `Vec3.closerThan(pos, distance)`. -fn closer_than(a: [f64; 3], b: [f64; 3], range: f32) -> bool { - let r = f64::from(range); - distance_sqr(a, b) < r * r -} -/// `Vec3.equals`: `Double.compare` on each axis. -fn same_location(a: [f64; 3], b: [f64; 3]) -> bool { - let bits = |v: f64| { - if v.is_nan() { - f64::NAN.to_bits() - } else { - v.to_bits() - } - }; - (0..3).all(|i| bits(a[i]) == bits(b[i])) -} -impl Subtitle { - /// `getBestSubtitleCandidate`: the only play, else the latest in range - /// (the farthest of equally recent ones; the first among full ties). - fn best_candidate(&self, position: [f64; 3]) -> Option { - match self.played.as_slice() { - [] => None, - [only] => Some(*only), - many => many - .iter() - .filter(|p| closer_than(p.location, position, self.range)) - .fold(None, |best: Option, p| match best { - Some(b) - if b.time > p.time - || b.time == p.time - && distance_sqr(b.location, position).sqrt() - >= distance_sqr(p.location, position).sqrt() => - { - Some(b) - } - _ => Some(*p), - }), - } - } - fn refresh(&mut self, location: [f64; 3], now: i64) { - self.played.retain(|p| !same_location(location, p.location)); - self.played.push(PlayedAt { - location, - time: now, - }); - } - fn audible_from(&self, camera: [f64; 3]) -> bool { - if self.range.is_infinite() { - return true; - } - self.best_candidate(camera) - .is_some_and(|p| closer_than(camera, p.location, self.range)) - } - fn purge_old_instances(&mut self, max_age: f64, now: i64) { - self.played.retain(|p| ((now - p.time) as f64) <= max_age); - } - /// `getBrightness`: fades from 255 to 75 over the display time. - fn brightness(&self, at: PlayedAt, multiplier: f64, now: i64) -> i32 { - let full = if self.looping { - LOOPING_FULL_BRIGHTNESS - } else { - 0 - }; - let age = (now - at.time - full).max(0) as f32; - let t = age / (((DISPLAY_TIME - full) as f64) * multiplier) as f32; - let v = if t < 0.0 { - 255.0 - } else if t > 1.0 { - 75.0 - } else { - 255.0 + t * (75.0 - 255.0_f32) - }; - v.floor() as i32 - } -} - -/// What a frame needs to render the overlay: the sound listener, the -/// accessibility options and the GUI size. -#[derive(Clone, Copy, Debug)] -pub struct Frame { - /// `options.showSubtitles`. - pub show: bool, - /// `SoundManager.getListenerTransform`: position, forward and up. - pub position: [f64; 3], - pub forward: [f64; 3], - pub up: [f64; 3], - /// `options.notificationDisplayTime`. - pub multiplier: f64, - /// `options.getBackgroundColor(0.8F)` (ARGB). - pub background: u32, - pub width: i32, - pub height: i32, -} -/// `Options.getBackgroundColor(defaultOpacity)`: the text background opacity -/// unless the background is for chat only. -pub fn background_color( - default_opacity: f32, - text_background_opacity: f32, - chat_only: bool, -) -> u32 { - let alpha = if chat_only { - default_opacity - } else { - text_background_opacity - }; - ((alpha * 255.0).floor() as i32 as u32) << 24 -} -/// One call the overlay makes, with the pose translation it is made under. -#[derive(Clone, Debug, PartialEq)] -pub enum Draw { - /// `graphics.nextStratum()`. - Stratum, - Fill { - x0: i32, - y0: i32, - x1: i32, - y1: i32, - color: u32, - translate: [f32; 2], - }, - /// Text with a drop shadow. - Text { - text: Text, - x: i32, - y: i32, - color: u32, - translate: [f32; 2], - }, -} - -/// Milliseconds on a monotonic clock (`Util.getMillis`). -pub fn now_ms() -> i64 { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - START - .get_or_init(std::time::Instant::now) - .elapsed() - .as_millis() as i64 -} -#[derive(Default)] -pub struct SubtitleOverlay { - subtitles: Vec, - listening: bool, -} -impl SubtitleOverlay { - /// Whether the overlay is one of the sound engine's listeners. - pub fn listening(&self) -> bool { - self.listening - } - /// `onPlaySound` for a sound the engine played while the overlay listens: - /// a subtitle already listed (by its text) refreshes its location. - pub fn on_play( - &mut self, - subtitle: Option<&str>, - location: [f64; 3], - range: f32, - looping: bool, - now: i64, - ) { - let Some(key) = subtitle else { - return; - }; - if let Some(s) = self.subtitles.iter_mut().find(|s| s.key == key) { - s.refresh(location, now); - return; - } - self.subtitles.push(Subtitle { - key: key.to_owned(), - range, - played: vec![PlayedAt { - location, - time: now, - }], - looping, - }); - } - /// `extractRenderState`: starts or stops listening as the option says, - /// forgets old plays and lays out the boxes at the bottom right. - pub fn extract(&mut self, frame: &Frame, font: &Font, now: i64) -> Vec { - let mut out = Vec::new(); - if self.listening != frame.show { - self.listening = frame.show; - } - if !self.listening { - return out; - } - let position = frame.position; - let (f, u) = (frame.forward, frame.up); - // ListenerTransform.right: forward x up. - let right = [ - f[1] * u[2] - f[2] * u[1], - f[2] * u[0] - f[0] * u[2], - f[0] * u[1] - f[1] * u[0], - ]; - let width_of = |t: &Text| font.width_text(t) as i32; - let mut audible = Vec::new(); - let mut width = 0; - for (i, s) in self.subtitles.iter_mut().enumerate() { - if !s.played.is_empty() { - s.purge_old_instances(3000.0 * frame.multiplier, now); - } - if s.audible_from(position) && !s.played.is_empty() { - width = width.max(width_of(&Text::translate(&s.key, &[]))); - audible.push(i); - } - } - if audible.is_empty() { - return out; - } - let w = |s: &str| font.width(s) as i32; - width += w("<") + w(" ") + w(">") + w(" "); - out.push(Draw::Stratum); - let mut row = 0; - for i in audible { - let s = &self.subtitles[i]; - let text = Text::translate(&s.key, &[]); - let Some(closest) = s.best_candidate(position) else { - continue; - }; - let mut delta = [ - closest.location[0] - position[0], - closest.location[1] - position[1], - closest.location[2] - position[2], - ]; - // Vec3.normalize. - let length = distance_sqr(delta, [0.0; 3]).sqrt(); - delta = if length < f64::from(1.0e-5_f32) { - [0.0; 3] - } else { - delta.map(|v| v / length) - }; - let dot = |a: [f64; 3]| a[0] * delta[0] + a[1] * delta[1] + a[2] * delta[2]; - let (rightness, forwardness) = (dot(right), dot(f)); - let in_view = forwardness > 0.5; - let half_width = width / 2; - let height = 9; - let half_height = height / 2; - let text_width = width_of(&text); - let brightness = s.brightness(closest, frame.multiplier, now); - let translate = [ - frame.width as f32 - half_width as f32 * 1.0 - 2.0, - (frame.height - 35) as f32 - (row * (height + 1)) as f32 * 1.0, - ]; - out.push(Draw::Fill { - x0: -half_width - 1, - y0: -half_height - 1, - x1: half_width + 1, - y1: half_height + 1, - color: frame.background, - translate, - }); - let b = brightness as u32 & 0xFF; - let color = 0xFF00_0000 | b << 16 | b << 8 | b; - if !in_view { - if rightness > 0.0 { - out.push(Draw::Text { - text: Text::literal(">"), - x: half_width - w(">"), - y: -half_height, - color, - translate, - }); - } else if rightness < 0.0 { - out.push(Draw::Text { - text: Text::literal("<"), - x: -half_width, - y: -half_height, - color, - translate, - }); - } - } - out.push(Draw::Text { - text, - x: -text_width / 2, - y: -half_height, - color, - translate, - }); - row += 1; - } - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn candidates_and_brightness() { - let mut s = Subtitle { - key: "a".into(), - range: 16.0, - played: vec![PlayedAt { - location: [0.0, 0.0, 3.0], - time: 1000, - }], - looping: false, - }; - assert_eq!(s.brightness(s.played[0], 1.0, 1000), 255); - assert_eq!(s.brightness(s.played[0], 1.0, 2500), 165); - assert_eq!(s.brightness(s.played[0], 2.0, 2500), 210); - assert_eq!(s.brightness(s.played[0], 1.0, 9000), 75); - // Equally recent plays: the farthest in range wins. - s.refresh([0.0, 0.0, 5.0], 1000); - s.refresh([0.0, 0.0, 40.0], 1000); - let best = s.best_candidate([0.0; 3]).unwrap(); - assert_eq!(best.location, [0.0, 0.0, 5.0]); - s.purge_old_instances(3000.0, 4001); - assert!(s.played.is_empty()); - assert!(!s.audible_from([0.0; 3])); - } - - #[test] - fn listening_follows_the_option() { - let mut o = SubtitleOverlay::default(); - o.on_play(Some("a"), [0.0; 3], 16.0, false, 0); - assert_eq!(o.subtitles.len(), 1); - o.on_play(None, [0.0; 3], 16.0, false, 0); - o.on_play(Some("a"), [1.0; 3], 16.0, false, 5); - assert_eq!(o.subtitles.len(), 1); - assert_eq!(o.subtitles[0].played.len(), 2); - assert!(!o.listening()); - } -} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScoreboardOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScoreboardOracle.java index 061013345..f76385193 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScoreboardOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaScoreboardOracle.java @@ -98,6 +98,15 @@ public final class VanillaScoreboardOracle { if (tag instanceof DoubleTag d) { return new JsonPrimitive("d:" + Long.toHexString(Double.doubleToRawLongBits(d.value()))); } + if (tag instanceof IntArrayTag a) { + JsonObject o = new JsonObject(); + JsonArray v = new JsonArray(); + for (int i : a.getAsIntArray()) { + v.add(i); + } + o.add("I;", v); + return o; + } return new JsonPrimitive("?" + tag.getType().getName()); } diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index a3798b28c..11dfdae56 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -176,6 +176,59 @@ def block_position(i): return 2 + 3 * (i % 10), -60, 2 + 3 * (i // 10) +SCOREBOARD = [ + 'scoreboard objectives add kills totalKillCount {"text":"Kills","color":"red"}', + 'scoreboard objectives add d dummy', + 'scoreboard objectives add hearts dummy "Hearts"', + 'scoreboard objectives modify hearts rendertype hearts', + 'scoreboard objectives add t trigger', + 'scoreboard objectives add mined minecraft.mined:minecraft.stone', + 'scoreboard objectives modify d displayautoupdate true', + 'scoreboard objectives modify d numberformat styled {"color":"gold","bold":true}', + 'scoreboard objectives modify kills numberformat blank', + 'scoreboard objectives setdisplay sidebar d', + 'scoreboard objectives setdisplay below_name hearts', + 'scoreboard objectives setdisplay sidebar.team.red kills', + 'scoreboard players set #fake d 5', + 'scoreboard players set Alex d -3', + 'scoreboard players set Alex kills 7', + 'scoreboard players set Alex hearts 0', + 'scoreboard players set Steve hearts 12', + 'scoreboard players add {uuid0} d 2', + 'scoreboard players display name Alex d {"text":"Alexandra","italic":true}', + 'scoreboard players display numberformat Alex hearts fixed "lots"', + 'scoreboard players enable Alex t', + 'scoreboard players set Steve t 3', + 'team add red {"text":"Red Team"}', + 'team modify red color red', + 'team modify red prefix "[R] "', + 'team modify red suffix {"text":" *","color":"gold"}', + 'team modify red friendlyFire false', + 'team modify red seeFriendlyInvisibles false', + 'team modify red nametagVisibility hideForOtherTeams', + 'team modify red deathMessageVisibility never', + 'team modify red collisionRule pushOwnTeam', + 'team join red Alex', + 'team join red #fake', + 'team add blue', + 'team join blue {uuid0}', + 'team join blue Steve', +] + + +def normalize_scoreboard(data): + """Each holder's scores sit in an identity-hash map in vanilla: compare them as a set.""" + scores = data.get('data', {}).get('PlayerScores') if isinstance(data, dict) else None + if isinstance(scores, list): + order = [] + for row in scores: + if row.get('Name') not in order: + order.append(row.get('Name')) + data['data']['PlayerScores'] = sorted( + scores, key=lambda r: (order.index(r.get('Name')), json.dumps(r, sort_keys=True, default=str))) + return data + + def build_world(directory): """Fill a fresh vanilla world; returns the failed scene commands.""" server = Vanilla(directory) @@ -199,6 +252,12 @@ def build_world(directory): out = server.run(command) if command_failed(out): failed.append((command, out)) + # A scoreboard with every kind of saved field (scoreboard.dat). No criteria that + # Horizon's own player (not the bot) would update while it runs. + for command in SCOREBOARD: + out = server.run(command.replace('{uuid0}', entity_uuid_text(0))) + if command_failed(out): + failed.append((command, out)) server.run('time set 6000') server.run('gamerule advance_time false') server.run('gamerule advance_weather false') @@ -472,7 +531,10 @@ def compare_worlds(vanilla, horizon): if not b.exists(): report.append((rel, 'present', 'missing from Horizon')) elif a.exists(): - compare_dat(rel, anvil_dump.read_dat(str(a)), anvil_dump.read_dat(str(b)), report) + va, hb = anvil_dump.read_dat(str(a)), anvil_dump.read_dat(str(b)) + if rel.endswith('scoreboard.dat'): + va, hb = normalize_scoreboard(va), normalize_scoreboard(hb) + compare_dat(rel, va, hb, report) return report diff --git a/tools/test_scoreboard_parity.py b/tools/test_scoreboard_parity.py index 7bb23f2c8..8a035eb17 100644 --- a/tools/test_scoreboard_parity.py +++ b/tools/test_scoreboard_parity.py @@ -72,6 +72,9 @@ def components(rng, name=None): lambda: {'type': 'text', 'text': 'typed'}, lambda: {'keybind': 'key.jump'}, lambda: {'text': 'strike', 'strikethrough': True, 'obfuscated': False}, + lambda: {'text': name or 'E', 'hover_event': {'action': 'show_entity', 'id': 'minecraft:pig', + 'uuid': [rng.randint(-9, 9) for _ in range(4)]}}, + lambda: {'text': 'tip', 'hover_event': {'action': 'show_text', 'value': {'text': 'hi', 'color': 'red'}}}, ] return rng.choice(choices)()